LLVM  13.0.0git
LLParser.cpp
Go to the documentation of this file.
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the parser class for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Value.h"
41 #include "llvm/Support/Casting.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <cstring>
49 #include <iterator>
50 #include <vector>
51 
52 using namespace llvm;
53 
54 static std::string getTypeString(Type *T) {
55  std::string Result;
56  raw_string_ostream Tmp(Result);
57  Tmp << *T;
58  return Tmp.str();
59 }
60 
61 /// Run: module ::= toplevelentity*
63  DataLayoutCallbackTy DataLayoutCallback) {
64  // Prime the lexer.
65  Lex.Lex();
66 
67  if (Context.shouldDiscardValueNames())
68  return error(
69  Lex.getLoc(),
70  "Can't read textual IR with a Context that discards named Values");
71 
72  if (M) {
73  if (parseTargetDefinitions())
74  return true;
75 
76  if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
77  M->setDataLayout(*LayoutOverride);
78  }
79 
80  return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
81  validateEndOfIndex();
82 }
83 
85  const SlotMapping *Slots) {
86  restoreParsingState(Slots);
87  Lex.Lex();
88 
89  Type *Ty = nullptr;
90  if (parseType(Ty) || parseConstantValue(Ty, C))
91  return true;
92  if (Lex.getKind() != lltok::Eof)
93  return error(Lex.getLoc(), "expected end of string");
94  return false;
95 }
96 
97 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
98  const SlotMapping *Slots) {
99  restoreParsingState(Slots);
100  Lex.Lex();
101 
102  Read = 0;
103  SMLoc Start = Lex.getLoc();
104  Ty = nullptr;
105  if (parseType(Ty))
106  return true;
107  SMLoc End = Lex.getLoc();
108  Read = End.getPointer() - Start.getPointer();
109 
110  return false;
111 }
112 
113 void LLParser::restoreParsingState(const SlotMapping *Slots) {
114  if (!Slots)
115  return;
116  NumberedVals = Slots->GlobalValues;
117  NumberedMetadata = Slots->MetadataNodes;
118  for (const auto &I : Slots->NamedTypes)
119  NamedTypes.insert(
120  std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
121  for (const auto &I : Slots->Types)
122  NumberedTypes.insert(
123  std::make_pair(I.first, std::make_pair(I.second, LocTy())));
124 }
125 
126 /// validateEndOfModule - Do final validity and sanity checks at the end of the
127 /// module.
128 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
129  if (!M)
130  return false;
131  // Handle any function attribute group forward references.
132  for (const auto &RAG : ForwardRefAttrGroups) {
133  Value *V = RAG.first;
134  const std::vector<unsigned> &Attrs = RAG.second;
135  AttrBuilder B;
136 
137  for (const auto &Attr : Attrs)
138  B.merge(NumberedAttrBuilders[Attr]);
139 
140  if (Function *Fn = dyn_cast<Function>(V)) {
141  AttributeList AS = Fn->getAttributes();
142  AttrBuilder FnAttrs(AS.getFnAttributes());
144 
145  FnAttrs.merge(B);
146 
147  // If the alignment was parsed as an attribute, move to the alignment
148  // field.
149  if (FnAttrs.hasAlignmentAttr()) {
150  Fn->setAlignment(FnAttrs.getAlignment());
151  FnAttrs.removeAttribute(Attribute::Alignment);
152  }
153 
155  AttributeSet::get(Context, FnAttrs));
156  Fn->setAttributes(AS);
157  } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
158  AttributeList AS = CI->getAttributes();
159  AttrBuilder FnAttrs(AS.getFnAttributes());
161  FnAttrs.merge(B);
163  AttributeSet::get(Context, FnAttrs));
164  CI->setAttributes(AS);
165  } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
166  AttributeList AS = II->getAttributes();
167  AttrBuilder FnAttrs(AS.getFnAttributes());
169  FnAttrs.merge(B);
171  AttributeSet::get(Context, FnAttrs));
172  II->setAttributes(AS);
173  } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
174  AttributeList AS = CBI->getAttributes();
175  AttrBuilder FnAttrs(AS.getFnAttributes());
177  FnAttrs.merge(B);
179  AttributeSet::get(Context, FnAttrs));
180  CBI->setAttributes(AS);
181  } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
182  AttrBuilder Attrs(GV->getAttributes());
183  Attrs.merge(B);
184  GV->setAttributes(AttributeSet::get(Context,Attrs));
185  } else {
186  llvm_unreachable("invalid object with forward attribute group reference");
187  }
188  }
189 
190  // If there are entries in ForwardRefBlockAddresses at this point, the
191  // function was never defined.
192  if (!ForwardRefBlockAddresses.empty())
193  return error(ForwardRefBlockAddresses.begin()->first.Loc,
194  "expected function name in blockaddress");
195 
196  for (const auto &NT : NumberedTypes)
197  if (NT.second.second.isValid())
198  return error(NT.second.second,
199  "use of undefined type '%" + Twine(NT.first) + "'");
200 
201  for (StringMap<std::pair<Type*, LocTy> >::iterator I =
202  NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
203  if (I->second.second.isValid())
204  return error(I->second.second,
205  "use of undefined type named '" + I->getKey() + "'");
206 
207  if (!ForwardRefComdats.empty())
208  return error(ForwardRefComdats.begin()->second,
209  "use of undefined comdat '$" +
210  ForwardRefComdats.begin()->first + "'");
211 
212  if (!ForwardRefVals.empty())
213  return error(ForwardRefVals.begin()->second.second,
214  "use of undefined value '@" + ForwardRefVals.begin()->first +
215  "'");
216 
217  if (!ForwardRefValIDs.empty())
218  return error(ForwardRefValIDs.begin()->second.second,
219  "use of undefined value '@" +
220  Twine(ForwardRefValIDs.begin()->first) + "'");
221 
222  if (!ForwardRefMDNodes.empty())
223  return error(ForwardRefMDNodes.begin()->second.second,
224  "use of undefined metadata '!" +
225  Twine(ForwardRefMDNodes.begin()->first) + "'");
226 
227  // Resolve metadata cycles.
228  for (auto &N : NumberedMetadata) {
229  if (N.second && !N.second->isResolved())
230  N.second->resolveCycles();
231  }
232 
233  for (auto *Inst : InstsWithTBAATag) {
234  MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
235  assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
236  auto *UpgradedMD = UpgradeTBAANode(*MD);
237  if (MD != UpgradedMD)
238  Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
239  }
240 
241  // Look for intrinsic functions and CallInst that need to be upgraded
242  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
243  UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
244 
245  // Some types could be renamed during loading if several modules are
246  // loaded in the same LLVMContext (LTO scenario). In this case we should
247  // remangle intrinsics names as well.
248  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
249  Function *F = &*FI++;
250  if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
251  F->replaceAllUsesWith(Remangled.getValue());
252  F->eraseFromParent();
253  }
254  }
255 
256  if (UpgradeDebugInfo)
258 
259  UpgradeModuleFlags(*M);
261 
262  if (!Slots)
263  return false;
264  // Initialize the slot mapping.
265  // Because by this point we've parsed and validated everything, we can "steal"
266  // the mapping from LLParser as it doesn't need it anymore.
267  Slots->GlobalValues = std::move(NumberedVals);
268  Slots->MetadataNodes = std::move(NumberedMetadata);
269  for (const auto &I : NamedTypes)
270  Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
271  for (const auto &I : NumberedTypes)
272  Slots->Types.insert(std::make_pair(I.first, I.second.first));
273 
274  return false;
275 }
276 
277 /// Do final validity and sanity checks at the end of the index.
278 bool LLParser::validateEndOfIndex() {
279  if (!Index)
280  return false;
281 
282  if (!ForwardRefValueInfos.empty())
283  return error(ForwardRefValueInfos.begin()->second.front().second,
284  "use of undefined summary '^" +
285  Twine(ForwardRefValueInfos.begin()->first) + "'");
286 
287  if (!ForwardRefAliasees.empty())
288  return error(ForwardRefAliasees.begin()->second.front().second,
289  "use of undefined summary '^" +
290  Twine(ForwardRefAliasees.begin()->first) + "'");
291 
292  if (!ForwardRefTypeIds.empty())
293  return error(ForwardRefTypeIds.begin()->second.front().second,
294  "use of undefined type id summary '^" +
295  Twine(ForwardRefTypeIds.begin()->first) + "'");
296 
297  return false;
298 }
299 
300 //===----------------------------------------------------------------------===//
301 // Top-Level Entities
302 //===----------------------------------------------------------------------===//
303 
304 bool LLParser::parseTargetDefinitions() {
305  while (true) {
306  switch (Lex.getKind()) {
307  case lltok::kw_target:
308  if (parseTargetDefinition())
309  return true;
310  break;
312  if (parseSourceFileName())
313  return true;
314  break;
315  default:
316  return false;
317  }
318  }
319 }
320 
321 bool LLParser::parseTopLevelEntities() {
322  // If there is no Module, then parse just the summary index entries.
323  if (!M) {
324  while (true) {
325  switch (Lex.getKind()) {
326  case lltok::Eof:
327  return false;
328  case lltok::SummaryID:
329  if (parseSummaryEntry())
330  return true;
331  break;
333  if (parseSourceFileName())
334  return true;
335  break;
336  default:
337  // Skip everything else
338  Lex.Lex();
339  }
340  }
341  }
342  while (true) {
343  switch (Lex.getKind()) {
344  default:
345  return tokError("expected top-level entity");
346  case lltok::Eof: return false;
347  case lltok::kw_declare:
348  if (parseDeclare())
349  return true;
350  break;
351  case lltok::kw_define:
352  if (parseDefine())
353  return true;
354  break;
355  case lltok::kw_module:
356  if (parseModuleAsm())
357  return true;
358  break;
359  case lltok::kw_deplibs:
360  if (parseDepLibs())
361  return true;
362  break;
363  case lltok::LocalVarID:
364  if (parseUnnamedType())
365  return true;
366  break;
367  case lltok::LocalVar:
368  if (parseNamedType())
369  return true;
370  break;
371  case lltok::GlobalID:
372  if (parseUnnamedGlobal())
373  return true;
374  break;
375  case lltok::GlobalVar:
376  if (parseNamedGlobal())
377  return true;
378  break;
379  case lltok::ComdatVar: if (parseComdat()) return true; break;
380  case lltok::exclaim:
381  if (parseStandaloneMetadata())
382  return true;
383  break;
384  case lltok::SummaryID:
385  if (parseSummaryEntry())
386  return true;
387  break;
388  case lltok::MetadataVar:
389  if (parseNamedMetadata())
390  return true;
391  break;
393  if (parseUnnamedAttrGrp())
394  return true;
395  break;
397  if (parseUseListOrder())
398  return true;
399  break;
401  if (parseUseListOrderBB())
402  return true;
403  break;
404  }
405  }
406 }
407 
408 /// toplevelentity
409 /// ::= 'module' 'asm' STRINGCONSTANT
410 bool LLParser::parseModuleAsm() {
411  assert(Lex.getKind() == lltok::kw_module);
412  Lex.Lex();
413 
414  std::string AsmStr;
415  if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
416  parseStringConstant(AsmStr))
417  return true;
418 
419  M->appendModuleInlineAsm(AsmStr);
420  return false;
421 }
422 
423 /// toplevelentity
424 /// ::= 'target' 'triple' '=' STRINGCONSTANT
425 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
426 bool LLParser::parseTargetDefinition() {
427  assert(Lex.getKind() == lltok::kw_target);
428  std::string Str;
429  switch (Lex.Lex()) {
430  default:
431  return tokError("unknown target property");
432  case lltok::kw_triple:
433  Lex.Lex();
434  if (parseToken(lltok::equal, "expected '=' after target triple") ||
435  parseStringConstant(Str))
436  return true;
437  M->setTargetTriple(Str);
438  return false;
440  Lex.Lex();
441  if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
442  parseStringConstant(Str))
443  return true;
444  M->setDataLayout(Str);
445  return false;
446  }
447 }
448 
449 /// toplevelentity
450 /// ::= 'source_filename' '=' STRINGCONSTANT
451 bool LLParser::parseSourceFileName() {
453  Lex.Lex();
454  if (parseToken(lltok::equal, "expected '=' after source_filename") ||
455  parseStringConstant(SourceFileName))
456  return true;
457  if (M)
458  M->setSourceFileName(SourceFileName);
459  return false;
460 }
461 
462 /// toplevelentity
463 /// ::= 'deplibs' '=' '[' ']'
464 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
465 /// FIXME: Remove in 4.0. Currently parse, but ignore.
466 bool LLParser::parseDepLibs() {
467  assert(Lex.getKind() == lltok::kw_deplibs);
468  Lex.Lex();
469  if (parseToken(lltok::equal, "expected '=' after deplibs") ||
470  parseToken(lltok::lsquare, "expected '=' after deplibs"))
471  return true;
472 
473  if (EatIfPresent(lltok::rsquare))
474  return false;
475 
476  do {
477  std::string Str;
478  if (parseStringConstant(Str))
479  return true;
480  } while (EatIfPresent(lltok::comma));
481 
482  return parseToken(lltok::rsquare, "expected ']' at end of list");
483 }
484 
485 /// parseUnnamedType:
486 /// ::= LocalVarID '=' 'type' type
487 bool LLParser::parseUnnamedType() {
488  LocTy TypeLoc = Lex.getLoc();
489  unsigned TypeID = Lex.getUIntVal();
490  Lex.Lex(); // eat LocalVarID;
491 
492  if (parseToken(lltok::equal, "expected '=' after name") ||
493  parseToken(lltok::kw_type, "expected 'type' after '='"))
494  return true;
495 
496  Type *Result = nullptr;
497  if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
498  return true;
499 
500  if (!isa<StructType>(Result)) {
501  std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
502  if (Entry.first)
503  return error(TypeLoc, "non-struct types may not be recursive");
504  Entry.first = Result;
505  Entry.second = SMLoc();
506  }
507 
508  return false;
509 }
510 
511 /// toplevelentity
512 /// ::= LocalVar '=' 'type' type
513 bool LLParser::parseNamedType() {
514  std::string Name = Lex.getStrVal();
515  LocTy NameLoc = Lex.getLoc();
516  Lex.Lex(); // eat LocalVar.
517 
518  if (parseToken(lltok::equal, "expected '=' after name") ||
519  parseToken(lltok::kw_type, "expected 'type' after name"))
520  return true;
521 
522  Type *Result = nullptr;
523  if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
524  return true;
525 
526  if (!isa<StructType>(Result)) {
527  std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
528  if (Entry.first)
529  return error(NameLoc, "non-struct types may not be recursive");
530  Entry.first = Result;
531  Entry.second = SMLoc();
532  }
533 
534  return false;
535 }
536 
537 /// toplevelentity
538 /// ::= 'declare' FunctionHeader
539 bool LLParser::parseDeclare() {
540  assert(Lex.getKind() == lltok::kw_declare);
541  Lex.Lex();
542 
543  std::vector<std::pair<unsigned, MDNode *>> MDs;
544  while (Lex.getKind() == lltok::MetadataVar) {
545  unsigned MDK;
546  MDNode *N;
547  if (parseMetadataAttachment(MDK, N))
548  return true;
549  MDs.push_back({MDK, N});
550  }
551 
552  Function *F;
553  if (parseFunctionHeader(F, false))
554  return true;
555  for (auto &MD : MDs)
556  F->addMetadata(MD.first, *MD.second);
557  return false;
558 }
559 
560 /// toplevelentity
561 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
562 bool LLParser::parseDefine() {
563  assert(Lex.getKind() == lltok::kw_define);
564  Lex.Lex();
565 
566  Function *F;
567  return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
568  parseFunctionBody(*F);
569 }
570 
571 /// parseGlobalType
572 /// ::= 'constant'
573 /// ::= 'global'
574 bool LLParser::parseGlobalType(bool &IsConstant) {
575  if (Lex.getKind() == lltok::kw_constant)
576  IsConstant = true;
577  else if (Lex.getKind() == lltok::kw_global)
578  IsConstant = false;
579  else {
580  IsConstant = false;
581  return tokError("expected 'global' or 'constant'");
582  }
583  Lex.Lex();
584  return false;
585 }
586 
587 bool LLParser::parseOptionalUnnamedAddr(
588  GlobalVariable::UnnamedAddr &UnnamedAddr) {
589  if (EatIfPresent(lltok::kw_unnamed_addr))
590  UnnamedAddr = GlobalValue::UnnamedAddr::Global;
591  else if (EatIfPresent(lltok::kw_local_unnamed_addr))
592  UnnamedAddr = GlobalValue::UnnamedAddr::Local;
593  else
594  UnnamedAddr = GlobalValue::UnnamedAddr::None;
595  return false;
596 }
597 
598 /// parseUnnamedGlobal:
599 /// OptionalVisibility (ALIAS | IFUNC) ...
600 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
601 /// OptionalDLLStorageClass
602 /// ... -> global variable
603 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
604 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
605 /// OptionalVisibility
606 /// OptionalDLLStorageClass
607 /// ... -> global variable
608 bool LLParser::parseUnnamedGlobal() {
609  unsigned VarID = NumberedVals.size();
610  std::string Name;
611  LocTy NameLoc = Lex.getLoc();
612 
613  // Handle the GlobalID form.
614  if (Lex.getKind() == lltok::GlobalID) {
615  if (Lex.getUIntVal() != VarID)
616  return error(Lex.getLoc(),
617  "variable expected to be numbered '%" + Twine(VarID) + "'");
618  Lex.Lex(); // eat GlobalID;
619 
620  if (parseToken(lltok::equal, "expected '=' after name"))
621  return true;
622  }
623 
624  bool HasLinkage;
625  unsigned Linkage, Visibility, DLLStorageClass;
626  bool DSOLocal;
628  GlobalVariable::UnnamedAddr UnnamedAddr;
629  if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
630  DSOLocal) ||
631  parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
632  return true;
633 
634  if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
635  return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
636  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
637 
638  return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
639  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
640 }
641 
642 /// parseNamedGlobal:
643 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
644 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
645 /// OptionalVisibility OptionalDLLStorageClass
646 /// ... -> global variable
647 bool LLParser::parseNamedGlobal() {
648  assert(Lex.getKind() == lltok::GlobalVar);
649  LocTy NameLoc = Lex.getLoc();
650  std::string Name = Lex.getStrVal();
651  Lex.Lex();
652 
653  bool HasLinkage;
654  unsigned Linkage, Visibility, DLLStorageClass;
655  bool DSOLocal;
657  GlobalVariable::UnnamedAddr UnnamedAddr;
658  if (parseToken(lltok::equal, "expected '=' in global variable") ||
659  parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
660  DSOLocal) ||
661  parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
662  return true;
663 
664  if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
665  return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
666  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
667 
668  return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
669  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
670 }
671 
672 bool LLParser::parseComdat() {
673  assert(Lex.getKind() == lltok::ComdatVar);
674  std::string Name = Lex.getStrVal();
675  LocTy NameLoc = Lex.getLoc();
676  Lex.Lex();
677 
678  if (parseToken(lltok::equal, "expected '=' here"))
679  return true;
680 
681  if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
682  return tokError("expected comdat type");
683 
685  switch (Lex.getKind()) {
686  default:
687  return tokError("unknown selection kind");
688  case lltok::kw_any:
689  SK = Comdat::Any;
690  break;
692  SK = Comdat::ExactMatch;
693  break;
694  case lltok::kw_largest:
695  SK = Comdat::Largest;
696  break;
699  break;
700  case lltok::kw_samesize:
701  SK = Comdat::SameSize;
702  break;
703  }
704  Lex.Lex();
705 
706  // See if the comdat was forward referenced, if so, use the comdat.
707  Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
709  if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
710  return error(NameLoc, "redefinition of comdat '$" + Name + "'");
711 
712  Comdat *C;
713  if (I != ComdatSymTab.end())
714  C = &I->second;
715  else
716  C = M->getOrInsertComdat(Name);
717  C->setSelectionKind(SK);
718 
719  return false;
720 }
721 
722 // MDString:
723 // ::= '!' STRINGCONSTANT
724 bool LLParser::parseMDString(MDString *&Result) {
725  std::string Str;
726  if (parseStringConstant(Str))
727  return true;
728  Result = MDString::get(Context, Str);
729  return false;
730 }
731 
732 // MDNode:
733 // ::= '!' MDNodeNumber
734 bool LLParser::parseMDNodeID(MDNode *&Result) {
735  // !{ ..., !42, ... }
736  LocTy IDLoc = Lex.getLoc();
737  unsigned MID = 0;
738  if (parseUInt32(MID))
739  return true;
740 
741  // If not a forward reference, just return it now.
742  if (NumberedMetadata.count(MID)) {
743  Result = NumberedMetadata[MID];
744  return false;
745  }
746 
747  // Otherwise, create MDNode forward reference.
748  auto &FwdRef = ForwardRefMDNodes[MID];
749  FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
750 
751  Result = FwdRef.first.get();
752  NumberedMetadata[MID].reset(Result);
753  return false;
754 }
755 
756 /// parseNamedMetadata:
757 /// !foo = !{ !1, !2 }
758 bool LLParser::parseNamedMetadata() {
760  std::string Name = Lex.getStrVal();
761  Lex.Lex();
762 
763  if (parseToken(lltok::equal, "expected '=' here") ||
764  parseToken(lltok::exclaim, "Expected '!' here") ||
765  parseToken(lltok::lbrace, "Expected '{' here"))
766  return true;
767 
769  if (Lex.getKind() != lltok::rbrace)
770  do {
771  MDNode *N = nullptr;
772  // parse DIExpressions inline as a special case. They are still MDNodes,
773  // so they can still appear in named metadata. Remove this logic if they
774  // become plain Metadata.
775  if (Lex.getKind() == lltok::MetadataVar &&
776  Lex.getStrVal() == "DIExpression") {
777  if (parseDIExpression(N, /*IsDistinct=*/false))
778  return true;
779  // DIArgLists should only appear inline in a function, as they may
780  // contain LocalAsMetadata arguments which require a function context.
781  } else if (Lex.getKind() == lltok::MetadataVar &&
782  Lex.getStrVal() == "DIArgList") {
783  return tokError("found DIArgList outside of function");
784  } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
785  parseMDNodeID(N)) {
786  return true;
787  }
788  NMD->addOperand(N);
789  } while (EatIfPresent(lltok::comma));
790 
791  return parseToken(lltok::rbrace, "expected end of metadata node");
792 }
793 
794 /// parseStandaloneMetadata:
795 /// !42 = !{...}
796 bool LLParser::parseStandaloneMetadata() {
797  assert(Lex.getKind() == lltok::exclaim);
798  Lex.Lex();
799  unsigned MetadataID = 0;
800 
801  MDNode *Init;
802  if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
803  return true;
804 
805  // Detect common error, from old metadata syntax.
806  if (Lex.getKind() == lltok::Type)
807  return tokError("unexpected type in metadata definition");
808 
809  bool IsDistinct = EatIfPresent(lltok::kw_distinct);
810  if (Lex.getKind() == lltok::MetadataVar) {
811  if (parseSpecializedMDNode(Init, IsDistinct))
812  return true;
813  } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
814  parseMDTuple(Init, IsDistinct))
815  return true;
816 
817  // See if this was forward referenced, if so, handle it.
818  auto FI = ForwardRefMDNodes.find(MetadataID);
819  if (FI != ForwardRefMDNodes.end()) {
820  FI->second.first->replaceAllUsesWith(Init);
821  ForwardRefMDNodes.erase(FI);
822 
823  assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
824  } else {
825  if (NumberedMetadata.count(MetadataID))
826  return tokError("Metadata id is already used");
827  NumberedMetadata[MetadataID].reset(Init);
828  }
829 
830  return false;
831 }
832 
833 // Skips a single module summary entry.
834 bool LLParser::skipModuleSummaryEntry() {
835  // Each module summary entry consists of a tag for the entry
836  // type, followed by a colon, then the fields which may be surrounded by
837  // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
838  // support is in place we will look for the tokens corresponding to the
839  // expected tags.
840  if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
841  Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
842  Lex.getKind() != lltok::kw_blockcount)
843  return tokError(
844  "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
845  "start of summary entry");
846  if (Lex.getKind() == lltok::kw_flags)
847  return parseSummaryIndexFlags();
848  if (Lex.getKind() == lltok::kw_blockcount)
849  return parseBlockCount();
850  Lex.Lex();
851  if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
852  parseToken(lltok::lparen, "expected '(' at start of summary entry"))
853  return true;
854  // Now walk through the parenthesized entry, until the number of open
855  // parentheses goes back down to 0 (the first '(' was parsed above).
856  unsigned NumOpenParen = 1;
857  do {
858  switch (Lex.getKind()) {
859  case lltok::lparen:
860  NumOpenParen++;
861  break;
862  case lltok::rparen:
863  NumOpenParen--;
864  break;
865  case lltok::Eof:
866  return tokError("found end of file while parsing summary entry");
867  default:
868  // Skip everything in between parentheses.
869  break;
870  }
871  Lex.Lex();
872  } while (NumOpenParen > 0);
873  return false;
874 }
875 
876 /// SummaryEntry
877 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
878 bool LLParser::parseSummaryEntry() {
879  assert(Lex.getKind() == lltok::SummaryID);
880  unsigned SummaryID = Lex.getUIntVal();
881 
882  // For summary entries, colons should be treated as distinct tokens,
883  // not an indication of the end of a label token.
884  Lex.setIgnoreColonInIdentifiers(true);
885 
886  Lex.Lex();
887  if (parseToken(lltok::equal, "expected '=' here"))
888  return true;
889 
890  // If we don't have an index object, skip the summary entry.
891  if (!Index)
892  return skipModuleSummaryEntry();
893 
894  bool result = false;
895  switch (Lex.getKind()) {
896  case lltok::kw_gv:
897  result = parseGVEntry(SummaryID);
898  break;
899  case lltok::kw_module:
900  result = parseModuleEntry(SummaryID);
901  break;
902  case lltok::kw_typeid:
903  result = parseTypeIdEntry(SummaryID);
904  break;
906  result = parseTypeIdCompatibleVtableEntry(SummaryID);
907  break;
908  case lltok::kw_flags:
909  result = parseSummaryIndexFlags();
910  break;
912  result = parseBlockCount();
913  break;
914  default:
915  result = error(Lex.getLoc(), "unexpected summary kind");
916  break;
917  }
918  Lex.setIgnoreColonInIdentifiers(false);
919  return result;
920 }
921 
922 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
925 }
926 
927 // If there was an explicit dso_local, update GV. In the absence of an explicit
928 // dso_local we keep the default value.
929 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
930  if (DSOLocal)
931  GV.setDSOLocal(true);
932 }
933 
934 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
935  Type *Ty2) {
936  std::string ErrString;
937  raw_string_ostream ErrOS(ErrString);
938  ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
939  return ErrOS.str();
940 }
941 
942 /// parseIndirectSymbol:
943 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
944 /// OptionalVisibility OptionalDLLStorageClass
945 /// OptionalThreadLocal OptionalUnnamedAddr
946 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
947 ///
948 /// IndirectSymbol
949 /// ::= TypeAndValue
950 ///
951 /// IndirectSymbolAttr
952 /// ::= ',' 'partition' StringConstant
953 ///
954 /// Everything through OptionalUnnamedAddr has already been parsed.
955 ///
956 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
957  unsigned L, unsigned Visibility,
958  unsigned DLLStorageClass, bool DSOLocal,
960  GlobalVariable::UnnamedAddr UnnamedAddr) {
961  bool IsAlias;
962  if (Lex.getKind() == lltok::kw_alias)
963  IsAlias = true;
964  else if (Lex.getKind() == lltok::kw_ifunc)
965  IsAlias = false;
966  else
967  llvm_unreachable("Not an alias or ifunc!");
968  Lex.Lex();
969 
971 
972  if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
973  return error(NameLoc, "invalid linkage type for alias");
974 
975  if (!isValidVisibilityForLinkage(Visibility, L))
976  return error(NameLoc,
977  "symbol with local linkage must have default visibility");
978 
979  Type *Ty;
980  LocTy ExplicitTypeLoc = Lex.getLoc();
981  if (parseType(Ty) ||
982  parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
983  return true;
984 
985  Constant *Aliasee;
986  LocTy AliaseeLoc = Lex.getLoc();
987  if (Lex.getKind() != lltok::kw_bitcast &&
988  Lex.getKind() != lltok::kw_getelementptr &&
989  Lex.getKind() != lltok::kw_addrspacecast &&
990  Lex.getKind() != lltok::kw_inttoptr) {
991  if (parseGlobalTypeAndValue(Aliasee))
992  return true;
993  } else {
994  // The bitcast dest type is not present, it is implied by the dest type.
995  ValID ID;
996  if (parseValID(ID))
997  return true;
998  if (ID.Kind != ValID::t_Constant)
999  return error(AliaseeLoc, "invalid aliasee");
1000  Aliasee = ID.ConstantVal;
1001  }
1002 
1003  Type *AliaseeType = Aliasee->getType();
1004  auto *PTy = dyn_cast<PointerType>(AliaseeType);
1005  if (!PTy)
1006  return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1007  unsigned AddrSpace = PTy->getAddressSpace();
1008 
1009  if (IsAlias && Ty != PTy->getElementType()) {
1010  return error(
1011  ExplicitTypeLoc,
1013  "explicit pointee type doesn't match operand's pointee type", Ty,
1014  PTy->getElementType()));
1015  }
1016 
1017  if (!IsAlias && !PTy->getElementType()->isFunctionTy()) {
1018  return error(ExplicitTypeLoc,
1019  "explicit pointee type should be a function type");
1020  }
1021 
1022  GlobalValue *GVal = nullptr;
1023 
1024  // See if the alias was forward referenced, if so, prepare to replace the
1025  // forward reference.
1026  if (!Name.empty()) {
1027  GVal = M->getNamedValue(Name);
1028  if (GVal) {
1029  if (!ForwardRefVals.erase(Name))
1030  return error(NameLoc, "redefinition of global '@" + Name + "'");
1031  }
1032  } else {
1033  auto I = ForwardRefValIDs.find(NumberedVals.size());
1034  if (I != ForwardRefValIDs.end()) {
1035  GVal = I->second.first;
1036  ForwardRefValIDs.erase(I);
1037  }
1038  }
1039 
1040  // Okay, create the alias but do not insert it into the module yet.
1041  std::unique_ptr<GlobalIndirectSymbol> GA;
1042  if (IsAlias)
1043  GA.reset(GlobalAlias::create(Ty, AddrSpace,
1045  Aliasee, /*Parent*/ nullptr));
1046  else
1047  GA.reset(GlobalIFunc::create(Ty, AddrSpace,
1049  Aliasee, /*Parent*/ nullptr));
1050  GA->setThreadLocalMode(TLM);
1051  GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1052  GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1053  GA->setUnnamedAddr(UnnamedAddr);
1054  maybeSetDSOLocal(DSOLocal, *GA);
1055 
1056  // At this point we've parsed everything except for the IndirectSymbolAttrs.
1057  // Now parse them if there are any.
1058  while (Lex.getKind() == lltok::comma) {
1059  Lex.Lex();
1060 
1061  if (Lex.getKind() == lltok::kw_partition) {
1062  Lex.Lex();
1063  GA->setPartition(Lex.getStrVal());
1064  if (parseToken(lltok::StringConstant, "expected partition string"))
1065  return true;
1066  } else {
1067  return tokError("unknown alias or ifunc property!");
1068  }
1069  }
1070 
1071  if (Name.empty())
1072  NumberedVals.push_back(GA.get());
1073 
1074  if (GVal) {
1075  // Verify that types agree.
1076  if (GVal->getType() != GA->getType())
1077  return error(
1078  ExplicitTypeLoc,
1079  "forward reference and definition of alias have different types");
1080 
1081  // If they agree, just RAUW the old value with the alias and remove the
1082  // forward ref info.
1083  GVal->replaceAllUsesWith(GA.get());
1084  GVal->eraseFromParent();
1085  }
1086 
1087  // Insert into the module, we know its name won't collide now.
1088  if (IsAlias)
1089  M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1090  else
1091  M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1092  assert(GA->getName() == Name && "Should not be a name conflict!");
1093 
1094  // The module owns this now
1095  GA.release();
1096 
1097  return false;
1098 }
1099 
1100 /// parseGlobal
1101 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1102 /// OptionalVisibility OptionalDLLStorageClass
1103 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1104 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1105 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1106 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1107 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1108 /// Const OptionalAttrs
1109 ///
1110 /// Everything up to and including OptionalUnnamedAddr has been parsed
1111 /// already.
1112 ///
1113 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1114  unsigned Linkage, bool HasLinkage,
1115  unsigned Visibility, unsigned DLLStorageClass,
1116  bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1117  GlobalVariable::UnnamedAddr UnnamedAddr) {
1118  if (!isValidVisibilityForLinkage(Visibility, Linkage))
1119  return error(NameLoc,
1120  "symbol with local linkage must have default visibility");
1121 
1122  unsigned AddrSpace;
1123  bool IsConstant, IsExternallyInitialized;
1124  LocTy IsExternallyInitializedLoc;
1125  LocTy TyLoc;
1126 
1127  Type *Ty = nullptr;
1128  if (parseOptionalAddrSpace(AddrSpace) ||
1129  parseOptionalToken(lltok::kw_externally_initialized,
1130  IsExternallyInitialized,
1131  &IsExternallyInitializedLoc) ||
1132  parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1133  return true;
1134 
1135  // If the linkage is specified and is external, then no initializer is
1136  // present.
1137  Constant *Init = nullptr;
1138  if (!HasLinkage ||
1141  if (parseGlobalValue(Ty, Init))
1142  return true;
1143  }
1144 
1146  return error(TyLoc, "invalid type for global variable");
1147 
1148  GlobalValue *GVal = nullptr;
1149 
1150  // See if the global was forward referenced, if so, use the global.
1151  if (!Name.empty()) {
1152  GVal = M->getNamedValue(Name);
1153  if (GVal) {
1154  if (!ForwardRefVals.erase(Name))
1155  return error(NameLoc, "redefinition of global '@" + Name + "'");
1156  }
1157  } else {
1158  auto I = ForwardRefValIDs.find(NumberedVals.size());
1159  if (I != ForwardRefValIDs.end()) {
1160  GVal = I->second.first;
1161  ForwardRefValIDs.erase(I);
1162  }
1163  }
1164 
1165  GlobalVariable *GV;
1166  if (!GVal) {
1167  GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1169  AddrSpace);
1170  } else {
1171  if (GVal->getValueType() != Ty)
1172  return error(
1173  TyLoc,
1174  "forward reference and definition of global have different types");
1175 
1176  GV = cast<GlobalVariable>(GVal);
1177 
1178  // Move the forward-reference to the correct spot in the module.
1179  M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1180  }
1181 
1182  if (Name.empty())
1183  NumberedVals.push_back(GV);
1184 
1185  // Set the parsed properties on the global.
1186  if (Init)
1187  GV->setInitializer(Init);
1188  GV->setConstant(IsConstant);
1190  maybeSetDSOLocal(DSOLocal, *GV);
1193  GV->setExternallyInitialized(IsExternallyInitialized);
1194  GV->setThreadLocalMode(TLM);
1195  GV->setUnnamedAddr(UnnamedAddr);
1196 
1197  // parse attributes on the global.
1198  while (Lex.getKind() == lltok::comma) {
1199  Lex.Lex();
1200 
1201  if (Lex.getKind() == lltok::kw_section) {
1202  Lex.Lex();
1203  GV->setSection(Lex.getStrVal());
1204  if (parseToken(lltok::StringConstant, "expected global section string"))
1205  return true;
1206  } else if (Lex.getKind() == lltok::kw_partition) {
1207  Lex.Lex();
1208  GV->setPartition(Lex.getStrVal());
1209  if (parseToken(lltok::StringConstant, "expected partition string"))
1210  return true;
1211  } else if (Lex.getKind() == lltok::kw_align) {
1212  MaybeAlign Alignment;
1213  if (parseOptionalAlignment(Alignment))
1214  return true;
1215  GV->setAlignment(Alignment);
1216  } else if (Lex.getKind() == lltok::MetadataVar) {
1217  if (parseGlobalObjectMetadataAttachment(*GV))
1218  return true;
1219  } else {
1220  Comdat *C;
1221  if (parseOptionalComdat(Name, C))
1222  return true;
1223  if (C)
1224  GV->setComdat(C);
1225  else
1226  return tokError("unknown global variable property!");
1227  }
1228  }
1229 
1231  LocTy BuiltinLoc;
1232  std::vector<unsigned> FwdRefAttrGrps;
1233  if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1234  return true;
1235  if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1236  GV->setAttributes(AttributeSet::get(Context, Attrs));
1237  ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1238  }
1239 
1240  return false;
1241 }
1242 
1243 /// parseUnnamedAttrGrp
1244 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1245 bool LLParser::parseUnnamedAttrGrp() {
1247  LocTy AttrGrpLoc = Lex.getLoc();
1248  Lex.Lex();
1249 
1250  if (Lex.getKind() != lltok::AttrGrpID)
1251  return tokError("expected attribute group id");
1252 
1253  unsigned VarID = Lex.getUIntVal();
1254  std::vector<unsigned> unused;
1255  LocTy BuiltinLoc;
1256  Lex.Lex();
1257 
1258  if (parseToken(lltok::equal, "expected '=' here") ||
1259  parseToken(lltok::lbrace, "expected '{' here") ||
1260  parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1261  BuiltinLoc) ||
1262  parseToken(lltok::rbrace, "expected end of attribute group"))
1263  return true;
1264 
1265  if (!NumberedAttrBuilders[VarID].hasAttributes())
1266  return error(AttrGrpLoc, "attribute group has no attributes");
1267 
1268  return false;
1269 }
1270 
1271 /// parseFnAttributeValuePairs
1272 /// ::= <attr> | <attr> '=' <value>
1273 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1274  std::vector<unsigned> &FwdRefAttrGrps,
1275  bool inAttrGrp, LocTy &BuiltinLoc) {
1276  bool HaveError = false;
1277 
1278  B.clear();
1279 
1280  while (true) {
1281  lltok::Kind Token = Lex.getKind();
1282  if (Token == lltok::kw_builtin)
1283  BuiltinLoc = Lex.getLoc();
1284  switch (Token) {
1285  default:
1286  if (!inAttrGrp) return HaveError;
1287  return error(Lex.getLoc(), "unterminated attribute group");
1288  case lltok::rbrace:
1289  // Finished.
1290  return false;
1291 
1292  case lltok::AttrGrpID: {
1293  // Allow a function to reference an attribute group:
1294  //
1295  // define void @foo() #1 { ... }
1296  if (inAttrGrp)
1297  HaveError |= error(
1298  Lex.getLoc(),
1299  "cannot have an attribute group reference in an attribute group");
1300 
1301  unsigned AttrGrpNum = Lex.getUIntVal();
1302  if (inAttrGrp) break;
1303 
1304  // Save the reference to the attribute group. We'll fill it in later.
1305  FwdRefAttrGrps.push_back(AttrGrpNum);
1306  break;
1307  }
1308  // Target-dependent attributes:
1309  case lltok::StringConstant: {
1310  if (parseStringAttribute(B))
1311  return true;
1312  continue;
1313  }
1314 
1315  // Target-independent attributes:
1316  case lltok::kw_align: {
1317  // As a hack, we allow function alignment to be initially parsed as an
1318  // attribute on a function declaration/definition or added to an attribute
1319  // group and later moved to the alignment field.
1320  MaybeAlign Alignment;
1321  if (inAttrGrp) {
1322  Lex.Lex();
1323  uint32_t Value = 0;
1324  if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1325  return true;
1326  Alignment = Align(Value);
1327  } else {
1328  if (parseOptionalAlignment(Alignment))
1329  return true;
1330  }
1331  B.addAlignmentAttr(Alignment);
1332  continue;
1333  }
1334  case lltok::kw_alignstack: {
1335  unsigned Alignment;
1336  if (inAttrGrp) {
1337  Lex.Lex();
1338  if (parseToken(lltok::equal, "expected '=' here") ||
1339  parseUInt32(Alignment))
1340  return true;
1341  } else {
1342  if (parseOptionalStackAlignment(Alignment))
1343  return true;
1344  }
1345  B.addStackAlignmentAttr(Alignment);
1346  continue;
1347  }
1348  case lltok::kw_allocsize: {
1349  unsigned ElemSizeArg;
1350  Optional<unsigned> NumElemsArg;
1351  // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1352  if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1353  return true;
1354  B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1355  continue;
1356  }
1357  case lltok::kw_vscale_range: {
1358  unsigned MinValue, MaxValue;
1359  // inAttrGrp doesn't matter; we only support vscale_range(a[, b])
1360  if (parseVScaleRangeArguments(MinValue, MaxValue))
1361  return true;
1362  B.addVScaleRangeAttr(MinValue, MaxValue);
1363  continue;
1364  }
1365  case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1366  case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1367  case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1368  case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1369  case lltok::kw_hot: B.addAttribute(Attribute::Hot); break;
1370  case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1372  B.addAttribute(Attribute::InaccessibleMemOnly); break;
1374  B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1375  case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1376  case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1377  case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1379  B.addAttribute(Attribute::MustProgress);
1380  break;
1381  case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1382  case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1383  case lltok::kw_nocallback:
1384  B.addAttribute(Attribute::NoCallback);
1385  break;
1386  case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1387  case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1389  B.addAttribute(Attribute::NoImplicitFloat); break;
1390  case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1391  case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1392  case lltok::kw_nomerge: B.addAttribute(Attribute::NoMerge); break;
1393  case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1394  case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1395  case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1396  case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1397  case lltok::kw_noprofile: B.addAttribute(Attribute::NoProfile); break;
1398  case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1399  case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1401  B.addAttribute(Attribute::NullPointerIsValid); break;
1403  B.addAttribute(Attribute::OptForFuzzing); break;
1404  case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1405  case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1406  case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1407  case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1409  B.addAttribute(Attribute::ReturnsTwice); break;
1410  case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1411  case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1412  case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1413  case lltok::kw_sspstrong:
1414  B.addAttribute(Attribute::StackProtectStrong); break;
1415  case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1417  B.addAttribute(Attribute::ShadowCallStack); break;
1419  B.addAttribute(Attribute::SanitizeAddress); break;
1421  B.addAttribute(Attribute::SanitizeHWAddress); break;
1423  B.addAttribute(Attribute::SanitizeMemTag); break;
1425  B.addAttribute(Attribute::SanitizeThread); break;
1427  B.addAttribute(Attribute::SanitizeMemory); break;
1429  B.addAttribute(Attribute::SpeculativeLoadHardening);
1430  break;
1431  case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1432  case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1433  case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1434  case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1435  case lltok::kw_preallocated: {
1436  Type *Ty;
1437  if (parsePreallocated(Ty))
1438  return true;
1439  B.addPreallocatedAttr(Ty);
1440  break;
1441  }
1442 
1443  // error handling.
1444  case lltok::kw_inreg:
1445  case lltok::kw_signext:
1446  case lltok::kw_zeroext:
1447  HaveError |=
1448  error(Lex.getLoc(), "invalid use of attribute on a function");
1449  break;
1450  case lltok::kw_byval:
1453  case lltok::kw_inalloca:
1454  case lltok::kw_nest:
1455  case lltok::kw_noalias:
1456  case lltok::kw_noundef:
1457  case lltok::kw_nocapture:
1458  case lltok::kw_nonnull:
1459  case lltok::kw_returned:
1460  case lltok::kw_sret:
1461  case lltok::kw_swifterror:
1462  case lltok::kw_swiftself:
1463  case lltok::kw_immarg:
1464  case lltok::kw_byref:
1465  HaveError |=
1466  error(Lex.getLoc(),
1467  "invalid use of parameter-only attribute on a function");
1468  break;
1469  }
1470 
1471  // parsePreallocated() consumes token
1472  if (Token != lltok::kw_preallocated)
1473  Lex.Lex();
1474  }
1475 }
1476 
1477 //===----------------------------------------------------------------------===//
1478 // GlobalValue Reference/Resolution Routines.
1479 //===----------------------------------------------------------------------===//
1480 
1482  const std::string &Name) {
1483  if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1485  PTy->getAddressSpace(), Name, M);
1486  else
1487  return new GlobalVariable(*M, PTy->getElementType(), false,
1490  PTy->getAddressSpace());
1491 }
1492 
1493 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1494  Value *Val, bool IsCall) {
1495  if (Val->getType() == Ty)
1496  return Val;
1497  // For calls we also accept variables in the program address space.
1498  Type *SuggestedTy = Ty;
1499  if (IsCall && isa<PointerType>(Ty)) {
1500  Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1502  SuggestedTy = TyInProgAS;
1503  if (Val->getType() == TyInProgAS)
1504  return Val;
1505  }
1506  if (Ty->isLabelTy())
1507  error(Loc, "'" + Name + "' is not a basic block");
1508  else
1509  error(Loc, "'" + Name + "' defined with type '" +
1510  getTypeString(Val->getType()) + "' but expected '" +
1511  getTypeString(SuggestedTy) + "'");
1512  return nullptr;
1513 }
1514 
1515 /// getGlobalVal - Get a value with the specified name or ID, creating a
1516 /// forward reference record if needed. This can return null if the value
1517 /// exists but does not have the right type.
1518 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1519  LocTy Loc, bool IsCall) {
1520  PointerType *PTy = dyn_cast<PointerType>(Ty);
1521  if (!PTy) {
1522  error(Loc, "global variable reference must have pointer type");
1523  return nullptr;
1524  }
1525 
1526  // Look this name up in the normal function symbol table.
1527  GlobalValue *Val =
1528  cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1529 
1530  // If this is a forward reference for the value, see if we already created a
1531  // forward ref record.
1532  if (!Val) {
1533  auto I = ForwardRefVals.find(Name);
1534  if (I != ForwardRefVals.end())
1535  Val = I->second.first;
1536  }
1537 
1538  // If we have the value in the symbol table or fwd-ref table, return it.
1539  if (Val)
1540  return cast_or_null<GlobalValue>(
1541  checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1542 
1543  // Otherwise, create a new forward reference for this value and remember it.
1544  GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1545  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1546  return FwdVal;
1547 }
1548 
1549 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1550  bool IsCall) {
1551  PointerType *PTy = dyn_cast<PointerType>(Ty);
1552  if (!PTy) {
1553  error(Loc, "global variable reference must have pointer type");
1554  return nullptr;
1555  }
1556 
1557  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1558 
1559  // If this is a forward reference for the value, see if we already created a
1560  // forward ref record.
1561  if (!Val) {
1562  auto I = ForwardRefValIDs.find(ID);
1563  if (I != ForwardRefValIDs.end())
1564  Val = I->second.first;
1565  }
1566 
1567  // If we have the value in the symbol table or fwd-ref table, return it.
1568  if (Val)
1569  return cast_or_null<GlobalValue>(
1570  checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1571 
1572  // Otherwise, create a new forward reference for this value and remember it.
1573  GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1574  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1575  return FwdVal;
1576 }
1577 
1578 //===----------------------------------------------------------------------===//
1579 // Comdat Reference/Resolution Routines.
1580 //===----------------------------------------------------------------------===//
1581 
1582 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1583  // Look this name up in the comdat symbol table.
1584  Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1586  if (I != ComdatSymTab.end())
1587  return &I->second;
1588 
1589  // Otherwise, create a new forward reference for this value and remember it.
1590  Comdat *C = M->getOrInsertComdat(Name);
1591  ForwardRefComdats[Name] = Loc;
1592  return C;
1593 }
1594 
1595 //===----------------------------------------------------------------------===//
1596 // Helper Routines.
1597 //===----------------------------------------------------------------------===//
1598 
1599 /// parseToken - If the current token has the specified kind, eat it and return
1600 /// success. Otherwise, emit the specified error and return failure.
1601 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1602  if (Lex.getKind() != T)
1603  return tokError(ErrMsg);
1604  Lex.Lex();
1605  return false;
1606 }
1607 
1608 /// parseStringConstant
1609 /// ::= StringConstant
1610 bool LLParser::parseStringConstant(std::string &Result) {
1611  if (Lex.getKind() != lltok::StringConstant)
1612  return tokError("expected string constant");
1613  Result = Lex.getStrVal();
1614  Lex.Lex();
1615  return false;
1616 }
1617 
1618 /// parseUInt32
1619 /// ::= uint32
1620 bool LLParser::parseUInt32(uint32_t &Val) {
1621  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1622  return tokError("expected integer");
1623  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1624  if (Val64 != unsigned(Val64))
1625  return tokError("expected 32-bit integer (too large)");
1626  Val = Val64;
1627  Lex.Lex();
1628  return false;
1629 }
1630 
1631 /// parseUInt64
1632 /// ::= uint64
1633 bool LLParser::parseUInt64(uint64_t &Val) {
1634  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1635  return tokError("expected integer");
1636  Val = Lex.getAPSIntVal().getLimitedValue();
1637  Lex.Lex();
1638  return false;
1639 }
1640 
1641 /// parseTLSModel
1642 /// := 'localdynamic'
1643 /// := 'initialexec'
1644 /// := 'localexec'
1645 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1646  switch (Lex.getKind()) {
1647  default:
1648  return tokError("expected localdynamic, initialexec or localexec");
1651  break;
1652  case lltok::kw_initialexec:
1654  break;
1655  case lltok::kw_localexec:
1657  break;
1658  }
1659 
1660  Lex.Lex();
1661  return false;
1662 }
1663 
1664 /// parseOptionalThreadLocal
1665 /// := /*empty*/
1666 /// := 'thread_local'
1667 /// := 'thread_local' '(' tlsmodel ')'
1668 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1670  if (!EatIfPresent(lltok::kw_thread_local))
1671  return false;
1672 
1674  if (Lex.getKind() == lltok::lparen) {
1675  Lex.Lex();
1676  return parseTLSModel(TLM) ||
1677  parseToken(lltok::rparen, "expected ')' after thread local model");
1678  }
1679  return false;
1680 }
1681 
1682 /// parseOptionalAddrSpace
1683 /// := /*empty*/
1684 /// := 'addrspace' '(' uint32 ')'
1685 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1686  AddrSpace = DefaultAS;
1687  if (!EatIfPresent(lltok::kw_addrspace))
1688  return false;
1689  return parseToken(lltok::lparen, "expected '(' in address space") ||
1690  parseUInt32(AddrSpace) ||
1691  parseToken(lltok::rparen, "expected ')' in address space");
1692 }
1693 
1694 /// parseStringAttribute
1695 /// := StringConstant
1696 /// := StringConstant '=' StringConstant
1697 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1698  std::string Attr = Lex.getStrVal();
1699  Lex.Lex();
1700  std::string Val;
1701  if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1702  return true;
1703  B.addAttribute(Attr, Val);
1704  return false;
1705 }
1706 
1707 /// parseOptionalParamAttrs - parse a potentially empty list of parameter
1708 /// attributes.
1709 bool LLParser::parseOptionalParamAttrs(AttrBuilder &B) {
1710  bool HaveError = false;
1711 
1712  B.clear();
1713 
1714  while (true) {
1715  lltok::Kind Token = Lex.getKind();
1716  switch (Token) {
1717  default: // End of attributes.
1718  return HaveError;
1719  case lltok::StringConstant: {
1720  if (parseStringAttribute(B))
1721  return true;
1722  continue;
1723  }
1724  case lltok::kw_align: {
1725  MaybeAlign Alignment;
1726  if (parseOptionalAlignment(Alignment, true))
1727  return true;
1728  B.addAlignmentAttr(Alignment);
1729  continue;
1730  }
1731  case lltok::kw_alignstack: {
1732  unsigned Alignment;
1733  if (parseOptionalStackAlignment(Alignment))
1734  return true;
1735  B.addStackAlignmentAttr(Alignment);
1736  continue;
1737  }
1738  case lltok::kw_byval: {
1739  Type *Ty;
1740  if (parseRequiredTypeAttr(Ty, lltok::kw_byval))
1741  return true;
1742  B.addByValAttr(Ty);
1743  continue;
1744  }
1745  case lltok::kw_sret: {
1746  Type *Ty;
1747  if (parseRequiredTypeAttr(Ty, lltok::kw_sret))
1748  return true;
1749  B.addStructRetAttr(Ty);
1750  continue;
1751  }
1752  case lltok::kw_preallocated: {
1753  Type *Ty;
1754  if (parsePreallocated(Ty))
1755  return true;
1756  B.addPreallocatedAttr(Ty);
1757  continue;
1758  }
1759  case lltok::kw_inalloca: {
1760  Type *Ty;
1761  if (parseInalloca(Ty))
1762  return true;
1763  B.addInAllocaAttr(Ty);
1764  continue;
1765  }
1767  uint64_t Bytes;
1768  if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1769  return true;
1770  B.addDereferenceableAttr(Bytes);
1771  continue;
1772  }
1774  uint64_t Bytes;
1775  if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1776  return true;
1777  B.addDereferenceableOrNullAttr(Bytes);
1778  continue;
1779  }
1780  case lltok::kw_byref: {
1781  Type *Ty;
1782  if (parseByRef(Ty))
1783  return true;
1784  B.addByRefAttr(Ty);
1785  continue;
1786  }
1787  case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1788  case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1789  case lltok::kw_noundef:
1790  B.addAttribute(Attribute::NoUndef);
1791  break;
1792  case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1793  case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1794  case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1795  case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1796  case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1797  case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1798  case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1799  case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1800  case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1801  case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1802  case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1803  case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1804  case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1805 
1807  case lltok::kw_argmemonly:
1808  case lltok::kw_builtin:
1809  case lltok::kw_inlinehint:
1810  case lltok::kw_jumptable:
1811  case lltok::kw_minsize:
1813  case lltok::kw_naked:
1814  case lltok::kw_nobuiltin:
1815  case lltok::kw_noduplicate:
1817  case lltok::kw_noinline:
1818  case lltok::kw_nonlazybind:
1819  case lltok::kw_nomerge:
1820  case lltok::kw_noprofile:
1821  case lltok::kw_noredzone:
1822  case lltok::kw_noreturn:
1823  case lltok::kw_nocf_check:
1824  case lltok::kw_nounwind:
1826  case lltok::kw_optnone:
1827  case lltok::kw_optsize:
1835  case lltok::kw_ssp:
1836  case lltok::kw_sspreq:
1837  case lltok::kw_sspstrong:
1838  case lltok::kw_safestack:
1840  case lltok::kw_strictfp:
1841  case lltok::kw_uwtable:
1843  HaveError |=
1844  error(Lex.getLoc(), "invalid use of function-only attribute");
1845  break;
1846  }
1847 
1848  Lex.Lex();
1849  }
1850 }
1851 
1852 /// parseOptionalReturnAttrs - parse a potentially empty list of return
1853 /// attributes.
1854 bool LLParser::parseOptionalReturnAttrs(AttrBuilder &B) {
1855  bool HaveError = false;
1856 
1857  B.clear();
1858 
1859  while (true) {
1860  lltok::Kind Token = Lex.getKind();
1861  switch (Token) {
1862  default: // End of attributes.
1863  return HaveError;
1864  case lltok::StringConstant: {
1865  if (parseStringAttribute(B))
1866  return true;
1867  continue;
1868  }
1870  uint64_t Bytes;
1871  if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1872  return true;
1873  B.addDereferenceableAttr(Bytes);
1874  continue;
1875  }
1877  uint64_t Bytes;
1878  if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1879  return true;
1880  B.addDereferenceableOrNullAttr(Bytes);
1881  continue;
1882  }
1883  case lltok::kw_align: {
1884  MaybeAlign Alignment;
1885  if (parseOptionalAlignment(Alignment))
1886  return true;
1887  B.addAlignmentAttr(Alignment);
1888  continue;
1889  }
1890  case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1891  case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1892  case lltok::kw_noundef:
1893  B.addAttribute(Attribute::NoUndef);
1894  break;
1895  case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1896  case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1897  case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1898 
1899  // error handling.
1900  case lltok::kw_byval:
1901  case lltok::kw_inalloca:
1902  case lltok::kw_nest:
1903  case lltok::kw_nocapture:
1904  case lltok::kw_returned:
1905  case lltok::kw_sret:
1906  case lltok::kw_swifterror:
1907  case lltok::kw_swiftself:
1908  case lltok::kw_immarg:
1909  case lltok::kw_byref:
1910  HaveError |=
1911  error(Lex.getLoc(), "invalid use of parameter-only attribute");
1912  break;
1913 
1914  case lltok::kw_alignstack:
1916  case lltok::kw_argmemonly:
1917  case lltok::kw_builtin:
1918  case lltok::kw_cold:
1919  case lltok::kw_inlinehint:
1920  case lltok::kw_jumptable:
1921  case lltok::kw_minsize:
1923  case lltok::kw_naked:
1924  case lltok::kw_nobuiltin:
1925  case lltok::kw_noduplicate:
1927  case lltok::kw_noinline:
1928  case lltok::kw_nonlazybind:
1929  case lltok::kw_nomerge:
1930  case lltok::kw_noprofile:
1931  case lltok::kw_noredzone:
1932  case lltok::kw_noreturn:
1933  case lltok::kw_nocf_check:
1934  case lltok::kw_nounwind:
1936  case lltok::kw_optnone:
1937  case lltok::kw_optsize:
1945  case lltok::kw_ssp:
1946  case lltok::kw_sspreq:
1947  case lltok::kw_sspstrong:
1948  case lltok::kw_safestack:
1950  case lltok::kw_strictfp:
1951  case lltok::kw_uwtable:
1953  HaveError |=
1954  error(Lex.getLoc(), "invalid use of function-only attribute");
1955  break;
1956  case lltok::kw_readnone:
1957  case lltok::kw_readonly:
1958  HaveError |=
1959  error(Lex.getLoc(), "invalid use of attribute on return type");
1960  break;
1962  HaveError |=
1963  error(Lex.getLoc(),
1964  "invalid use of parameter-only/call site-only attribute");
1965  break;
1966  }
1967 
1968  Lex.Lex();
1969  }
1970 }
1971 
1972 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1973  HasLinkage = true;
1974  switch (Kind) {
1975  default:
1976  HasLinkage = false;
1978  case lltok::kw_private:
1980  case lltok::kw_internal:
1982  case lltok::kw_weak:
1984  case lltok::kw_weak_odr:
1986  case lltok::kw_linkonce:
1992  case lltok::kw_appending:
1994  case lltok::kw_common:
1996  case lltok::kw_extern_weak:
1998  case lltok::kw_external:
2000  }
2001 }
2002 
2003 /// parseOptionalLinkage
2004 /// ::= /*empty*/
2005 /// ::= 'private'
2006 /// ::= 'internal'
2007 /// ::= 'weak'
2008 /// ::= 'weak_odr'
2009 /// ::= 'linkonce'
2010 /// ::= 'linkonce_odr'
2011 /// ::= 'available_externally'
2012 /// ::= 'appending'
2013 /// ::= 'common'
2014 /// ::= 'extern_weak'
2015 /// ::= 'external'
2016 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2017  unsigned &Visibility,
2018  unsigned &DLLStorageClass, bool &DSOLocal) {
2019  Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2020  if (HasLinkage)
2021  Lex.Lex();
2022  parseOptionalDSOLocal(DSOLocal);
2023  parseOptionalVisibility(Visibility);
2024  parseOptionalDLLStorageClass(DLLStorageClass);
2025 
2026  if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2027  return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2028  }
2029 
2030  return false;
2031 }
2032 
2033 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2034  switch (Lex.getKind()) {
2035  default:
2036  DSOLocal = false;
2037  break;
2038  case lltok::kw_dso_local:
2039  DSOLocal = true;
2040  Lex.Lex();
2041  break;
2043  DSOLocal = false;
2044  Lex.Lex();
2045  break;
2046  }
2047 }
2048 
2049 /// parseOptionalVisibility
2050 /// ::= /*empty*/
2051 /// ::= 'default'
2052 /// ::= 'hidden'
2053 /// ::= 'protected'
2054 ///
2055 void LLParser::parseOptionalVisibility(unsigned &Res) {
2056  switch (Lex.getKind()) {
2057  default:
2059  return;
2060  case lltok::kw_default:
2062  break;
2063  case lltok::kw_hidden:
2065  break;
2066  case lltok::kw_protected:
2068  break;
2069  }
2070  Lex.Lex();
2071 }
2072 
2073 /// parseOptionalDLLStorageClass
2074 /// ::= /*empty*/
2075 /// ::= 'dllimport'
2076 /// ::= 'dllexport'
2077 ///
2078 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2079  switch (Lex.getKind()) {
2080  default:
2082  return;
2083  case lltok::kw_dllimport:
2085  break;
2086  case lltok::kw_dllexport:
2088  break;
2089  }
2090  Lex.Lex();
2091 }
2092 
2093 /// parseOptionalCallingConv
2094 /// ::= /*empty*/
2095 /// ::= 'ccc'
2096 /// ::= 'fastcc'
2097 /// ::= 'intel_ocl_bicc'
2098 /// ::= 'coldcc'
2099 /// ::= 'cfguard_checkcc'
2100 /// ::= 'x86_stdcallcc'
2101 /// ::= 'x86_fastcallcc'
2102 /// ::= 'x86_thiscallcc'
2103 /// ::= 'x86_vectorcallcc'
2104 /// ::= 'arm_apcscc'
2105 /// ::= 'arm_aapcscc'
2106 /// ::= 'arm_aapcs_vfpcc'
2107 /// ::= 'aarch64_vector_pcs'
2108 /// ::= 'aarch64_sve_vector_pcs'
2109 /// ::= 'msp430_intrcc'
2110 /// ::= 'avr_intrcc'
2111 /// ::= 'avr_signalcc'
2112 /// ::= 'ptx_kernel'
2113 /// ::= 'ptx_device'
2114 /// ::= 'spir_func'
2115 /// ::= 'spir_kernel'
2116 /// ::= 'x86_64_sysvcc'
2117 /// ::= 'win64cc'
2118 /// ::= 'webkit_jscc'
2119 /// ::= 'anyregcc'
2120 /// ::= 'preserve_mostcc'
2121 /// ::= 'preserve_allcc'
2122 /// ::= 'ghccc'
2123 /// ::= 'swiftcc'
2124 /// ::= 'x86_intrcc'
2125 /// ::= 'hhvmcc'
2126 /// ::= 'hhvm_ccc'
2127 /// ::= 'cxx_fast_tlscc'
2128 /// ::= 'amdgpu_vs'
2129 /// ::= 'amdgpu_ls'
2130 /// ::= 'amdgpu_hs'
2131 /// ::= 'amdgpu_es'
2132 /// ::= 'amdgpu_gs'
2133 /// ::= 'amdgpu_ps'
2134 /// ::= 'amdgpu_cs'
2135 /// ::= 'amdgpu_kernel'
2136 /// ::= 'tailcc'
2137 /// ::= 'cc' UINT
2138 ///
2139 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2140  switch (Lex.getKind()) {
2141  default: CC = CallingConv::C; return false;
2142  case lltok::kw_ccc: CC = CallingConv::C; break;
2143  case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2144  case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2151  case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
2157  break;
2159  case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
2164  case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
2167  case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2169  case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2172  case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2173  case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2174  case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
2175  case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
2176  case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
2178  case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
2180  case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
2181  case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2182  case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2183  case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2184  case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2185  case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2187  case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2188  case lltok::kw_cc: {
2189  Lex.Lex();
2190  return parseUInt32(CC);
2191  }
2192  }
2193 
2194  Lex.Lex();
2195  return false;
2196 }
2197 
2198 /// parseMetadataAttachment
2199 /// ::= !dbg !42
2200 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2201  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2202 
2203  std::string Name = Lex.getStrVal();
2204  Kind = M->getMDKindID(Name);
2205  Lex.Lex();
2206 
2207  return parseMDNode(MD);
2208 }
2209 
2210 /// parseInstructionMetadata
2211 /// ::= !dbg !42 (',' !dbg !57)*
2212 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2213  do {
2214  if (Lex.getKind() != lltok::MetadataVar)
2215  return tokError("expected metadata after comma");
2216 
2217  unsigned MDK;
2218  MDNode *N;
2219  if (parseMetadataAttachment(MDK, N))
2220  return true;
2221 
2222  Inst.setMetadata(MDK, N);
2223  if (MDK == LLVMContext::MD_tbaa)
2224  InstsWithTBAATag.push_back(&Inst);
2225 
2226  // If this is the end of the list, we're done.
2227  } while (EatIfPresent(lltok::comma));
2228  return false;
2229 }
2230 
2231 /// parseGlobalObjectMetadataAttachment
2232 /// ::= !dbg !57
2233 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2234  unsigned MDK;
2235  MDNode *N;
2236  if (parseMetadataAttachment(MDK, N))
2237  return true;
2238 
2239  GO.addMetadata(MDK, *N);
2240  return false;
2241 }
2242 
2243 /// parseOptionalFunctionMetadata
2244 /// ::= (!dbg !57)*
2245 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2246  while (Lex.getKind() == lltok::MetadataVar)
2247  if (parseGlobalObjectMetadataAttachment(F))
2248  return true;
2249  return false;
2250 }
2251 
2252 /// parseOptionalAlignment
2253 /// ::= /* empty */
2254 /// ::= 'align' 4
2255 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2256  Alignment = None;
2257  if (!EatIfPresent(lltok::kw_align))
2258  return false;
2259  LocTy AlignLoc = Lex.getLoc();
2260  uint32_t Value = 0;
2261 
2262  LocTy ParenLoc = Lex.getLoc();
2263  bool HaveParens = false;
2264  if (AllowParens) {
2265  if (EatIfPresent(lltok::lparen))
2266  HaveParens = true;
2267  }
2268 
2269  if (parseUInt32(Value))
2270  return true;
2271 
2272  if (HaveParens && !EatIfPresent(lltok::rparen))
2273  return error(ParenLoc, "expected ')'");
2274 
2275  if (!isPowerOf2_32(Value))
2276  return error(AlignLoc, "alignment is not a power of two");
2278  return error(AlignLoc, "huge alignments are not supported yet");
2279  Alignment = Align(Value);
2280  return false;
2281 }
2282 
2283 /// parseOptionalDerefAttrBytes
2284 /// ::= /* empty */
2285 /// ::= AttrKind '(' 4 ')'
2286 ///
2287 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2288 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2289  uint64_t &Bytes) {
2290  assert((AttrKind == lltok::kw_dereferenceable ||
2291  AttrKind == lltok::kw_dereferenceable_or_null) &&
2292  "contract!");
2293 
2294  Bytes = 0;
2295  if (!EatIfPresent(AttrKind))
2296  return false;
2297  LocTy ParenLoc = Lex.getLoc();
2298  if (!EatIfPresent(lltok::lparen))
2299  return error(ParenLoc, "expected '('");
2300  LocTy DerefLoc = Lex.getLoc();
2301  if (parseUInt64(Bytes))
2302  return true;
2303  ParenLoc = Lex.getLoc();
2304  if (!EatIfPresent(lltok::rparen))
2305  return error(ParenLoc, "expected ')'");
2306  if (!Bytes)
2307  return error(DerefLoc, "dereferenceable bytes must be non-zero");
2308  return false;
2309 }
2310 
2311 /// parseOptionalCommaAlign
2312 /// ::=
2313 /// ::= ',' align 4
2314 ///
2315 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2316 /// end.
2317 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2318  bool &AteExtraComma) {
2319  AteExtraComma = false;
2320  while (EatIfPresent(lltok::comma)) {
2321  // Metadata at the end is an early exit.
2322  if (Lex.getKind() == lltok::MetadataVar) {
2323  AteExtraComma = true;
2324  return false;
2325  }
2326 
2327  if (Lex.getKind() != lltok::kw_align)
2328  return error(Lex.getLoc(), "expected metadata or 'align'");
2329 
2330  if (parseOptionalAlignment(Alignment))
2331  return true;
2332  }
2333 
2334  return false;
2335 }
2336 
2337 /// parseOptionalCommaAddrSpace
2338 /// ::=
2339 /// ::= ',' addrspace(1)
2340 ///
2341 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2342 /// end.
2343 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2344  bool &AteExtraComma) {
2345  AteExtraComma = false;
2346  while (EatIfPresent(lltok::comma)) {
2347  // Metadata at the end is an early exit.
2348  if (Lex.getKind() == lltok::MetadataVar) {
2349  AteExtraComma = true;
2350  return false;
2351  }
2352 
2353  Loc = Lex.getLoc();
2354  if (Lex.getKind() != lltok::kw_addrspace)
2355  return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2356 
2357  if (parseOptionalAddrSpace(AddrSpace))
2358  return true;
2359  }
2360 
2361  return false;
2362 }
2363 
2364 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2365  Optional<unsigned> &HowManyArg) {
2366  Lex.Lex();
2367 
2368  auto StartParen = Lex.getLoc();
2369  if (!EatIfPresent(lltok::lparen))
2370  return error(StartParen, "expected '('");
2371 
2372  if (parseUInt32(BaseSizeArg))
2373  return true;
2374 
2375  if (EatIfPresent(lltok::comma)) {
2376  auto HowManyAt = Lex.getLoc();
2377  unsigned HowMany;
2378  if (parseUInt32(HowMany))
2379  return true;
2380  if (HowMany == BaseSizeArg)
2381  return error(HowManyAt,
2382  "'allocsize' indices can't refer to the same parameter");
2383  HowManyArg = HowMany;
2384  } else
2385  HowManyArg = None;
2386 
2387  auto EndParen = Lex.getLoc();
2388  if (!EatIfPresent(lltok::rparen))
2389  return error(EndParen, "expected ')'");
2390  return false;
2391 }
2392 
2393 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2394  unsigned &MaxValue) {
2395  Lex.Lex();
2396 
2397  auto StartParen = Lex.getLoc();
2398  if (!EatIfPresent(lltok::lparen))
2399  return error(StartParen, "expected '('");
2400 
2401  if (parseUInt32(MinValue))
2402  return true;
2403 
2404  if (EatIfPresent(lltok::comma)) {
2405  if (parseUInt32(MaxValue))
2406  return true;
2407  } else
2408  MaxValue = MinValue;
2409 
2410  auto EndParen = Lex.getLoc();
2411  if (!EatIfPresent(lltok::rparen))
2412  return error(EndParen, "expected ')'");
2413  return false;
2414 }
2415 
2416 /// parseScopeAndOrdering
2417 /// if isAtomic: ::= SyncScope? AtomicOrdering
2418 /// else: ::=
2419 ///
2420 /// This sets Scope and Ordering to the parsed values.
2421 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2422  AtomicOrdering &Ordering) {
2423  if (!IsAtomic)
2424  return false;
2425 
2426  return parseScope(SSID) || parseOrdering(Ordering);
2427 }
2428 
2429 /// parseScope
2430 /// ::= syncscope("singlethread" | "<target scope>")?
2431 ///
2432 /// This sets synchronization scope ID to the ID of the parsed value.
2433 bool LLParser::parseScope(SyncScope::ID &SSID) {
2434  SSID = SyncScope::System;
2435  if (EatIfPresent(lltok::kw_syncscope)) {
2436  auto StartParenAt = Lex.getLoc();
2437  if (!EatIfPresent(lltok::lparen))
2438  return error(StartParenAt, "Expected '(' in syncscope");
2439 
2440  std::string SSN;
2441  auto SSNAt = Lex.getLoc();
2442  if (parseStringConstant(SSN))
2443  return error(SSNAt, "Expected synchronization scope name");
2444 
2445  auto EndParenAt = Lex.getLoc();
2446  if (!EatIfPresent(lltok::rparen))
2447  return error(EndParenAt, "Expected ')' in syncscope");
2448 
2449  SSID = Context.getOrInsertSyncScopeID(SSN);
2450  }
2451 
2452  return false;
2453 }
2454 
2455 /// parseOrdering
2456 /// ::= AtomicOrdering
2457 ///
2458 /// This sets Ordering to the parsed value.
2459 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2460  switch (Lex.getKind()) {
2461  default:
2462  return tokError("Expected ordering on atomic instruction");
2463  case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2464  case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2465  // Not specified yet:
2466  // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2467  case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2468  case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2469  case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2470  case lltok::kw_seq_cst:
2472  break;
2473  }
2474  Lex.Lex();
2475  return false;
2476 }
2477 
2478 /// parseOptionalStackAlignment
2479 /// ::= /* empty */
2480 /// ::= 'alignstack' '(' 4 ')'
2481 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2482  Alignment = 0;
2483  if (!EatIfPresent(lltok::kw_alignstack))
2484  return false;
2485  LocTy ParenLoc = Lex.getLoc();
2486  if (!EatIfPresent(lltok::lparen))
2487  return error(ParenLoc, "expected '('");
2488  LocTy AlignLoc = Lex.getLoc();
2489  if (parseUInt32(Alignment))
2490  return true;
2491  ParenLoc = Lex.getLoc();
2492  if (!EatIfPresent(lltok::rparen))
2493  return error(ParenLoc, "expected ')'");
2494  if (!isPowerOf2_32(Alignment))
2495  return error(AlignLoc, "stack alignment is not a power of two");
2496  return false;
2497 }
2498 
2499 /// parseIndexList - This parses the index list for an insert/extractvalue
2500 /// instruction. This sets AteExtraComma in the case where we eat an extra
2501 /// comma at the end of the line and find that it is followed by metadata.
2502 /// Clients that don't allow metadata can call the version of this function that
2503 /// only takes one argument.
2504 ///
2505 /// parseIndexList
2506 /// ::= (',' uint32)+
2507 ///
2508 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2509  bool &AteExtraComma) {
2510  AteExtraComma = false;
2511 
2512  if (Lex.getKind() != lltok::comma)
2513  return tokError("expected ',' as start of index list");
2514 
2515  while (EatIfPresent(lltok::comma)) {
2516  if (Lex.getKind() == lltok::MetadataVar) {
2517  if (Indices.empty())
2518  return tokError("expected index");
2519  AteExtraComma = true;
2520  return false;
2521  }
2522  unsigned Idx = 0;
2523  if (parseUInt32(Idx))
2524  return true;
2525  Indices.push_back(Idx);
2526  }
2527 
2528  return false;
2529 }
2530 
2531 //===----------------------------------------------------------------------===//
2532 // Type Parsing.
2533 //===----------------------------------------------------------------------===//
2534 
2535 /// parseType - parse a type.
2536 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2537  SMLoc TypeLoc = Lex.getLoc();
2538  switch (Lex.getKind()) {
2539  default:
2540  return tokError(Msg);
2541  case lltok::Type:
2542  // Type ::= 'float' | 'void' (etc)
2543  Result = Lex.getTyVal();
2544  Lex.Lex();
2545  break;
2546  case lltok::lbrace:
2547  // Type ::= StructType
2548  if (parseAnonStructType(Result, false))
2549  return true;
2550  break;
2551  case lltok::lsquare:
2552  // Type ::= '[' ... ']'
2553  Lex.Lex(); // eat the lsquare.
2554  if (parseArrayVectorType(Result, false))
2555  return true;
2556  break;
2557  case lltok::less: // Either vector or packed struct.
2558  // Type ::= '<' ... '>'
2559  Lex.Lex();
2560  if (Lex.getKind() == lltok::lbrace) {
2561  if (parseAnonStructType(Result, true) ||
2562  parseToken(lltok::greater, "expected '>' at end of packed struct"))
2563  return true;
2564  } else if (parseArrayVectorType(Result, true))
2565  return true;
2566  break;
2567  case lltok::LocalVar: {
2568  // Type ::= %foo
2569  std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2570 
2571  // If the type hasn't been defined yet, create a forward definition and
2572  // remember where that forward def'n was seen (in case it never is defined).
2573  if (!Entry.first) {
2574  Entry.first = StructType::create(Context, Lex.getStrVal());
2575  Entry.second = Lex.getLoc();
2576  }
2577  Result = Entry.first;
2578  Lex.Lex();
2579  break;
2580  }
2581 
2582  case lltok::LocalVarID: {
2583  // Type ::= %4
2584  std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2585 
2586  // If the type hasn't been defined yet, create a forward definition and
2587  // remember where that forward def'n was seen (in case it never is defined).
2588  if (!Entry.first) {
2589  Entry.first = StructType::create(Context);
2590  Entry.second = Lex.getLoc();
2591  }
2592  Result = Entry.first;
2593  Lex.Lex();
2594  break;
2595  }
2596  }
2597 
2598  // parse the type suffixes.
2599  while (true) {
2600  switch (Lex.getKind()) {
2601  // End of type.
2602  default:
2603  if (!AllowVoid && Result->isVoidTy())
2604  return error(TypeLoc, "void type only allowed for function results");
2605  return false;
2606 
2607  // Type ::= Type '*'
2608  case lltok::star:
2609  if (Result->isLabelTy())
2610  return tokError("basic block pointers are invalid");
2611  if (Result->isVoidTy())
2612  return tokError("pointers to void are invalid - use i8* instead");
2613  if (!PointerType::isValidElementType(Result))
2614  return tokError("pointer to this type is invalid");
2615  Result = PointerType::getUnqual(Result);
2616  Lex.Lex();
2617  break;
2618 
2619  // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2620  case lltok::kw_addrspace: {
2621  if (Result->isLabelTy())
2622  return tokError("basic block pointers are invalid");
2623  if (Result->isVoidTy())
2624  return tokError("pointers to void are invalid; use i8* instead");
2625  if (!PointerType::isValidElementType(Result))
2626  return tokError("pointer to this type is invalid");
2627  unsigned AddrSpace;
2628  if (parseOptionalAddrSpace(AddrSpace) ||
2629  parseToken(lltok::star, "expected '*' in address space"))
2630  return true;
2631 
2632  Result = PointerType::get(Result, AddrSpace);
2633  break;
2634  }
2635 
2636  /// Types '(' ArgTypeListI ')' OptFuncAttrs
2637  case lltok::lparen:
2638  if (parseFunctionType(Result))
2639  return true;
2640  break;
2641  }
2642  }
2643 }
2644 
2645 /// parseParameterList
2646 /// ::= '(' ')'
2647 /// ::= '(' Arg (',' Arg)* ')'
2648 /// Arg
2649 /// ::= Type OptionalAttributes Value OptionalAttributes
2650 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2651  PerFunctionState &PFS, bool IsMustTailCall,
2652  bool InVarArgsFunc) {
2653  if (parseToken(lltok::lparen, "expected '(' in call"))
2654  return true;
2655 
2656  while (Lex.getKind() != lltok::rparen) {
2657  // If this isn't the first argument, we need a comma.
2658  if (!ArgList.empty() &&
2659  parseToken(lltok::comma, "expected ',' in argument list"))
2660  return true;
2661 
2662  // parse an ellipsis if this is a musttail call in a variadic function.
2663  if (Lex.getKind() == lltok::dotdotdot) {
2664  const char *Msg = "unexpected ellipsis in argument list for ";
2665  if (!IsMustTailCall)
2666  return tokError(Twine(Msg) + "non-musttail call");
2667  if (!InVarArgsFunc)
2668  return tokError(Twine(Msg) + "musttail call in non-varargs function");
2669  Lex.Lex(); // Lex the '...', it is purely for readability.
2670  return parseToken(lltok::rparen, "expected ')' at end of argument list");
2671  }
2672 
2673  // parse the argument.
2674  LocTy ArgLoc;
2675  Type *ArgTy = nullptr;
2676  AttrBuilder ArgAttrs;
2677  Value *V;
2678  if (parseType(ArgTy, ArgLoc))
2679  return true;
2680 
2681  if (ArgTy->isMetadataTy()) {
2682  if (parseMetadataAsValue(V, PFS))
2683  return true;
2684  } else {
2685  // Otherwise, handle normal operands.
2686  if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2687  return true;
2688  }
2689  ArgList.push_back(ParamInfo(
2690  ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2691  }
2692 
2693  if (IsMustTailCall && InVarArgsFunc)
2694  return tokError("expected '...' at end of argument list for musttail call "
2695  "in varargs function");
2696 
2697  Lex.Lex(); // Lex the ')'.
2698  return false;
2699 }
2700 
2701 /// parseRequiredTypeAttr
2702 /// ::= attrname(<ty>)
2703 bool LLParser::parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName) {
2704  Result = nullptr;
2705  if (!EatIfPresent(AttrName))
2706  return true;
2707  if (!EatIfPresent(lltok::lparen))
2708  return error(Lex.getLoc(), "expected '('");
2709  if (parseType(Result))
2710  return true;
2711  if (!EatIfPresent(lltok::rparen))
2712  return error(Lex.getLoc(), "expected ')'");
2713  return false;
2714 }
2715 
2716 /// parsePreallocated
2717 /// ::= preallocated(<ty>)
2718 bool LLParser::parsePreallocated(Type *&Result) {
2719  return parseRequiredTypeAttr(Result, lltok::kw_preallocated);
2720 }
2721 
2722 /// parseInalloca
2723 /// ::= inalloca(<ty>)
2724 bool LLParser::parseInalloca(Type *&Result) {
2725  return parseRequiredTypeAttr(Result, lltok::kw_inalloca);
2726 }
2727 
2728 /// parseByRef
2729 /// ::= byref(<type>)
2730 bool LLParser::parseByRef(Type *&Result) {
2731  return parseRequiredTypeAttr(Result, lltok::kw_byref);
2732 }
2733 
2734 /// parseOptionalOperandBundles
2735 /// ::= /*empty*/
2736 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2737 ///
2738 /// OperandBundle
2739 /// ::= bundle-tag '(' ')'
2740 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2741 ///
2742 /// bundle-tag ::= String Constant
2743 bool LLParser::parseOptionalOperandBundles(
2744  SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2745  LocTy BeginLoc = Lex.getLoc();
2746  if (!EatIfPresent(lltok::lsquare))
2747  return false;
2748 
2749  while (Lex.getKind() != lltok::rsquare) {
2750  // If this isn't the first operand bundle, we need a comma.
2751  if (!BundleList.empty() &&
2752  parseToken(lltok::comma, "expected ',' in input list"))
2753  return true;
2754 
2755  std::string Tag;
2756  if (parseStringConstant(Tag))
2757  return true;
2758 
2759  if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2760  return true;
2761 
2762  std::vector<Value *> Inputs;
2763  while (Lex.getKind() != lltok::rparen) {
2764  // If this isn't the first input, we need a comma.
2765  if (!Inputs.empty() &&
2766  parseToken(lltok::comma, "expected ',' in input list"))
2767  return true;
2768 
2769  Type *Ty = nullptr;
2770  Value *Input = nullptr;
2771  if (parseType(Ty) || parseValue(Ty, Input, PFS))
2772  return true;
2773  Inputs.push_back(Input);
2774  }
2775 
2776  BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2777 
2778  Lex.Lex(); // Lex the ')'.
2779  }
2780 
2781  if (BundleList.empty())
2782  return error(BeginLoc, "operand bundle set must not be empty");
2783 
2784  Lex.Lex(); // Lex the ']'.
2785  return false;
2786 }
2787 
2788 /// parseArgumentList - parse the argument list for a function type or function
2789 /// prototype.
2790 /// ::= '(' ArgTypeListI ')'
2791 /// ArgTypeListI
2792 /// ::= /*empty*/
2793 /// ::= '...'
2794 /// ::= ArgTypeList ',' '...'
2795 /// ::= ArgType (',' ArgType)*
2796 ///
2797 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2798  bool &IsVarArg) {
2799  unsigned CurValID = 0;
2800  IsVarArg = false;
2801  assert(Lex.getKind() == lltok::lparen);
2802  Lex.Lex(); // eat the (.
2803 
2804  if (Lex.getKind() == lltok::rparen) {
2805  // empty
2806  } else if (Lex.getKind() == lltok::dotdotdot) {
2807  IsVarArg = true;
2808  Lex.Lex();
2809  } else {
2810  LocTy TypeLoc = Lex.getLoc();
2811  Type *ArgTy = nullptr;
2813  std::string Name;
2814 
2815  if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2816  return true;
2817 
2818  if (ArgTy->isVoidTy())
2819  return error(TypeLoc, "argument can not have void type");
2820 
2821  if (Lex.getKind() == lltok::LocalVar) {
2822  Name = Lex.getStrVal();
2823  Lex.Lex();
2824  } else if (Lex.getKind() == lltok::LocalVarID) {
2825  if (Lex.getUIntVal() != CurValID)
2826  return error(TypeLoc, "argument expected to be numbered '%" +
2827  Twine(CurValID) + "'");
2828  ++CurValID;
2829  Lex.Lex();
2830  }
2831 
2833  return error(TypeLoc, "invalid type for function argument");
2834 
2835  ArgList.emplace_back(TypeLoc, ArgTy,
2836  AttributeSet::get(ArgTy->getContext(), Attrs),
2837  std::move(Name));
2838 
2839  while (EatIfPresent(lltok::comma)) {
2840  // Handle ... at end of arg list.
2841  if (EatIfPresent(lltok::dotdotdot)) {
2842  IsVarArg = true;
2843  break;
2844  }
2845 
2846  // Otherwise must be an argument type.
2847  TypeLoc = Lex.getLoc();
2848  if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2849  return true;
2850 
2851  if (ArgTy->isVoidTy())
2852  return error(TypeLoc, "argument can not have void type");
2853 
2854  if (Lex.getKind() == lltok::LocalVar) {
2855  Name = Lex.getStrVal();
2856  Lex.Lex();
2857  } else {
2858  if (Lex.getKind() == lltok::LocalVarID) {
2859  if (Lex.getUIntVal() != CurValID)
2860  return error(TypeLoc, "argument expected to be numbered '%" +
2861  Twine(CurValID) + "'");
2862  Lex.Lex();
2863  }
2864  ++CurValID;
2865  Name = "";
2866  }
2867 
2868  if (!ArgTy->isFirstClassType())
2869  return error(TypeLoc, "invalid type for function argument");
2870 
2871  ArgList.emplace_back(TypeLoc, ArgTy,
2872  AttributeSet::get(ArgTy->getContext(), Attrs),
2873  std::move(Name));
2874  }
2875  }
2876 
2877  return parseToken(lltok::rparen, "expected ')' at end of argument list");
2878 }
2879 
2880 /// parseFunctionType
2881 /// ::= Type ArgumentList OptionalAttrs
2882 bool LLParser::parseFunctionType(Type *&Result) {
2883  assert(Lex.getKind() == lltok::lparen);
2884 
2885  if (!FunctionType::isValidReturnType(Result))
2886  return tokError("invalid function return type");
2887 
2888  SmallVector<ArgInfo, 8> ArgList;
2889  bool IsVarArg;
2890  if (parseArgumentList(ArgList, IsVarArg))
2891  return true;
2892 
2893  // Reject names on the arguments lists.
2894  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2895  if (!ArgList[i].Name.empty())
2896  return error(ArgList[i].Loc, "argument name invalid in function type");
2897  if (ArgList[i].Attrs.hasAttributes())
2898  return error(ArgList[i].Loc,
2899  "argument attributes invalid in function type");
2900  }
2901 
2902  SmallVector<Type*, 16> ArgListTy;
2903  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2904  ArgListTy.push_back(ArgList[i].Ty);
2905 
2906  Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2907  return false;
2908 }
2909 
2910 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2911 /// other structs.
2912 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2913  SmallVector<Type*, 8> Elts;
2914  if (parseStructBody(Elts))
2915  return true;
2916 
2917  Result = StructType::get(Context, Elts, Packed);
2918  return false;
2919 }
2920 
2921 /// parseStructDefinition - parse a struct in a 'type' definition.
2922 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2923  std::pair<Type *, LocTy> &Entry,
2924  Type *&ResultTy) {
2925  // If the type was already defined, diagnose the redefinition.
2926  if (Entry.first && !Entry.second.isValid())
2927  return error(TypeLoc, "redefinition of type");
2928 
2929  // If we have opaque, just return without filling in the definition for the
2930  // struct. This counts as a definition as far as the .ll file goes.
2931  if (EatIfPresent(lltok::kw_opaque)) {
2932  // This type is being defined, so clear the location to indicate this.
2933  Entry.second = SMLoc();
2934 
2935  // If this type number has never been uttered, create it.
2936  if (!Entry.first)
2937  Entry.first = StructType::create(Context, Name);
2938  ResultTy = Entry.first;
2939  return false;
2940  }
2941 
2942  // If the type starts with '<', then it is either a packed struct or a vector.
2943  bool isPacked = EatIfPresent(lltok::less);
2944 
2945  // If we don't have a struct, then we have a random type alias, which we
2946  // accept for compatibility with old files. These types are not allowed to be
2947  // forward referenced and not allowed to be recursive.
2948  if (Lex.getKind() != lltok::lbrace) {
2949  if (Entry.first)
2950  return error(TypeLoc, "forward references to non-struct type");
2951 
2952  ResultTy = nullptr;
2953  if (isPacked)
2954  return parseArrayVectorType(ResultTy, true);
2955  return parseType(ResultTy);
2956  }
2957 
2958  // This type is being defined, so clear the location to indicate this.
2959  Entry.second = SMLoc();
2960 
2961  // If this type number has never been uttered, create it.
2962  if (!Entry.first)
2963  Entry.first = StructType::create(Context, Name);
2964 
2965  StructType *STy = cast<StructType>(Entry.first);
2966 
2967  SmallVector<Type*, 8> Body;
2968  if (parseStructBody(Body) ||
2969  (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2970  return true;
2971 
2972  STy->setBody(Body, isPacked);
2973  ResultTy = STy;
2974  return false;
2975 }
2976 
2977 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2978 /// StructType
2979 /// ::= '{' '}'
2980 /// ::= '{' Type (',' Type)* '}'
2981 /// ::= '<' '{' '}' '>'
2982 /// ::= '<' '{' Type (',' Type)* '}' '>'
2983 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2984  assert(Lex.getKind() == lltok::lbrace);
2985  Lex.Lex(); // Consume the '{'
2986 
2987  // Handle the empty struct.
2988  if (EatIfPresent(lltok::rbrace))
2989  return false;
2990 
2991  LocTy EltTyLoc = Lex.getLoc();
2992  Type *Ty = nullptr;
2993  if (parseType(Ty))
2994  return true;
2995  Body.push_back(Ty);
2996 
2998  return error(EltTyLoc, "invalid element type for struct");
2999 
3000  while (EatIfPresent(lltok::comma)) {
3001  EltTyLoc = Lex.getLoc();
3002  if (parseType(Ty))
3003  return true;
3004 
3006  return error(EltTyLoc, "invalid element type for struct");
3007 
3008  Body.push_back(Ty);
3009  }
3010 
3011  return parseToken(lltok::rbrace, "expected '}' at end of struct");
3012 }
3013 
3014 /// parseArrayVectorType - parse an array or vector type, assuming the first
3015 /// token has already been consumed.
3016 /// Type
3017 /// ::= '[' APSINTVAL 'x' Types ']'
3018 /// ::= '<' APSINTVAL 'x' Types '>'
3019 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3020 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3021  bool Scalable = false;
3022 
3023  if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3024  Lex.Lex(); // consume the 'vscale'
3025  if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3026  return true;
3027 
3028  Scalable = true;
3029  }
3030 
3031  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3032  Lex.getAPSIntVal().getBitWidth() > 64)
3033  return tokError("expected number in address space");
3034 
3035  LocTy SizeLoc = Lex.getLoc();
3036  uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3037  Lex.Lex();
3038 
3039  if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3040  return true;
3041 
3042  LocTy TypeLoc = Lex.getLoc();
3043  Type *EltTy = nullptr;
3044  if (parseType(EltTy))
3045  return true;
3046 
3047  if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3048  "expected end of sequential type"))
3049  return true;
3050 
3051  if (IsVector) {
3052  if (Size == 0)
3053  return error(SizeLoc, "zero element vector is illegal");
3054  if ((unsigned)Size != Size)
3055  return error(SizeLoc, "size too large for vector");
3056  if (!VectorType::isValidElementType(EltTy))
3057  return error(TypeLoc, "invalid vector element type");
3058  Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3059  } else {
3060  if (!ArrayType::isValidElementType(EltTy))
3061  return error(TypeLoc, "invalid array element type");
3062  Result = ArrayType::get(EltTy, Size);
3063  }
3064  return false;
3065 }
3066 
3067 //===----------------------------------------------------------------------===//
3068 // Function Semantic Analysis.
3069 //===----------------------------------------------------------------------===//
3070 
3071 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3072  int functionNumber)
3073  : P(p), F(f), FunctionNumber(functionNumber) {
3074 
3075  // Insert unnamed arguments into the NumberedVals list.
3076  for (Argument &A : F.args())
3077  if (!A.hasName())
3078  NumberedVals.push_back(&A);
3079 }
3080 
3081 LLParser::PerFunctionState::~PerFunctionState() {
3082  // If there were any forward referenced non-basicblock values, delete them.
3083 
3084  for (const auto &P : ForwardRefVals) {
3085  if (isa<BasicBlock>(P.second.first))
3086  continue;
3087  P.second.first->replaceAllUsesWith(
3088  UndefValue::get(P.second.first->getType()));
3089  P.second.first->deleteValue();
3090  }
3091 
3092  for (const auto &P : ForwardRefValIDs) {
3093  if (isa<BasicBlock>(P.second.first))
3094  continue;
3095  P.second.first->replaceAllUsesWith(
3096  UndefValue::get(P.second.first->getType()));
3097  P.second.first->deleteValue();
3098  }
3099 }
3100 
3101 bool LLParser::PerFunctionState::finishFunction() {
3102  if (!ForwardRefVals.empty())
3103  return P.error(ForwardRefVals.begin()->second.second,
3104  "use of undefined value '%" + ForwardRefVals.begin()->first +
3105  "'");
3106  if (!ForwardRefValIDs.empty())
3107  return P.error(ForwardRefValIDs.begin()->second.second,
3108  "use of undefined value '%" +
3109  Twine(ForwardRefValIDs.begin()->first) + "'");
3110  return false;
3111 }
3112 
3113 /// getVal - Get a value with the specified name or ID, creating a
3114 /// forward reference record if needed. This can return null if the value
3115 /// exists but does not have the right type.
3116 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3117  LocTy Loc, bool IsCall) {
3118  // Look this name up in the normal function symbol table.
3119  Value *Val = F.getValueSymbolTable()->lookup(Name);
3120 
3121  // If this is a forward reference for the value, see if we already created a
3122  // forward ref record.
3123  if (!Val) {
3124  auto I = ForwardRefVals.find(Name);
3125  if (I != ForwardRefVals.end())
3126  Val = I->second.first;
3127  }
3128 
3129  // If we have the value in the symbol table or fwd-ref table, return it.
3130  if (Val)
3131  return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
3132 
3133  // Don't make placeholders with invalid type.
3134  if (!Ty->isFirstClassType()) {
3135  P.error(Loc, "invalid use of a non-first-class type");
3136  return nullptr;
3137  }
3138 
3139  // Otherwise, create a new forward reference for this value and remember it.
3140  Value *FwdVal;
3141  if (Ty->isLabelTy()) {
3142  FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3143  } else {
3144  FwdVal = new Argument(Ty, Name);
3145  }
3146 
3147  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3148  return FwdVal;
3149 }
3150 
3151 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc,
3152  bool IsCall) {
3153  // Look this name up in the normal function symbol table.
3154  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3155 
3156  // If this is a forward reference for the value, see if we already created a
3157  // forward ref record.
3158  if (!Val) {
3159  auto I = ForwardRefValIDs.find(ID);
3160  if (I != ForwardRefValIDs.end())
3161  Val = I->second.first;
3162  }
3163 
3164  // If we have the value in the symbol table or fwd-ref table, return it.
3165  if (Val)
3166  return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
3167 
3168  if (!Ty->isFirstClassType()) {
3169  P.error(Loc, "invalid use of a non-first-class type");
3170  return nullptr;
3171  }
3172 
3173  // Otherwise, create a new forward reference for this value and remember it.
3174  Value *FwdVal;
3175  if (Ty->isLabelTy()) {
3176  FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3177  } else {
3178  FwdVal = new Argument(Ty);
3179  }
3180 
3181  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3182  return FwdVal;
3183 }
3184 
3185 /// setInstName - After an instruction is parsed and inserted into its
3186 /// basic block, this installs its name.
3187 bool LLParser::PerFunctionState::setInstName(int NameID,
3188  const std::string &NameStr,
3189  LocTy NameLoc, Instruction *Inst) {
3190  // If this instruction has void type, it cannot have a name or ID specified.
3191  if (Inst->getType()->isVoidTy()) {
3192  if (NameID != -1 || !NameStr.empty())
3193  return P.error(NameLoc, "instructions returning void cannot have a name");
3194  return false;
3195  }
3196 
3197  // If this was a numbered instruction, verify that the instruction is the
3198  // expected value and resolve any forward references.
3199  if (NameStr.empty()) {
3200  // If neither a name nor an ID was specified, just use the next ID.
3201  if (NameID == -1)
3202  NameID = NumberedVals.size();
3203 
3204  if (unsigned(NameID) != NumberedVals.size())
3205  return P.error(NameLoc, "instruction expected to be numbered '%" +
3206  Twine(NumberedVals.size()) + "'");
3207 
3208  auto FI = ForwardRefValIDs.find(NameID);
3209  if (FI != ForwardRefValIDs.end()) {
3210  Value *Sentinel = FI->second.first;
3211  if (Sentinel->getType() != Inst->getType())
3212  return P.error(NameLoc, "instruction forward referenced with type '" +
3213  getTypeString(FI->second.first->getType()) +
3214  "'");
3215 
3216  Sentinel->replaceAllUsesWith(Inst);
3217  Sentinel->deleteValue();
3218  ForwardRefValIDs.erase(FI);
3219  }
3220 
3221  NumberedVals.push_back(Inst);
3222  return false;
3223  }
3224 
3225  // Otherwise, the instruction had a name. Resolve forward refs and set it.
3226  auto FI = ForwardRefVals.find(NameStr);
3227  if (FI != ForwardRefVals.end()) {
3228  Value *Sentinel = FI->second.first;
3229  if (Sentinel->getType() != Inst->getType())
3230  return P.error(NameLoc, "instruction forward referenced with type '" +
3231  getTypeString(FI->second.first->getType()) +
3232  "'");
3233 
3234  Sentinel->replaceAllUsesWith(Inst);
3235  Sentinel->deleteValue();
3236  ForwardRefVals.erase(FI);
3237  }
3238 
3239  // Set the name on the instruction.
3240  Inst->setName(NameStr);
3241 
3242  if (Inst->getName() != NameStr)
3243  return P.error(NameLoc, "multiple definition of local value named '" +
3244  NameStr + "'");
3245  return false;
3246 }
3247 
3248 /// getBB - Get a basic block with the specified name or ID, creating a
3249 /// forward reference record if needed.
3250 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3251  LocTy Loc) {
3252  return dyn_cast_or_null<BasicBlock>(
3253  getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3254 }
3255 
3256 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3257  return dyn_cast_or_null<BasicBlock>(
3258  getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3259 }
3260 
3261 /// defineBB - Define the specified basic block, which is either named or
3262 /// unnamed. If there is an error, this returns null otherwise it returns
3263 /// the block being defined.
3264 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3265  int NameID, LocTy Loc) {
3266  BasicBlock *BB;
3267  if (Name.empty()) {
3268  if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3269  P.error(Loc, "label expected to be numbered '" +
3270  Twine(NumberedVals.size()) + "'");
3271  return nullptr;
3272  }
3273  BB = getBB(NumberedVals.size(), Loc);
3274  if (!BB) {
3275  P.error(Loc, "unable to create block numbered '" +
3276  Twine(NumberedVals.size()) + "'");
3277  return nullptr;
3278  }
3279  } else {
3280  BB = getBB(Name, Loc);
3281  if (!BB) {
3282  P.error(Loc, "unable to create block named '" + Name + "'");
3283  return nullptr;
3284  }
3285  }
3286 
3287  // Move the block to the end of the function. Forward ref'd blocks are
3288  // inserted wherever they happen to be referenced.
3289  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3290 
3291  // Remove the block from forward ref sets.
3292  if (Name.empty()) {
3293  ForwardRefValIDs.erase(NumberedVals.size());
3294  NumberedVals.push_back(BB);
3295  } else {
3296  // BB forward references are already in the function symbol table.
3297  ForwardRefVals.erase(Name);
3298  }
3299 
3300  return BB;
3301 }
3302 
3303 //===----------------------------------------------------------------------===//
3304 // Constants.
3305 //===----------------------------------------------------------------------===//
3306 
3307 /// parseValID - parse an abstract value that doesn't necessarily have a
3308 /// type implied. For example, if we parse "4" we don't know what integer type
3309 /// it has. The value will later be combined with its type and checked for
3310 /// sanity. PFS is used to convert function-local operands of metadata (since
3311 /// metadata operands are not just parsed here but also converted to values).
3312 /// PFS can be null when we are not parsing metadata values inside a function.
3313 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS) {
3314  ID.Loc = Lex.getLoc();
3315  switch (Lex.getKind()) {
3316  default:
3317  return tokError("expected value token");
3318  case lltok::GlobalID: // @42
3319  ID.UIntVal = Lex.getUIntVal();
3320  ID.Kind = ValID::t_GlobalID;
3321  break;
3322  case lltok::GlobalVar: // @foo
3323  ID.StrVal = Lex.getStrVal();
3324  ID.Kind = ValID::t_GlobalName;
3325  break;
3326  case lltok::LocalVarID: // %42
3327  ID.UIntVal = Lex.getUIntVal();
3328  ID.Kind = ValID::t_LocalID;
3329  break;
3330  case lltok::LocalVar: // %foo
3331  ID.StrVal = Lex.getStrVal();
3332  ID.Kind = ValID::t_LocalName;
3333  break;
3334  case lltok::APSInt:
3335  ID.APSIntVal = Lex.getAPSIntVal();
3336  ID.Kind = ValID::t_APSInt;
3337  break;
3338  case lltok::APFloat:
3339  ID.APFloatVal = Lex.getAPFloatVal();
3340  ID.Kind = ValID::t_APFloat;
3341  break;
3342  case lltok::kw_true:
3343  ID.ConstantVal = ConstantInt::getTrue(Context);
3344  ID.Kind = ValID::t_Constant;
3345  break;
3346  case lltok::kw_false:
3347  ID.ConstantVal = ConstantInt::getFalse(Context);
3348  ID.Kind = ValID::t_Constant;
3349  break;
3350  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3351  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3352  case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3353  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3354  case lltok::kw_none: ID.Kind = ValID::t_None; break;
3355 
3356  case lltok::lbrace: {
3357  // ValID ::= '{' ConstVector '}'
3358  Lex.Lex();
3360  if (parseGlobalValueVector(Elts) ||
3361  parseToken(lltok::rbrace, "expected end of struct constant"))
3362  return true;
3363 
3364  ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3365  ID.UIntVal = Elts.size();
3366  memcpy(ID.ConstantStructElts.get(), Elts.data(),
3367  Elts.size() * sizeof(Elts[0]));
3368  ID.Kind = ValID::t_ConstantStruct;
3369  return false;
3370  }
3371  case lltok::less: {
3372  // ValID ::= '<' ConstVector '>' --> Vector.
3373  // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3374  Lex.Lex();
3375  bool isPackedStruct = EatIfPresent(lltok::lbrace);
3376 
3378  LocTy FirstEltLoc = Lex.getLoc();
3379  if (parseGlobalValueVector(Elts) ||
3380  (isPackedStruct &&
3381  parseToken(lltok::rbrace, "expected end of packed struct")) ||
3382  parseToken(lltok::greater, "expected end of constant"))
3383  return true;
3384 
3385  if (isPackedStruct) {
3386  ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3387  memcpy(ID.ConstantStructElts.get(), Elts.data(),
3388  Elts.size() * sizeof(Elts[0]));
3389  ID.UIntVal = Elts.size();
3391  return false;
3392  }
3393 
3394  if (Elts.empty())
3395  return error(ID.Loc, "constant vector must not be empty");
3396 
3397  if (!Elts[0]->getType()->isIntegerTy() &&
3398  !Elts[0]->getType()->isFloatingPointTy() &&
3399  !Elts[0]->getType()->isPointerTy())
3400  return error(
3401  FirstEltLoc,
3402  "vector elements must have integer, pointer or floating point type");
3403 
3404  // Verify that all the vector elements have the same type.
3405  for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3406  if (Elts[i]->getType() != Elts[0]->getType())
3407  return error(FirstEltLoc, "vector element #" + Twine(i) +
3408  " is not of type '" +
3409  getTypeString(Elts[0]->getType()));
3410 
3411  ID.ConstantVal = ConstantVector::get(Elts);
3412  ID.Kind = ValID::t_Constant;
3413  return false;
3414  }
3415  case lltok::lsquare: { // Array Constant
3416  Lex.Lex();
3418  LocTy FirstEltLoc = Lex.getLoc();
3419  if (parseGlobalValueVector(Elts) ||
3420  parseToken(lltok::rsquare, "expected end of array constant"))
3421  return true;
3422 
3423  // Handle empty element.
3424  if (Elts.empty()) {
3425  // Use undef instead of an array because it's inconvenient to determine
3426  // the element type at this point, there being no elements to examine.
3427  ID.Kind = ValID::t_EmptyArray;
3428  return false;
3429  }
3430 
3431  if (!Elts[0]->getType()->isFirstClassType())
3432  return error(FirstEltLoc, "invalid array element type: " +
3433  getTypeString(Elts[0]->getType()));
3434 
3435  ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3436 
3437  // Verify all elements are correct type!
3438  for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3439  if (Elts[i]->getType() != Elts[0]->getType())
3440  return error(FirstEltLoc, "array element #" + Twine(i) +
3441  " is not of type '" +
3442  getTypeString(Elts[0]->getType()));
3443  }
3444 
3445  ID.ConstantVal = ConstantArray::get(ATy, Elts);
3446  ID.Kind = ValID::t_Constant;
3447  return false;
3448  }
3449  case lltok::kw_c: // c "foo"
3450  Lex.Lex();
3451  ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3452  false);
3453  if (parseToken(lltok::StringConstant, "expected string"))
3454  return true;
3455  ID.Kind = ValID::t_Constant;
3456  return false;
3457 
3458  case lltok::kw_asm: {
3459  // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3460  // STRINGCONSTANT
3461  bool HasSideEffect, AlignStack, AsmDialect;
3462  Lex.Lex();
3463  if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3464  parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3465  parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3466  parseStringConstant(ID.StrVal) ||
3467  parseToken(lltok::comma, "expected comma in inline asm expression") ||
3468  parseToken(lltok::StringConstant, "expected constraint string"))
3469  return true;
3470  ID.StrVal2 = Lex.getStrVal();
3471  ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3472  (unsigned(AsmDialect)<<2);
3473  ID.Kind = ValID::t_InlineAsm;
3474  return false;
3475  }
3476 
3477  case lltok::kw_blockaddress: {
3478  // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3479  Lex.Lex();
3480 
3481  ValID Fn, Label;
3482 
3483  if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3484  parseValID(Fn) ||
3485  parseToken(lltok::comma,
3486  "expected comma in block address expression") ||
3487  parseValID(Label) ||
3488  parseToken(lltok::rparen, "expected ')' in block address expression"))
3489  return true;
3490 
3491  if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3492  return error(Fn.Loc, "expected function name in blockaddress");
3493  if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3494  return error(Label.Loc, "expected basic block name in blockaddress");
3495 
3496  // Try to find the function (but skip it if it's forward-referenced).
3497  GlobalValue *GV = nullptr;
3498  if (Fn.Kind == ValID::t_GlobalID) {
3499  if (Fn.UIntVal < NumberedVals.size())
3500  GV = NumberedVals[Fn.UIntVal];
3501  } else if (!ForwardRefVals.count(Fn.StrVal)) {
3502  GV = M->getNamedValue(Fn.StrVal);
3503  }
3504  Function *F = nullptr;
3505  if (GV) {
3506  // Confirm that it's actually a function with a definition.
3507  if (!isa<Function>(GV))
3508  return error(Fn.Loc, "expected function name in blockaddress");
3509  F = cast<Function>(GV);
3510  if (F->isDeclaration())
3511  return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3512  }
3513 
3514  if (!F) {
3515  // Make a global variable as a placeholder for this reference.
3516  GlobalValue *&FwdRef =
3517  ForwardRefBlockAddresses.insert(std::make_pair(
3518  std::move(Fn),
3519  std::map<ValID, GlobalValue *>()))
3520  .first->second.insert(std::make_pair(std::move(Label), nullptr))
3521  .first->second;
3522  if (!FwdRef)
3523  FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3524  GlobalValue::InternalLinkage, nullptr, "");
3525  ID.ConstantVal = FwdRef;
3526  ID.Kind = ValID::t_Constant;
3527  return false;
3528  }
3529 
3530  // We found the function; now find the basic block. Don't use PFS, since we
3531  // might be inside a constant expression.
3532  BasicBlock *BB;
3533  if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3534  if (Label.Kind == ValID::t_LocalID)
3535  BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3536  else
3537  BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3538  if (!BB)
3539  return error(Label.Loc, "referenced value is not a basic block");
3540  } else {
3541  if (Label.Kind == ValID::t_LocalID)
3542  return error(Label.Loc, "cannot take address of numeric label after "
3543  "the function is defined");
3544  BB = dyn_cast_or_null<BasicBlock>(
3545  F->getValueSymbolTable()->lookup(Label.StrVal));
3546  if (!BB)
3547  return error(Label.Loc, "referenced value is not a basic block");
3548  }
3549 
3550  ID.ConstantVal = BlockAddress::get(F, BB);
3551  ID.Kind = ValID::t_Constant;
3552  return false;
3553  }
3554 
3556  // ValID ::= 'dso_local_equivalent' @foo
3557  Lex.Lex();
3558 
3559  ValID Fn;
3560 
3561  if (parseValID(Fn))
3562  return true;
3563 
3564  if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3565  return error(Fn.Loc,
3566  "expected global value name in dso_local_equivalent");
3567 
3568  // Try to find the function (but skip it if it's forward-referenced).
3569  GlobalValue *GV = nullptr;
3570  if (Fn.Kind == ValID::t_GlobalID) {
3571  if (Fn.UIntVal < NumberedVals.size())
3572  GV = NumberedVals[Fn.UIntVal];
3573  } else if (!ForwardRefVals.count(Fn.StrVal)) {
3574  GV = M->getNamedValue(Fn.StrVal);
3575  }
3576 
3577  assert(GV && "Could not find a corresponding global variable");
3578 
3579  if (!GV->getValueType()->isFunctionTy())
3580  return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3581  "in dso_local_equivalent");
3582 
3583  ID.ConstantVal = DSOLocalEquivalent::get(GV);
3584  ID.Kind = ValID::t_Constant;
3585  return false;
3586  }
3587 
3588  case lltok::kw_trunc:
3589  case lltok::kw_zext:
3590  case lltok::kw_sext:
3591  case lltok::kw_fptrunc:
3592  case lltok::kw_fpext:
3593  case lltok::kw_bitcast:
3595  case lltok::kw_uitofp:
3596  case lltok::kw_sitofp:
3597  case lltok::kw_fptoui:
3598  case lltok::kw_fptosi:
3599  case lltok::kw_inttoptr:
3600  case lltok::kw_ptrtoint: {
3601  unsigned Opc = Lex.getUIntVal();
3602  Type *DestTy = nullptr;
3603  Constant *SrcVal;
3604  Lex.Lex();
3605  if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3606  parseGlobalTypeAndValue(SrcVal) ||
3607  parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3608  parseType(DestTy) ||
3609  parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3610  return true;
3611  if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3612  return error(ID.Loc, "invalid cast opcode for cast from '" +
3613  getTypeString(SrcVal->getType()) + "' to '" +
3614  getTypeString(DestTy) + "'");
3615  ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3616  SrcVal, DestTy);
3617  ID.Kind = ValID::t_Constant;
3618  return false;
3619  }
3620  case lltok::kw_extractvalue: {
3621  Lex.Lex();
3622  Constant *Val;
3623  SmallVector<unsigned, 4> Indices;
3624  if (parseToken(lltok::lparen,
3625  "expected '(' in extractvalue constantexpr") ||
3626  parseGlobalTypeAndValue(Val) || parseIndexList(Indices) ||
3627  parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3628  return true;
3629 
3630  if (!Val->getType()->isAggregateType())
3631  return error(ID.Loc, "extractvalue operand must be aggregate type");
3632  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3633  return error(ID.Loc, "invalid indices for extractvalue");
3634  ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3635  ID.Kind = ValID::t_Constant;
3636  return false;
3637  }
3638  case lltok::kw_insertvalue: {
3639  Lex.Lex();
3640  Constant *Val0, *Val1;
3641  SmallVector<unsigned, 4> Indices;
3642  if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") ||
3643  parseGlobalTypeAndValue(Val0) ||
3644  parseToken(lltok::comma,
3645  "expected comma in insertvalue constantexpr") ||
3646  parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) ||
3647  parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3648  return true;
3649  if (!Val0->getType()->isAggregateType())
3650  return error(ID.Loc, "insertvalue operand must be aggregate type");
3651  Type *IndexedType =
3652  ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3653  if (!IndexedType)
3654  return error(ID.Loc, "invalid indices for insertvalue");
3655  if (IndexedType != Val1->getType())
3656  return error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3657  getTypeString(Val1->getType()) +
3658  "' instead of '" + getTypeString(IndexedType) +
3659  "'");
3660  ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3661  ID.Kind = ValID::t_Constant;
3662  return false;
3663  }
3664  case lltok::kw_icmp:
3665  case lltok::kw_fcmp: {
3666  unsigned PredVal, Opc = Lex.getUIntVal();
3667  Constant *Val0, *Val1;
3668  Lex.Lex();
3669  if (parseCmpPredicate(PredVal, Opc) ||
3670  parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3671  parseGlobalTypeAndValue(Val0) ||
3672  parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3673  parseGlobalTypeAndValue(Val1) ||
3674  parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3675  return true;
3676 
3677  if (Val0->getType() != Val1->getType())
3678  return error(ID.Loc, "compare operands must have the same type");
3679 
3680  CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3681 
3682  if (Opc == Instruction::FCmp) {
3683  if (!Val0->getType()->isFPOrFPVectorTy())
3684  return error(ID.Loc, "fcmp requires floating point operands");
3685  ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3686  } else {
3687  assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3688  if (!Val0->getType()->isIntOrIntVectorTy() &&
3689  !Val0->getType()->isPtrOrPtrVectorTy())
3690  return error(ID.Loc, "icmp requires pointer or integer operands");
3691  ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3692  }
3693  ID.Kind = ValID::t_Constant;
3694  return false;
3695  }
3696 
3697  // Unary Operators.
3698  case lltok::kw_fneg: {
3699  unsigned Opc = Lex.getUIntVal();
3700  Constant *Val;
3701  Lex.Lex();
3702  if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3703  parseGlobalTypeAndValue(Val) ||
3704  parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3705  return true;
3706 
3707  // Check that the type is valid for the operator.
3708  switch (Opc) {
3709  case Instruction::FNeg:
3710  if (!Val->getType()->isFPOrFPVectorTy())
3711  return error(ID.Loc, "constexpr requires fp operands");
3712  break;
3713  default: llvm_unreachable("Unknown unary operator!");
3714  }
3715  unsigned Flags = 0;
3716  Constant *C = ConstantExpr::get(Opc, Val, Flags);
3717  ID.ConstantVal = C;
3718  ID.Kind = ValID::t_Constant;
3719  return false;
3720  }
3721  // Binary Operators.
3722  case lltok::kw_add:
3723  case lltok::kw_fadd:
3724  case lltok::kw_sub:
3725  case lltok::kw_fsub:
3726  case lltok::kw_mul:
3727  case lltok::kw_fmul:
3728  case lltok::kw_udiv:
3729  case lltok::kw_sdiv:
3730  case lltok::kw_fdiv:
3731  case lltok::kw_urem:
3732  case lltok::kw_srem:
3733  case lltok::kw_frem:
3734  case lltok::kw_shl:
3735  case lltok::kw_lshr:
3736  case lltok::kw_ashr: {
3737  bool NUW = false;
3738  bool NSW = false;
3739  bool Exact = false;
3740  unsigned Opc = Lex.getUIntVal();
3741  Constant *Val0, *Val1;
3742  Lex.Lex();
3743  if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3744  Opc == Instruction::Mul || Opc == Instruction::Shl) {
3745  if (EatIfPresent(lltok::kw_nuw))
3746  NUW = true;
3747  if (EatIfPresent(lltok::kw_nsw)) {
3748  NSW = true;
3749  if (EatIfPresent(lltok::kw_nuw))
3750  NUW = true;
3751  }
3752  } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3753  Opc == Instruction::LShr || Opc == Instruction::AShr) {
3754  if (EatIfPresent(lltok::kw_exact))
3755  Exact = true;
3756  }
3757  if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3758  parseGlobalTypeAndValue(Val0) ||
3759  parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3760  parseGlobalTypeAndValue(Val1) ||
3761  parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3762  return true;
3763  if (Val0->getType() != Val1->getType())
3764  return error(ID.Loc, "operands of constexpr must have same type");
3765  // Check that the type is valid for the operator.
3766  switch (Opc) {
3767  case Instruction::Add:
3768  case Instruction::Sub:
3769  case Instruction::Mul:
3770  case Instruction::UDiv:
3771  case Instruction::SDiv:
3772  case Instruction::URem:
3773  case Instruction::SRem:
3774  case Instruction::Shl:
3775  case Instruction::AShr:
3776  case Instruction::LShr:
3777  if (!Val0->getType()->isIntOrIntVectorTy())
3778  return error(ID.Loc, "constexpr requires integer operands");
3779  break;
3780  case Instruction::FAdd:
3781  case Instruction::FSub:
3782  case Instruction::FMul:
3783  case Instruction::FDiv:
3784  case Instruction::FRem:
3785  if (!Val0->getType()->isFPOrFPVectorTy())
3786  return error(ID.Loc, "constexpr requires fp operands");
3787  break;
3788  default: llvm_unreachable("Unknown binary operator!");
3789  }
3790  unsigned Flags = 0;
3792  if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3793  if (Exact) Flags |= PossiblyExactOperator::IsExact;
3794  Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3795  ID.ConstantVal = C;
3796  ID.Kind = ValID::t_Constant;
3797  return false;
3798  }
3799 
3800  // Logical Operations
3801  case lltok::kw_and:
3802  case lltok::kw_or:
3803  case lltok::kw_xor: {
3804  unsigned Opc = Lex.getUIntVal();
3805  Constant *Val0, *Val1;
3806  Lex.Lex();
3807  if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3808  parseGlobalTypeAndValue(Val0) ||
3809  parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3810  parseGlobalTypeAndValue(Val1) ||
3811  parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3812  return true;
3813  if (Val0->getType() != Val1->getType())
3814  return error(ID.Loc, "operands of constexpr must have same type");
3815  if (!Val0->getType()->isIntOrIntVectorTy())
3816  return error(ID.Loc,
3817  "constexpr requires integer or integer vector operands");
3818  ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3819  ID.Kind = ValID::t_Constant;
3820  return false;
3821  }
3822 
3827  case lltok::kw_select: {
3828  unsigned Opc = Lex.getUIntVal();
3830  bool InBounds = false;
3831  Type *Ty;
3832  Lex.Lex();
3833 
3834  if (Opc == Instruction::GetElementPtr)
3835  InBounds = EatIfPresent(lltok::kw_inbounds);
3836 
3837  if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3838  return true;
3839 
3840  LocTy ExplicitTypeLoc = Lex.getLoc();
3841  if (Opc == Instruction::GetElementPtr) {
3842  if (parseType(Ty) ||
3843  parseToken(lltok::comma, "expected comma after getelementptr's type"))
3844  return true;
3845  }
3846 
3847  Optional<unsigned> InRangeOp;
3848  if (parseGlobalValueVector(
3849  Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3850  parseToken(lltok::rparen, "expected ')' in constantexpr"))
3851  return true;
3852 
3853  if (Opc == Instruction::GetElementPtr) {
3854  if (Elts.size() == 0 ||
3855  !Elts[0]->getType()->isPtrOrPtrVectorTy())
3856  return error(ID.Loc, "base of getelementptr must be a pointer");
3857 
3858  Type *BaseType = Elts[0]->getType();
3859  auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3860  if (Ty != BasePointerType->getElementType()) {
3861  return error(
3862  ExplicitTypeLoc,
3864  "explicit pointee type doesn't match operand's pointee type",
3865  Ty, BasePointerType->getElementType()));
3866  }
3867 
3868  unsigned GEPWidth =
3869  BaseType->isVectorTy()
3870  ? cast<FixedVectorType>(BaseType)->getNumElements()
3871  : 0;
3872 
3873  ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3874  for (Constant *Val : Indices) {
3875  Type *ValTy = Val->getType();
3876  if (!ValTy->isIntOrIntVectorTy())
3877  return error(ID.Loc, "getelementptr index must be an integer");
3878  if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3879  unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3880  if (GEPWidth && (ValNumEl != GEPWidth))
3881  return error(
3882  ID.Loc,
3883  "getelementptr vector index has a wrong number of elements");
3884  // GEPWidth may have been unknown because the base is a scalar,
3885  // but it is known now.
3886  GEPWidth = ValNumEl;
3887  }
3888  }
3889 
3890  SmallPtrSet<Type*, 4> Visited;
3891  if (!Indices.empty() && !Ty->isSized(&Visited))
3892  return error(ID.Loc, "base element of getelementptr must be sized");
3893 
3894  if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3895  return error(ID.Loc, "invalid getelementptr indices");
3896 
3897  if (InRangeOp) {
3898  if (*InRangeOp == 0)
3899  return error(ID.Loc,
3900  "inrange keyword may not appear on pointer operand");
3901  --*InRangeOp;
3902  }
3903 
3904  ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3905  InBounds, InRangeOp);
3906  } else if (Opc == Instruction::Select) {
3907  if (Elts.size() != 3)
3908  return error(ID.Loc, "expected three operands to select");
3909  if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3910  Elts[2]))
3911  return error(ID.Loc, Reason);
3912  ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3913  } else if (Opc == Instruction::ShuffleVector) {
3914  if (Elts.size() != 3)
3915  return error(ID.Loc, "expected three operands to shufflevector");
3916  if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3917  return error(ID.Loc, "invalid operands to shufflevector");
3919  ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3920  ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3921  } else if (Opc == Instruction::ExtractElement) {
3922  if (Elts.size() != 2)
3923  return error(ID.Loc, "expected two operands to extractelement");
3924  if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3925  return error(ID.Loc, "invalid extractelement operands");
3926  ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3927  } else {
3928  assert(Opc == Instruction::InsertElement && "Unknown opcode");
3929  if (Elts.size() != 3)
3930  return error(ID.Loc, "expected three operands to insertelement");
3931  if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3932  return error(ID.Loc, "invalid insertelement operands");
3933  ID.ConstantVal =
3934  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3935  }
3936 
3937  ID.Kind = ValID::t_Constant;
3938  return false;
3939  }
3940  }
3941 
3942  Lex.Lex();
3943  return false;
3944 }
3945 
3946 /// parseGlobalValue - parse a global value with the specified type.
3947 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3948  C = nullptr;
3949  ValID ID;
3950  Value *V = nullptr;
3951  bool Parsed = parseValID(ID) ||
3952  convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3953  if (V && !(C = dyn_cast<Constant>(V)))
3954  return error(ID.Loc, "global values must be constants");
3955  return Parsed;
3956 }
3957 
3958 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3959  Type *Ty = nullptr;
3960  return parseType(Ty) || parseGlobalValue(Ty, V);
3961 }
3962 
3963 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3964  C = nullptr;
3965 
3966  LocTy KwLoc = Lex.getLoc();
3967  if (!EatIfPresent(lltok::kw_comdat))
3968  return false;
3969 
3970  if (EatIfPresent(lltok::lparen)) {
3971  if (Lex.getKind() != lltok::ComdatVar)
3972  return tokError("expected comdat variable");
3973  C = getComdat(Lex.getStrVal(), Lex.getLoc());
3974  Lex.Lex();
3975  if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3976  return true;
3977  } else {
3978  if (GlobalName.empty())
3979  return tokError("comdat cannot be unnamed");
3980  C = getComdat(std::string(GlobalName), KwLoc);
3981  }
3982 
3983  return false;
3984 }
3985 
3986 /// parseGlobalValueVector
3987 /// ::= /*empty*/
3988 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3989 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3990  Optional<unsigned> *InRangeOp) {
3991  // Empty list.
3992  if (Lex.getKind() == lltok::rbrace ||
3993  Lex.getKind() == lltok::rsquare ||
3994  Lex.getKind() == lltok::greater ||
3995  Lex.getKind() == lltok::rparen)
3996  return false;
3997 
3998  do {
3999  if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
4000  *InRangeOp = Elts.size();
4001 
4002  Constant *C;
4003  if (parseGlobalTypeAndValue(C))
4004  return true;
4005  Elts.push_back(C);
4006  } while (EatIfPresent(lltok::comma));
4007 
4008  return false;
4009 }
4010 
4011 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4013  if (parseMDNodeVector(Elts))
4014  return true;
4015 
4016  MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4017  return false;
4018 }
4019 
4020 /// MDNode:
4021 /// ::= !{ ... }
4022 /// ::= !7
4023 /// ::= !DILocation(...)
4024 bool LLParser::parseMDNode(MDNode *&N) {
4025  if (Lex.getKind() == lltok::MetadataVar)
4026  return parseSpecializedMDNode(N);
4027 
4028  return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4029 }
4030 
4031 bool LLParser::parseMDNodeTail(MDNode *&N) {
4032  // !{ ... }
4033  if (Lex.getKind() == lltok::lbrace)
4034  return parseMDTuple(N);
4035 
4036  // !42
4037  return parseMDNodeID(N);
4038 }
4039 
4040 namespace {
4041 
4042 /// Structure to represent an optional metadata field.
4043 template <class FieldTy> struct MDFieldImpl {
4044  typedef MDFieldImpl ImplTy;
4045  FieldTy Val;
4046  bool Seen;
4047 
4048  void assign(FieldTy Val) {
4049  Seen = true;
4050  this->Val = std::move(Val);
4051  }
4052 
4053  explicit MDFieldImpl(FieldTy Default)
4054  : Val(std::move(Default)), Seen(false) {}
4055 };
4056 
4057 /// Structure to represent an optional metadata field that
4058 /// can be of either type (A or B) and encapsulates the
4059 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4060 /// to reimplement the specifics for representing each Field.
4061 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4062  typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4063  FieldTypeA A;
4064  FieldTypeB B;
4065  bool Seen;
4066 
4067  enum {
4068  IsInvalid = 0,
4069  IsTypeA = 1,
4070  IsTypeB = 2
4071  } WhatIs;
4072 
4073  void assign(FieldTypeA A) {
4074  Seen = true;
4075  this->A = std::move(A);
4076  WhatIs = IsTypeA;
4077  }
4078 
4079  void assign(FieldTypeB B) {
4080  Seen = true;
4081  this->B = std::move(B);
4082  WhatIs = IsTypeB;
4083  }
4084 
4085  explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4086  : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4087  WhatIs(IsInvalid) {}
4088 };
4089 
4090 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4091  uint64_t Max;
4092 
4093  MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4094  : ImplTy(Default), Max(Max) {}
4095 };
4096 
4097 struct LineField : public MDUnsignedField {
4098  LineField() : MDUnsignedField(0, UINT32_MAX) {}
4099 };
4100 
4101 struct ColumnField : public MDUnsignedField {
4102  ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4103 };
4104 
4105 struct DwarfTagField : public MDUnsignedField {
4106  DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4107  DwarfTagField(dwarf::Tag DefaultTag)
4108  : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4109 };
4110 
4111 struct DwarfMacinfoTypeField : public MDUnsignedField {
4112  DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4113  DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4114  : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4115 };
4116 
4117 struct DwarfAttEncodingField : public MDUnsignedField {
4118  DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4119 };
4120 
4121 struct DwarfVirtualityField : public MDUnsignedField {
4122  DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4123 };
4124 
4125 struct DwarfLangField : public MDUnsignedField {
4126  DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4127 };
4128 
4129 struct DwarfCCField : public MDUnsignedField {
4130  DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4131 };
4132 
4133 struct EmissionKindField : public MDUnsignedField {
4134  EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4135 };
4136 
4137 struct NameTableKindField : public MDUnsignedField {
4138  NameTableKindField()
4139  : MDUnsignedField(
4140  0, (unsigned)
4141  DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4142 };
4143 
4144 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4145  DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4146 };
4147 
4148 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4149  DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4150 };
4151 
4152 struct MDAPSIntField : public MDFieldImpl<APSInt> {
4153  MDAPSIntField() : ImplTy(APSInt()) {}
4154 };
4155 
4156 struct MDSignedField : public MDFieldImpl<int64_t> {
4157  int64_t Min;
4158  int64_t Max;
4159 
4160  MDSignedField(int64_t Default = 0)
4161  : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
4162  MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4163  : ImplTy(Default), Min(Min), Max(Max) {}
4164 };
4165 
4166 struct MDBoolField : public MDFieldImpl<bool> {
4167  MDBoolField(bool Default = false) : ImplTy(Default) {}
4168 };
4169 
4170 struct MDField : public MDFieldImpl<Metadata *> {
4171  bool AllowNull;
4172 
4173  MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4174 };
4175 
4176 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
4177  MDConstant() : ImplTy(nullptr) {}
4178 };
4179 
4180 struct MDStringField : public MDFieldImpl<MDString *> {
4181  bool AllowEmpty;
4182  MDStringField(bool AllowEmpty = true)
4183  : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4184 };
4185 
4186 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4187  MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4188 };
4189 
4190 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4191  ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4192 };
4193 
4194 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4195  MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4196  : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4197 
4198  MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4199  bool AllowNull = true)
4200  : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4201 
4202  bool isMDSignedField() const { return WhatIs == IsTypeA; }
4203  bool isMDField() const { return WhatIs == IsTypeB; }
4204  int64_t getMDSignedValue() const {
4205  assert(isMDSignedField() && "Wrong field type");
4206  return A.Val;
4207  }
4208  Metadata *getMDFieldValue() const {
4209  assert(isMDField() && "Wrong field type");
4210  return B.Val;
4211  }
4212 };
4213 
4214 struct MDSignedOrUnsignedField
4215  : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
4216  MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
4217 
4218  bool isMDSignedField() const { return WhatIs == IsTypeA; }
4219  bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
4220  int64_t getMDSignedValue() const {
4221  assert(isMDSignedField() && "Wrong field type");
4222  return A.Val;
4223  }
4224  uint64_t getMDUnsignedValue() const {
4225  assert(isMDUnsignedField() && "Wrong field type");
4226  return B.Val;
4227  }
4228 };
4229 
4230 } // end anonymous namespace
4231 
4232 namespace llvm {
4233 
4234 template <>
4235 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4236  if (Lex.getKind() != lltok::APSInt)
4237  return tokError("expected integer");
4238 
4239  Result.assign(Lex.getAPSIntVal());
4240  Lex.Lex();
4241  return false;
4242 }
4243 
4244 template <>
4245 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4246  MDUnsignedField &Result) {
4247  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4248  return tokError("expected unsigned integer");
4249 
4250  auto &U = Lex.getAPSIntVal();
4251  if (U.ugt(Result.Max))
4252  return tokError("value for '" + Name + "' too large, limit is " +
4253  Twine(Result.Max));
4254  Result.assign(U.getZExtValue());
4255  assert(Result.Val <= Result.Max && "Expected value in range");
4256  Lex.Lex();
4257  return false;
4258 }
4259 
4260 template <>
4261 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4262  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4263 }
4264 template <>
4265 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4266  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4267 }
4268 
4269 template <>
4270 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4271  if (Lex.getKind() == lltok::APSInt)
4272  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4273 
4274  if (Lex.getKind() != lltok::DwarfTag)
4275  return tokError("expected DWARF tag");
4276 
4277  unsigned Tag = dwarf::getTag(Lex.getStrVal());
4278  if (Tag == dwarf::DW_TAG_invalid)
4279  return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4280  assert(Tag <= Result.Max && "Expected valid DWARF tag");
4281 
4282  Result.assign(Tag);
4283  Lex.Lex();
4284  return false;
4285 }
4286 
4287 template <>
4288 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4289  DwarfMacinfoTypeField &Result) {
4290  if (Lex.getKind() == lltok::APSInt)
4291  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4292 
4293  if (Lex.getKind() != lltok::DwarfMacinfo)
4294  return tokError("expected DWARF macinfo type");
4295 
4296  unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4297  if (Macinfo == dwarf::DW_MACINFO_invalid)
4298  return tokError("invalid DWARF macinfo type" + Twine(" '") +
4299  Lex.getStrVal() + "'");
4300  assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4301 
4302  Result.assign(Macinfo);
4303  Lex.Lex();
4304  return false;
4305 }
4306 
4307 template <>
4308 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4309  DwarfVirtualityField &Result) {
4310  if (Lex.getKind() == lltok::APSInt)
4311  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4312 
4313  if (Lex.getKind() != lltok::DwarfVirtuality)
4314  return tokError("expected DWARF virtuality code");
4315 
4316  unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4317  if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4318  return tokError("invalid DWARF virtuality code" + Twine(" '") +
4319  Lex.getStrVal() + "'");
4320  assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4321  Result.assign(Virtuality);
4322  Lex.Lex();
4323  return false;
4324 }
4325 
4326 template <>
4327 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4328  if (Lex.getKind() == lltok::APSInt)
4329  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4330 
4331  if (Lex.getKind() != lltok::DwarfLang)
4332  return tokError("expected DWARF language");
4333 
4334  unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4335  if (!Lang)
4336  return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4337  "'");
4338  assert(Lang <= Result.Max && "Expected valid DWARF language");
4339  Result.assign(Lang);
4340  Lex.Lex();
4341  return false;
4342 }
4343 
4344 template <>
4345 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4346  if (Lex.getKind() == lltok::APSInt)
4347  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4348 
4349  if (Lex.getKind() != lltok::DwarfCC)
4350  return tokError("expected DWARF calling convention");
4351 
4352  unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4353  if (!CC)
4354  return tokError("invalid DWARF calling convention" + Twine(" '") +
4355  Lex.getStrVal() + "'");
4356  assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4357  Result.assign(CC);
4358  Lex.Lex();
4359  return false;
4360 }
4361 
4362 template <>
4363 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4364  EmissionKindField &Result) {
4365  if (Lex.getKind() == lltok::APSInt)
4366  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4367 
4368  if (Lex.getKind() != lltok::EmissionKind)
4369  return tokError("expected emission kind");
4370 
4372  if (!Kind)
4373  return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4374  "'");
4375  assert(*Kind <= Result.Max && "Expected valid emission kind");
4376  Result.assign(*Kind);
4377  Lex.Lex();
4378  return false;
4379 }
4380 
4381 template <>
4382 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4383  NameTableKindField &Result) {
4384  if (Lex.getKind() == lltok::APSInt)
4385  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4386 
4387  if (Lex.getKind() != lltok::NameTableKind)
4388  return tokError("expected nameTable kind");
4389 
4391  if (!Kind)
4392  return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4393  "'");
4394  assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4395  Result.assign((unsigned)*Kind);
4396  Lex.Lex();
4397  return false;
4398 }
4399 
4400 template <>
4401 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4402  DwarfAttEncodingField &Result) {
4403  if (Lex.getKind() == lltok::APSInt)
4404  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4405 
4406  if (Lex.getKind() != lltok::DwarfAttEncoding)
4407  return tokError("expected DWARF type attribute encoding");
4408 
4409  unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4410  if (!Encoding)
4411  return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4412  Lex.getStrVal() + "'");
4413  assert(Encoding <= Result.Max && "Expected valid DWARF language");
4414  Result.assign(Encoding);
4415  Lex.Lex();
4416  return false;
4417 }
4418 
4419 /// DIFlagField
4420 /// ::= uint32
4421 /// ::= DIFlagVector
4422 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4423 template <>
4424 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4425 
4426  // parser for a single flag.
4427  auto parseFlag = [&](DINode::DIFlags &Val) {
4428  if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4429  uint32_t TempVal = static_cast<uint32_t>(Val);
4430  bool Res = parseUInt32(TempVal);
4431  Val = static_cast<DINode::DIFlags>(TempVal);
4432  return Res;
4433  }
4434 
4435  if (Lex.getKind() != lltok::DIFlag)
4436  return tokError("expected debug info flag");
4437 
4438  Val = DINode::getFlag(Lex.getStrVal());
4439  if (!Val)
4440  return tokError(Twine("invalid debug info flag flag '") +
4441  Lex.getStrVal() + "'");
4442  Lex.Lex();
4443  return false;
4444  };
4445 
4446  // parse the flags and combine them together.
4447  DINode::DIFlags Combined = DINode::FlagZero;
4448  do {
4449  DINode::DIFlags Val;
4450  if (parseFlag(Val))
4451  return true;
4452  Combined |= Val;
4453  } while (EatIfPresent(lltok::bar));
4454 
4455  Result.assign(Combined);
4456  return false;
4457 }
4458 
4459 /// DISPFlagField
4460 /// ::= uint32
4461 /// ::= DISPFlagVector
4462 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4463 template <>
4464 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4465 
4466  // parser for a single flag.
4467  auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4468  if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4469  uint32_t TempVal = static_cast<uint32_t>(Val);
4470  bool Res = parseUInt32(TempVal);
4471  Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4472  return Res;
4473  }
4474 
4475  if (Lex.getKind() != lltok::DISPFlag)
4476  return tokError("expected debug info flag");
4477 
4478  Val = DISubprogram::getFlag(Lex.getStrVal());
4479  if (!Val)
4480  return tokError(Twine("invalid subprogram debug info flag '") +
4481  Lex.getStrVal() + "'");
4482  Lex.Lex();
4483  return false;
4484  };
4485 
4486  // parse the flags and combine them together.
4487  DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4488  do {
4490  if (parseFlag(Val))
4491  return true;
4492  Combined |= Val;
4493  } while (EatIfPresent(lltok::bar));
4494 
4495  Result.assign(Combined);
4496  return false;
4497 }
4498 
4499 template <>
4500 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4501  if (Lex.getKind() != lltok::APSInt)
4502  return tokError("expected signed integer");
4503 
4504  auto &S = Lex.getAPSIntVal();
4505  if (S < Result.Min)
4506  return tokError("value for '" + Name + "' too small, limit is " +
4507  Twine(Result.Min));
4508  if (S > Result.Max)
4509  return tokError("value for '" + Name + "' too large, limit is " +
4510  Twine(Result.Max));
4511  Result.assign(S.getExtValue());
4512  assert(Result.Val >= Result.Min && "Expected value in range");
4513  assert(Result.Val <= Result.Max && "Expected value in range");
4514  Lex.Lex();
4515  return false;
4516 }
4517 
4518 template <>
4519 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4520  switch (Lex.getKind()) {
4521  default:
4522  return tokError("expected 'true' or 'false'");
4523  case lltok::kw_true:
4524  Result.assign(true);
4525  break;
4526  case lltok::kw_false:
4527  Result.assign(false);
4528  break;
4529  }
4530  Lex.Lex();
4531  return false;
4532 }
4533 
4534 template <>
4535 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4536  if (Lex.getKind() == lltok::kw_null) {
4537  if (!Result.AllowNull)
4538  return tokError("'" + Name + "' cannot be null");
4539  Lex.Lex();
4540  Result.assign(nullptr);
4541  return false;
4542  }
4543 
4544  Metadata *MD;
4545  if (parseMetadata(MD, nullptr))
4546  return true;
4547 
4548  Result.assign(MD);
4549  return false;
4550 }
4551 
4552 template <>
4553 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4554  MDSignedOrMDField &Result) {
4555  // Try to parse a signed int.
4556  if (Lex.getKind() == lltok::APSInt) {
4557  MDSignedField Res = Result.A;
4558  if (!parseMDField(Loc, Name, Res)) {
4559  Result.assign(Res);
4560  return false;
4561  }
4562  return true;
4563  }
4564 
4565  // Otherwise, try to parse as an MDField.
4566  MDField Res = Result.B;
4567  if (!parseMDField(Loc, Name, Res)) {
4568  Result.assign(Res);
4569  return false;
4570  }
4571 
4572  return true;
4573 }
4574 
4575 template <>
4576 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4577  LocTy ValueLoc = Lex.getLoc();
4578  std::string S;
4579  if (parseStringConstant(S))
4580  return true;
4581 
4582  if (!Result.AllowEmpty && S.empty())
4583  return error(ValueLoc, "'" + Name + "' cannot be empty");
4584 
4585  Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4586  return false;
4587 }
4588 
4589 template <>
4590 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4592  if (parseMDNodeVector(MDs))
4593  return true;
4594 
4595  Result.assign(std::move(MDs));
4596  return false;
4597 }
4598 
4599 template <>
4600 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4601  ChecksumKindField &Result) {
4604 
4605  if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4606  return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4607  "'");
4608 
4609  Result.assign(*CSKind);
4610  Lex.Lex();
4611  return false;
4612 }
4613 
4614 } // end namespace llvm
4615 
4616 template <class ParserTy>
4617 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4618  do {
4619  if (Lex.getKind() != lltok::LabelStr)
4620  return tokError("expected field label here");
4621 
4622  if (ParseField())
4623  return true;
4624  } while (EatIfPresent(lltok::comma));
4625 
4626  return false;
4627 }
4628 
4629 template <class ParserTy>
4630 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4631  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4632  Lex.Lex();
4633 
4634  if (parseToken(lltok::lparen, "expected '(' here"))
4635  return true;
4636  if (Lex.getKind() != lltok::rparen)
4637  if (parseMDFieldsImplBody(ParseField))
4638  return true;
4639 
4640  ClosingLoc = Lex.getLoc();
4641  return parseToken(lltok::rparen, "expected ')' here");
4642 }
4643 
4644 template <class FieldTy>
4645 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4646  if (Result.Seen)
4647  return tokError("field '" + Name + "' cannot be specified more than once");
4648 
4649  LocTy Loc = Lex.getLoc();
4650  Lex.Lex();
4651  return parseMDField(Loc, Name, Result);
4652 }
4653 
4654 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4655  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4656 
4657 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4658  if (Lex.getStrVal() == #CLASS) \
4659  return parse##CLASS(N, IsDistinct);
4660 #include "llvm/IR/Metadata.def"
4661 
4662  return tokError("expected metadata type");
4663 }
4664 
4665 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4666 #define NOP_FIELD(NAME, TYPE, INIT)
4667 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4668  if (!NAME.Seen) \
4669  return error(ClosingLoc, "missing required field '" #NAME "'");
4670 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4671  if (Lex.getStrVal() == #NAME) \
4672  return parseMDField(#NAME, NAME);
4673 #define PARSE_MD_FIELDS() \
4674  VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4675  do { \
4676  LocTy ClosingLoc; \
4677  if (parseMDFieldsImpl( \
4678  [&]() -> bool { \
4679  VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4680  return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4681  "'"); \
4682  }, \
4683  ClosingLoc)) \
4684  return true; \
4685  VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4686  } while (false)
4687 #define GET_OR_DISTINCT(CLASS, ARGS) \
4688  (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4689 
4690 /// parseDILocationFields:
4691 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4692 /// isImplicitCode: true)
4693 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4694 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4695  OPTIONAL(line, LineField, ); \
4696  OPTIONAL(column, ColumnField, ); \
4697  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4698  OPTIONAL(inlinedAt, MDField, ); \
4699  OPTIONAL(isImplicitCode, MDBoolField, (false));
4700  PARSE_MD_FIELDS();
4701 #undef VISIT_MD_FIELDS
4702 
4703  Result =
4704  GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4705  inlinedAt.Val, isImplicitCode.Val));
4706  return false;
4707 }
4708 
4709 /// parseGenericDINode:
4710 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4711 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4712 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4713  REQUIRED(tag, DwarfTagField, ); \
4714  OPTIONAL(header, MDStringField, ); \
4715  OPTIONAL(operands, MDFieldList, );
4716  PARSE_MD_FIELDS();
4717 #undef VISIT_MD_FIELDS
4718 
4720  (Context, tag.Val, header.Val, operands.Val));
4721  return false;
4722 }
4723 
4724 /// parseDISubrange:
4725 /// ::= !DISubrange(count: 30, lowerBound: 2)
4726 /// ::= !DISubrange(count: !node, lowerBound: 2)
4727 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4728 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4729 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4730  OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4731  OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4732  OPTIONAL(upperBound, MDSignedOrMDField, ); \
4733  OPTIONAL(stride, MDSignedOrMDField, );
4734  PARSE_MD_FIELDS();
4735 #undef VISIT_MD_FIELDS
4736 
4737  Metadata *Count = nullptr;
4738  Metadata *LowerBound = nullptr;
4739  Metadata *UpperBound = nullptr;
4740  Metadata *Stride = nullptr;
4741 
4742  auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4743  if (Bound.isMDSignedField())
4745  Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4746  if (Bound.isMDField())
4747  return Bound.getMDFieldValue();
4748  return nullptr;
4749  };
4750 
4751  Count = convToMetadata(count);
4752  LowerBound = convToMetadata(lowerBound);
4753  UpperBound = convToMetadata(upperBound);
4754  Stride = convToMetadata(stride);
4755 
4757  (Context, Count, LowerBound, UpperBound, Stride));
4758 
4759  return false;
4760 }
4761 
4762 /// parseDIGenericSubrange:
4763 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4764 /// !node3)
4765 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4766 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4767  OPTIONAL(count, MDSignedOrMDField, ); \
4768  OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4769  OPTIONAL(upperBound, MDSignedOrMDField, ); \
4770  OPTIONAL(stride, MDSignedOrMDField, );
4771  PARSE_MD_FIELDS();
4772 #undef VISIT_MD_FIELDS
4773 
4774  auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4775  if (Bound.isMDSignedField())
4776  return DIExpression::get(
4777  Context, {dwarf::DW_OP_consts,
4778  static_cast<uint64_t>(Bound.getMDSignedValue())});
4779  if (Bound.isMDField())
4780  return Bound.getMDFieldValue();
4781  return nullptr;
4782  };
4783 
4784  Metadata *Count = ConvToMetadata(count);
4785  Metadata *LowerBound = ConvToMetadata(lowerBound);
4786  Metadata *UpperBound = ConvToMetadata(upperBound);
4787  Metadata *Stride = ConvToMetadata(stride);
4788 
4790  (Context, Count, LowerBound, UpperBound, Stride));
4791 
4792  return false;
4793 }
4794 
4795 /// parseDIEnumerator:
4796 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4797 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4798 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4799  REQUIRED(name, MDStringField, ); \
4800  REQUIRED(value, MDAPSIntField, ); \
4801  OPTIONAL(isUnsigned, MDBoolField, (false));
4802  PARSE_MD_FIELDS();
4803 #undef VISIT_MD_FIELDS
4804 
4805  if (isUnsigned.Val && value.Val.isNegative())
4806  return tokError("unsigned enumerator with negative value");
4807 
4808  APSInt Value(value.Val);
4809  // Add a leading zero so that unsigned values with the msb set are not
4810  // mistaken for negative values when used for signed enumerators.
4811  if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4812  Value = Value.zext(Value.getBitWidth() + 1);
4813 
4814  Result =
4815  GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4816 
4817  return false;
4818 }
4819 
4820 /// parseDIBasicType:
4821 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4822 /// encoding: DW_ATE_encoding, flags: 0)
4823 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4824 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4825  OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4826  OPTIONAL(name, MDStringField, ); \
4827  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4828  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4829  OPTIONAL(encoding, DwarfAttEncodingField, ); \
4830  OPTIONAL(flags, DIFlagField, );
4831  PARSE_MD_FIELDS();
4832 #undef VISIT_MD_FIELDS
4833 
4834  Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4835  align.Val, encoding.Val, flags.Val));
4836  return false;
4837 }
4838 
4839 /// parseDIStringType:
4840 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4841 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4842 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4843  OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4844  OPTIONAL(name, MDStringField, ); \
4845  OPTIONAL(stringLength, MDField, ); \
4846  OPTIONAL(stringLengthExpression, MDField, ); \
4847  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4848  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4849  OPTIONAL(encoding, DwarfAttEncodingField, );
4850  PARSE_MD_FIELDS();
4851 #undef VISIT_MD_FIELDS
4852 
4854  (Context, tag.Val, name.Val, stringLength.Val,
4855  stringLengthExpression.Val, size.Val, align.Val,
4856  encoding.Val));
4857  return false;
4858 }
4859 
4860 /// parseDIDerivedType:
4861 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4862 /// line: 7, scope: !1, baseType: !2, size: 32,
4863 /// align: 32, offset: 0, flags: 0, extraData: !3,
4864 /// dwarfAddressSpace: 3)
4865 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4866 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4867  REQUIRED(tag, DwarfTagField, ); \
4868  OPTIONAL(name, MDStringField, ); \
4869  OPTIONAL(file, MDField, ); \
4870  OPTIONAL(line, LineField, ); \
4871  OPTIONAL(scope, MDField, ); \
4872  REQUIRED(baseType, MDField, ); \
4873  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4874  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4875  OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4876  OPTIONAL(flags, DIFlagField, ); \
4877  OPTIONAL(extraData, MDField, ); \
4878  OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4879  PARSE_MD_FIELDS();
4880 #undef VISIT_MD_FIELDS
4881 
4882  Optional<unsigned> DWARFAddressSpace;
4883  if (dwarfAddressSpace.Val != UINT32_MAX)
4884  DWARFAddressSpace = dwarfAddressSpace.Val;
4885 
4887  (Context, tag.Val, name.Val, file.Val, line.Val,
4888  scope.Val, baseType.Val, size.Val, align.Val,
4889  offset.Val, DWARFAddressSpace, flags.Val,
4890  extraData.Val));
4891  return false;
4892 }
4893 
4894 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4895 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4896  REQUIRED(tag, DwarfTagField, ); \
4897  OPTIONAL(name, MDStringField, ); \
4898  OPTIONAL(file, MDField, ); \
4899  OPTIONAL(line, LineField, ); \
4900  OPTIONAL(scope, MDField, ); \
4901  OPTIONAL(baseType, MDField, ); \
4902  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4903  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4904  OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4905  OPTIONAL(flags, DIFlagField, ); \
4906  OPTIONAL(elements, MDField, ); \
4907  OPTIONAL(runtimeLang, DwarfLangField, ); \
4908  OPTIONAL(vtableHolder, MDField, ); \
4909  OPTIONAL(templateParams, MDField, ); \
4910  OPTIONAL(identifier, MDStringField, ); \
4911  OPTIONAL(discriminator, MDField, ); \
4912  OPTIONAL(dataLocation, MDField, ); \
4913  OPTIONAL(associated, MDField, ); \
4914  OPTIONAL(allocated, MDField, ); \
4915  OPTIONAL(rank, MDSignedOrMDField, );
4916  PARSE_MD_FIELDS();
4917 #undef VISIT_MD_FIELDS
4918 
4919  Metadata *Rank = nullptr;
4920  if (rank.isMDSignedField())
4922  Type::getInt64Ty(Context), rank.getMDSignedValue()));
4923  else if (rank.isMDField())
4924  Rank = rank.getMDFieldValue();
4925 
4926  // If this has an identifier try to build an ODR type.
4927  if (identifier.Val)
4928  if (auto *CT = DICompositeType::buildODRType(
4929  Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4930  scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4931  elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4932  discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4933  Rank)) {
4934  Result = CT;
4935  return false;
4936  }
4937 
4938  // Create a new node, and save it in the context if it belongs in the type
4939  // map.
4942  (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4943  size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4944  runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4945  discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4946  Rank));
4947  return false;
4948 }
4949 
4950 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4951 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4952  OPTIONAL(flags, DIFlagField, ); \
4953  OPTIONAL(cc, DwarfCCField, ); \
4954  REQUIRED(types, MDField, );
4955  PARSE_MD_FIELDS();
4956 #undef VISIT_MD_FIELDS
4957 
4959  (Context, flags.Val, cc.Val, types.Val));
4960  return false;
4961 }
4962 
4963 /// parseDIFileType:
4964 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4965 /// checksumkind: CSK_MD5,
4966 /// checksum: "000102030405060708090a0b0c0d0e0f",
4967 /// source: "source file contents")
4968 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4969  // The default constructed value for checksumkind is required, but will never
4970  // be used, as the parser checks if the field was actually Seen before using
4971  // the Val.
4972 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4973  REQUIRED(filename, MDStringField, ); \
4974  REQUIRED(directory, MDStringField, ); \
4975  OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4976  OPTIONAL(checksum, MDStringField, ); \
4977  OPTIONAL(source, MDStringField, );
4978  PARSE_MD_FIELDS();
4979 #undef VISIT_MD_FIELDS
4980 
4982  if (checksumkind.Seen && checksum.Seen)
4983  OptChecksum.emplace(checksumkind.Val, checksum.Val);
4984  else if (checksumkind.Seen || checksum.Seen)
4985  return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4986 
4987  Optional<MDString *> OptSource;
4988  if (source.Seen)
4989  OptSource = source.Val;
4990  Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4991  OptChecksum, OptSource));
4992  return false;
4993 }
4994 
4995 /// parseDICompileUnit:
4996 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4997 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4998 /// splitDebugFilename: "abc.debug",
4999 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5000 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5001 /// sysroot: "/", sdk: "MacOSX.sdk")
5002 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5003  if (!IsDistinct)
5004  return Lex.Error("missing 'distinct', required for !DICompileUnit");
5005 
5006 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5007  REQUIRED(language, DwarfLangField, ); \
5008  REQUIRED(file, MDField, (/* AllowNull */ false)); \
5009  OPTIONAL(producer, MDStringField, ); \
5010  OPTIONAL(isOptimized, MDBoolField, ); \
5011  OPTIONAL(flags, MDStringField, ); \
5012  OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5013  OPTIONAL(splitDebugFilename, MDStringField, ); \
5014  OPTIONAL(emissionKind, EmissionKindField, ); \
5015  OPTIONAL(enums, MDField, ); \
5016  OPTIONAL(retainedTypes, MDField, ); \
5017  OPTIONAL(globals, MDField, ); \
5018  OPTIONAL(imports, MDField, ); \
5019  OPTIONAL(macros, MDField, ); \
5020  OPTIONAL(dwoId, MDUnsignedField, ); \
5021  OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5022  OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5023  OPTIONAL(nameTableKind, NameTableKindField, ); \
5024  OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5025  OPTIONAL(sysroot, MDStringField, ); \
5026  OPTIONAL(sdk, MDStringField, );
5027  PARSE_MD_FIELDS();
5028 #undef VISIT_MD_FIELDS
5029 
5031  Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5032  runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5033  retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5034  splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5035  rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5036  return false;
5037 }
5038 
5039 /// parseDISubprogram:
5040 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5041 /// file: !1, line: 7, type: !2, isLocal: false,
5042 /// isDefinition: true, scopeLine: 8, containingType: !3,
5043 /// virtuality: DW_VIRTUALTIY_pure_virtual,
5044 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5045 /// spFlags: 10, isOptimized: false, templateParams: !4,
5046 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
5047 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5048  auto Loc = Lex.getLoc();
5049 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5050  OPTIONAL(scope, MDField, ); \
5051  OPTIONAL(name, MDStringField, ); \
5052  OPTIONAL(linkageName, MDStringField, ); \
5053  OPTIONAL(file, MDField, ); \
5054  OPTIONAL(line, LineField, ); \
5055  OPTIONAL(type, MDField, ); \
5056  OPTIONAL(isLocal, MDBoolField, ); \
5057  OPTIONAL(isDefinition, MDBoolField, (true)); \
5058  OPTIONAL(scopeLine, LineField, ); \
5059  OPTIONAL(containingType, MDField, ); \
5060  OPTIONAL(virtuality, DwarfVirtualityField, ); \
5061  OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5062  OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5063  OPTIONAL(flags, DIFlagField, ); \
5064  OPTIONAL(spFlags, DISPFlagField, ); \
5065  OPTIONAL(isOptimized, MDBoolField, ); \
5066  OPTIONAL(unit, MDField, ); \
5067  OPTIONAL(templateParams, MDField, ); \
5068  OPTIONAL(declaration, MDField, ); \
5069  OPTIONAL(retainedNodes, MDField, ); \
5070  OPTIONAL(thrownTypes, MDField, );
5071  PARSE_MD_FIELDS();
5072 #undef VISIT_MD_FIELDS
5073 
5074  // An explicit spFlags field takes precedence over individual fields in
5075  // older IR versions.
5076  DISubprogram::DISPFlags SPFlags =
5077  spFlags.Seen ? spFlags.Val
5078  : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5079  isOptimized.Val, virtuality.Val);
5080  if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5081  return Lex.Error(
5082  Loc,
5083  "missing 'distinct', required for !DISubprogram that is a Definition");
5085  DISubprogram,
5086  (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5087  type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5088  thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5089  declaration.Val, retainedNodes.Val, thrownTypes.Val));
5090  return false;
5091 }
5092 
5093 /// parseDILexicalBlock:
5094 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5095 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5096 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5097  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5098  OPTIONAL(file, MDField, ); \
5099  OPTIONAL(line, LineField, ); \
5100  OPTIONAL(column, ColumnField, );
5101  PARSE_MD_FIELDS();
5102 #undef VISIT_MD_FIELDS
5103 
5105  DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5106  return false;
5107 }
5108 
5109 /// parseDILexicalBlockFile:
5110 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5111 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5112 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5113  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5114  OPTIONAL(file, MDField, ); \
5115  REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5116  PARSE_MD_FIELDS();
5117 #undef VISIT_MD_FIELDS
5118 
5120  (Context, scope.Val, file.Val, discriminator.Val));
5121  return false;
5122 }
5123 
5124 /// parseDICommonBlock:
5125 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5126 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5127 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5128  REQUIRED(scope, MDField, ); \
5129  OPTIONAL(declaration, MDField, ); \
5130  OPTIONAL(name, MDStringField, ); \
5131  OPTIONAL(file, MDField, ); \
5132  OPTIONAL(line, LineField, );
5133  PARSE_MD_FIELDS();
5134 #undef VISIT_MD_FIELDS
5135 
5137  (Context, scope.Val, declaration.Val, name.Val,
5138  file.Val, line.Val));
5139  return false;
5140 }
5141 
5142 /// parseDINamespace:
5143 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5144 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5145 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5146  REQUIRED(scope, MDField, ); \
5147  OPTIONAL(name, MDStringField, ); \
5148  OPTIONAL(exportSymbols, MDBoolField, );
5149  PARSE_MD_FIELDS();
5150 #undef VISIT_MD_FIELDS
5151 
5153  (Context, scope.Val, name.Val, exportSymbols.Val));
5154  return false;
5155 }
5156 
5157 /// parseDIMacro:
5158 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5159 /// "SomeValue")
5160 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5161 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5162  REQUIRED(type, DwarfMacinfoTypeField, ); \
5163  OPTIONAL(line, LineField, ); \
5164  REQUIRED(name, MDStringField, ); \
5165  OPTIONAL(value, MDStringField, );
5166  PARSE_MD_FIELDS();
5167 #undef VISIT_MD_FIELDS
5168 
5170  (Context, type.Val, line.Val, name.Val, value.Val));
5171  return false;
5172 }
5173 
5174 /// parseDIMacroFile:
5175 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5176 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5177 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5178  OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5179  OPTIONAL(line, LineField, ); \
5180  REQUIRED(file, MDField, ); \
5181  OPTIONAL(nodes, MDField, );
5182  PARSE_MD_FIELDS();
5183 #undef VISIT_MD_FIELDS
5184 
5186  (Context, type.Val, line.Val, file.Val, nodes.Val));
5187  return false;
5188 }
5189 
5190 /// parseDIModule:
5191 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5192 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5193 /// file: !1, line: 4, isDecl: false)
5194 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5195 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5196  REQUIRED(scope, MDField, ); \
5197  REQUIRED(name, MDStringField, ); \
5198  OPTIONAL(configMacros, MDStringField, ); \
5199  OPTIONAL(includePath, MDStringField, ); \
5200  OPTIONAL(apinotes, MDStringField, ); \
5201  OPTIONAL(file, MDField, ); \
5202  OPTIONAL(line, LineField, ); \
5203  OPTIONAL(isDecl, MDBoolField, );
5204  PARSE_MD_FIELDS();
5205 #undef VISIT_MD_FIELDS
5206 
5207  Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5208  configMacros.Val, includePath.Val,
5209  apinotes.Val, line.Val, isDecl.Val));
5210  return false;
5211 }
5212 
5213 /// parseDITemplateTypeParameter:
5214 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5215