1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LLParser.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.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/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/Dwarf.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstring>
52 #include <iterator>
53 #include <vector>
54 
55 using namespace llvm;
56 
57 static std::string getTypeString(Type *T) {
58   std::string Result;
59   raw_string_ostream Tmp(Result);
60   Tmp << *T;
61   return Tmp.str();
62 }
63 
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run() {
66   // Prime the lexer.
67   Lex.Lex();
68 
69   if (Context.shouldDiscardValueNames())
70     return Error(
71         Lex.getLoc(),
72         "Can't read textual IR with a Context that discards named Values");
73 
74   return ParseTopLevelEntities() ||
75          ValidateEndOfModule();
76 }
77 
78 bool LLParser::parseStandaloneConstantValue(Constant *&C,
79                                             const SlotMapping *Slots) {
80   restoreParsingState(Slots);
81   Lex.Lex();
82 
83   Type *Ty = nullptr;
84   if (ParseType(Ty) || parseConstantValue(Ty, C))
85     return true;
86   if (Lex.getKind() != lltok::Eof)
87     return Error(Lex.getLoc(), "expected end of string");
88   return false;
89 }
90 
91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92                                     const SlotMapping *Slots) {
93   restoreParsingState(Slots);
94   Lex.Lex();
95 
96   Read = 0;
97   SMLoc Start = Lex.getLoc();
98   Ty = nullptr;
99   if (ParseType(Ty))
100     return true;
101   SMLoc End = Lex.getLoc();
102   Read = End.getPointer() - Start.getPointer();
103 
104   return false;
105 }
106 
107 void LLParser::restoreParsingState(const SlotMapping *Slots) {
108   if (!Slots)
109     return;
110   NumberedVals = Slots->GlobalValues;
111   NumberedMetadata = Slots->MetadataNodes;
112   for (const auto &I : Slots->NamedTypes)
113     NamedTypes.insert(
114         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115   for (const auto &I : Slots->Types)
116     NumberedTypes.insert(
117         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118 }
119 
120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121 /// module.
122 bool LLParser::ValidateEndOfModule() {
123   // Handle any function attribute group forward references.
124   for (const auto &RAG : ForwardRefAttrGroups) {
125     Value *V = RAG.first;
126     const std::vector<unsigned> &Attrs = RAG.second;
127     AttrBuilder B;
128 
129     for (const auto &Attr : Attrs)
130       B.merge(NumberedAttrBuilders[Attr]);
131 
132     if (Function *Fn = dyn_cast<Function>(V)) {
133       AttributeList AS = Fn->getAttributes();
134       AttrBuilder FnAttrs(AS.getFnAttributes());
135       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
136 
137       FnAttrs.merge(B);
138 
139       // If the alignment was parsed as an attribute, move to the alignment
140       // field.
141       if (FnAttrs.hasAlignmentAttr()) {
142         Fn->setAlignment(FnAttrs.getAlignment());
143         FnAttrs.removeAttribute(Attribute::Alignment);
144       }
145 
146       AS = AS.addAttributes(
147           Context, AttributeList::FunctionIndex,
148           AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
149       Fn->setAttributes(AS);
150     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
151       AttributeList AS = CI->getAttributes();
152       AttrBuilder FnAttrs(AS.getFnAttributes());
153       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
154       FnAttrs.merge(B);
155       AS = AS.addAttributes(
156           Context, AttributeList::FunctionIndex,
157           AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
158       CI->setAttributes(AS);
159     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
160       AttributeList AS = II->getAttributes();
161       AttrBuilder FnAttrs(AS.getFnAttributes());
162       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
163       FnAttrs.merge(B);
164       AS = AS.addAttributes(
165           Context, AttributeList::FunctionIndex,
166           AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
167       II->setAttributes(AS);
168     } else {
169       llvm_unreachable("invalid object with forward attribute group reference");
170     }
171   }
172 
173   // If there are entries in ForwardRefBlockAddresses at this point, the
174   // function was never defined.
175   if (!ForwardRefBlockAddresses.empty())
176     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
177                  "expected function name in blockaddress");
178 
179   for (const auto &NT : NumberedTypes)
180     if (NT.second.second.isValid())
181       return Error(NT.second.second,
182                    "use of undefined type '%" + Twine(NT.first) + "'");
183 
184   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
185        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
186     if (I->second.second.isValid())
187       return Error(I->second.second,
188                    "use of undefined type named '" + I->getKey() + "'");
189 
190   if (!ForwardRefComdats.empty())
191     return Error(ForwardRefComdats.begin()->second,
192                  "use of undefined comdat '$" +
193                      ForwardRefComdats.begin()->first + "'");
194 
195   if (!ForwardRefVals.empty())
196     return Error(ForwardRefVals.begin()->second.second,
197                  "use of undefined value '@" + ForwardRefVals.begin()->first +
198                  "'");
199 
200   if (!ForwardRefValIDs.empty())
201     return Error(ForwardRefValIDs.begin()->second.second,
202                  "use of undefined value '@" +
203                  Twine(ForwardRefValIDs.begin()->first) + "'");
204 
205   if (!ForwardRefMDNodes.empty())
206     return Error(ForwardRefMDNodes.begin()->second.second,
207                  "use of undefined metadata '!" +
208                  Twine(ForwardRefMDNodes.begin()->first) + "'");
209 
210   // Resolve metadata cycles.
211   for (auto &N : NumberedMetadata) {
212     if (N.second && !N.second->isResolved())
213       N.second->resolveCycles();
214   }
215 
216   for (auto *Inst : InstsWithTBAATag) {
217     MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
218     assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
219     auto *UpgradedMD = UpgradeTBAANode(*MD);
220     if (MD != UpgradedMD)
221       Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
222   }
223 
224   // Look for intrinsic functions and CallInst that need to be upgraded
225   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
226     UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
227 
228   // Some types could be renamed during loading if several modules are
229   // loaded in the same LLVMContext (LTO scenario). In this case we should
230   // remangle intrinsics names as well.
231   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
232     Function *F = &*FI++;
233     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
234       F->replaceAllUsesWith(Remangled.getValue());
235       F->eraseFromParent();
236     }
237   }
238 
239   UpgradeDebugInfo(*M);
240 
241   UpgradeModuleFlags(*M);
242 
243   if (!Slots)
244     return false;
245   // Initialize the slot mapping.
246   // Because by this point we've parsed and validated everything, we can "steal"
247   // the mapping from LLParser as it doesn't need it anymore.
248   Slots->GlobalValues = std::move(NumberedVals);
249   Slots->MetadataNodes = std::move(NumberedMetadata);
250   for (const auto &I : NamedTypes)
251     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
252   for (const auto &I : NumberedTypes)
253     Slots->Types.insert(std::make_pair(I.first, I.second.first));
254 
255   return false;
256 }
257 
258 //===----------------------------------------------------------------------===//
259 // Top-Level Entities
260 //===----------------------------------------------------------------------===//
261 
262 bool LLParser::ParseTopLevelEntities() {
263   while (true) {
264     switch (Lex.getKind()) {
265     default:         return TokError("expected top-level entity");
266     case lltok::Eof: return false;
267     case lltok::kw_declare: if (ParseDeclare()) return true; break;
268     case lltok::kw_define:  if (ParseDefine()) return true; break;
269     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
270     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
271     case lltok::kw_source_filename:
272       if (ParseSourceFileName())
273         return true;
274       break;
275     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
276     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
277     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
278     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
279     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
280     case lltok::ComdatVar:  if (parseComdat()) return true; break;
281     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
282     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
283     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
284     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
285     case lltok::kw_uselistorder_bb:
286       if (ParseUseListOrderBB())
287         return true;
288       break;
289     }
290   }
291 }
292 
293 /// toplevelentity
294 ///   ::= 'module' 'asm' STRINGCONSTANT
295 bool LLParser::ParseModuleAsm() {
296   assert(Lex.getKind() == lltok::kw_module);
297   Lex.Lex();
298 
299   std::string AsmStr;
300   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
301       ParseStringConstant(AsmStr)) return true;
302 
303   M->appendModuleInlineAsm(AsmStr);
304   return false;
305 }
306 
307 /// toplevelentity
308 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
309 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
310 bool LLParser::ParseTargetDefinition() {
311   assert(Lex.getKind() == lltok::kw_target);
312   std::string Str;
313   switch (Lex.Lex()) {
314   default: return TokError("unknown target property");
315   case lltok::kw_triple:
316     Lex.Lex();
317     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
318         ParseStringConstant(Str))
319       return true;
320     M->setTargetTriple(Str);
321     return false;
322   case lltok::kw_datalayout:
323     Lex.Lex();
324     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
325         ParseStringConstant(Str))
326       return true;
327     M->setDataLayout(Str);
328     return false;
329   }
330 }
331 
332 /// toplevelentity
333 ///   ::= 'source_filename' '=' STRINGCONSTANT
334 bool LLParser::ParseSourceFileName() {
335   assert(Lex.getKind() == lltok::kw_source_filename);
336   std::string Str;
337   Lex.Lex();
338   if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
339       ParseStringConstant(Str))
340     return true;
341   M->setSourceFileName(Str);
342   return false;
343 }
344 
345 /// toplevelentity
346 ///   ::= 'deplibs' '=' '[' ']'
347 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
348 /// FIXME: Remove in 4.0. Currently parse, but ignore.
349 bool LLParser::ParseDepLibs() {
350   assert(Lex.getKind() == lltok::kw_deplibs);
351   Lex.Lex();
352   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
353       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
354     return true;
355 
356   if (EatIfPresent(lltok::rsquare))
357     return false;
358 
359   do {
360     std::string Str;
361     if (ParseStringConstant(Str)) return true;
362   } while (EatIfPresent(lltok::comma));
363 
364   return ParseToken(lltok::rsquare, "expected ']' at end of list");
365 }
366 
367 /// ParseUnnamedType:
368 ///   ::= LocalVarID '=' 'type' type
369 bool LLParser::ParseUnnamedType() {
370   LocTy TypeLoc = Lex.getLoc();
371   unsigned TypeID = Lex.getUIntVal();
372   Lex.Lex(); // eat LocalVarID;
373 
374   if (ParseToken(lltok::equal, "expected '=' after name") ||
375       ParseToken(lltok::kw_type, "expected 'type' after '='"))
376     return true;
377 
378   Type *Result = nullptr;
379   if (ParseStructDefinition(TypeLoc, "",
380                             NumberedTypes[TypeID], Result)) return true;
381 
382   if (!isa<StructType>(Result)) {
383     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
384     if (Entry.first)
385       return Error(TypeLoc, "non-struct types may not be recursive");
386     Entry.first = Result;
387     Entry.second = SMLoc();
388   }
389 
390   return false;
391 }
392 
393 /// toplevelentity
394 ///   ::= LocalVar '=' 'type' type
395 bool LLParser::ParseNamedType() {
396   std::string Name = Lex.getStrVal();
397   LocTy NameLoc = Lex.getLoc();
398   Lex.Lex();  // eat LocalVar.
399 
400   if (ParseToken(lltok::equal, "expected '=' after name") ||
401       ParseToken(lltok::kw_type, "expected 'type' after name"))
402     return true;
403 
404   Type *Result = nullptr;
405   if (ParseStructDefinition(NameLoc, Name,
406                             NamedTypes[Name], Result)) return true;
407 
408   if (!isa<StructType>(Result)) {
409     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
410     if (Entry.first)
411       return Error(NameLoc, "non-struct types may not be recursive");
412     Entry.first = Result;
413     Entry.second = SMLoc();
414   }
415 
416   return false;
417 }
418 
419 /// toplevelentity
420 ///   ::= 'declare' FunctionHeader
421 bool LLParser::ParseDeclare() {
422   assert(Lex.getKind() == lltok::kw_declare);
423   Lex.Lex();
424 
425   std::vector<std::pair<unsigned, MDNode *>> MDs;
426   while (Lex.getKind() == lltok::MetadataVar) {
427     unsigned MDK;
428     MDNode *N;
429     if (ParseMetadataAttachment(MDK, N))
430       return true;
431     MDs.push_back({MDK, N});
432   }
433 
434   Function *F;
435   if (ParseFunctionHeader(F, false))
436     return true;
437   for (auto &MD : MDs)
438     F->addMetadata(MD.first, *MD.second);
439   return false;
440 }
441 
442 /// toplevelentity
443 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
444 bool LLParser::ParseDefine() {
445   assert(Lex.getKind() == lltok::kw_define);
446   Lex.Lex();
447 
448   Function *F;
449   return ParseFunctionHeader(F, true) ||
450          ParseOptionalFunctionMetadata(*F) ||
451          ParseFunctionBody(*F);
452 }
453 
454 /// ParseGlobalType
455 ///   ::= 'constant'
456 ///   ::= 'global'
457 bool LLParser::ParseGlobalType(bool &IsConstant) {
458   if (Lex.getKind() == lltok::kw_constant)
459     IsConstant = true;
460   else if (Lex.getKind() == lltok::kw_global)
461     IsConstant = false;
462   else {
463     IsConstant = false;
464     return TokError("expected 'global' or 'constant'");
465   }
466   Lex.Lex();
467   return false;
468 }
469 
470 bool LLParser::ParseOptionalUnnamedAddr(
471     GlobalVariable::UnnamedAddr &UnnamedAddr) {
472   if (EatIfPresent(lltok::kw_unnamed_addr))
473     UnnamedAddr = GlobalValue::UnnamedAddr::Global;
474   else if (EatIfPresent(lltok::kw_local_unnamed_addr))
475     UnnamedAddr = GlobalValue::UnnamedAddr::Local;
476   else
477     UnnamedAddr = GlobalValue::UnnamedAddr::None;
478   return false;
479 }
480 
481 /// ParseUnnamedGlobal:
482 ///   OptionalVisibility (ALIAS | IFUNC) ...
483 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
484 ///                                                     ...   -> global variable
485 ///   GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
486 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
487 ///                                                     ...   -> global variable
488 bool LLParser::ParseUnnamedGlobal() {
489   unsigned VarID = NumberedVals.size();
490   std::string Name;
491   LocTy NameLoc = Lex.getLoc();
492 
493   // Handle the GlobalID form.
494   if (Lex.getKind() == lltok::GlobalID) {
495     if (Lex.getUIntVal() != VarID)
496       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
497                    Twine(VarID) + "'");
498     Lex.Lex(); // eat GlobalID;
499 
500     if (ParseToken(lltok::equal, "expected '=' after name"))
501       return true;
502   }
503 
504   bool HasLinkage;
505   unsigned Linkage, Visibility, DLLStorageClass;
506   GlobalVariable::ThreadLocalMode TLM;
507   GlobalVariable::UnnamedAddr UnnamedAddr;
508   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
509       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
510     return true;
511 
512   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
513     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
514                        DLLStorageClass, TLM, UnnamedAddr);
515 
516   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
517                              DLLStorageClass, TLM, UnnamedAddr);
518 }
519 
520 /// ParseNamedGlobal:
521 ///   GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
522 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
523 ///                                                     ...   -> global variable
524 bool LLParser::ParseNamedGlobal() {
525   assert(Lex.getKind() == lltok::GlobalVar);
526   LocTy NameLoc = Lex.getLoc();
527   std::string Name = Lex.getStrVal();
528   Lex.Lex();
529 
530   bool HasLinkage;
531   unsigned Linkage, Visibility, DLLStorageClass;
532   GlobalVariable::ThreadLocalMode TLM;
533   GlobalVariable::UnnamedAddr UnnamedAddr;
534   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
535       ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
536       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
537     return true;
538 
539   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
540     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
541                        DLLStorageClass, TLM, UnnamedAddr);
542 
543   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
544                              DLLStorageClass, TLM, UnnamedAddr);
545 }
546 
547 bool LLParser::parseComdat() {
548   assert(Lex.getKind() == lltok::ComdatVar);
549   std::string Name = Lex.getStrVal();
550   LocTy NameLoc = Lex.getLoc();
551   Lex.Lex();
552 
553   if (ParseToken(lltok::equal, "expected '=' here"))
554     return true;
555 
556   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
557     return TokError("expected comdat type");
558 
559   Comdat::SelectionKind SK;
560   switch (Lex.getKind()) {
561   default:
562     return TokError("unknown selection kind");
563   case lltok::kw_any:
564     SK = Comdat::Any;
565     break;
566   case lltok::kw_exactmatch:
567     SK = Comdat::ExactMatch;
568     break;
569   case lltok::kw_largest:
570     SK = Comdat::Largest;
571     break;
572   case lltok::kw_noduplicates:
573     SK = Comdat::NoDuplicates;
574     break;
575   case lltok::kw_samesize:
576     SK = Comdat::SameSize;
577     break;
578   }
579   Lex.Lex();
580 
581   // See if the comdat was forward referenced, if so, use the comdat.
582   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
583   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
584   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
585     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
586 
587   Comdat *C;
588   if (I != ComdatSymTab.end())
589     C = &I->second;
590   else
591     C = M->getOrInsertComdat(Name);
592   C->setSelectionKind(SK);
593 
594   return false;
595 }
596 
597 // MDString:
598 //   ::= '!' STRINGCONSTANT
599 bool LLParser::ParseMDString(MDString *&Result) {
600   std::string Str;
601   if (ParseStringConstant(Str)) return true;
602   Result = MDString::get(Context, Str);
603   return false;
604 }
605 
606 // MDNode:
607 //   ::= '!' MDNodeNumber
608 bool LLParser::ParseMDNodeID(MDNode *&Result) {
609   // !{ ..., !42, ... }
610   LocTy IDLoc = Lex.getLoc();
611   unsigned MID = 0;
612   if (ParseUInt32(MID))
613     return true;
614 
615   // If not a forward reference, just return it now.
616   if (NumberedMetadata.count(MID)) {
617     Result = NumberedMetadata[MID];
618     return false;
619   }
620 
621   // Otherwise, create MDNode forward reference.
622   auto &FwdRef = ForwardRefMDNodes[MID];
623   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
624 
625   Result = FwdRef.first.get();
626   NumberedMetadata[MID].reset(Result);
627   return false;
628 }
629 
630 /// ParseNamedMetadata:
631 ///   !foo = !{ !1, !2 }
632 bool LLParser::ParseNamedMetadata() {
633   assert(Lex.getKind() == lltok::MetadataVar);
634   std::string Name = Lex.getStrVal();
635   Lex.Lex();
636 
637   if (ParseToken(lltok::equal, "expected '=' here") ||
638       ParseToken(lltok::exclaim, "Expected '!' here") ||
639       ParseToken(lltok::lbrace, "Expected '{' here"))
640     return true;
641 
642   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
643   if (Lex.getKind() != lltok::rbrace)
644     do {
645       if (ParseToken(lltok::exclaim, "Expected '!' here"))
646         return true;
647 
648       MDNode *N = nullptr;
649       if (ParseMDNodeID(N)) return true;
650       NMD->addOperand(N);
651     } while (EatIfPresent(lltok::comma));
652 
653   return ParseToken(lltok::rbrace, "expected end of metadata node");
654 }
655 
656 /// ParseStandaloneMetadata:
657 ///   !42 = !{...}
658 bool LLParser::ParseStandaloneMetadata() {
659   assert(Lex.getKind() == lltok::exclaim);
660   Lex.Lex();
661   unsigned MetadataID = 0;
662 
663   MDNode *Init;
664   if (ParseUInt32(MetadataID) ||
665       ParseToken(lltok::equal, "expected '=' here"))
666     return true;
667 
668   // Detect common error, from old metadata syntax.
669   if (Lex.getKind() == lltok::Type)
670     return TokError("unexpected type in metadata definition");
671 
672   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
673   if (Lex.getKind() == lltok::MetadataVar) {
674     if (ParseSpecializedMDNode(Init, IsDistinct))
675       return true;
676   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
677              ParseMDTuple(Init, IsDistinct))
678     return true;
679 
680   // See if this was forward referenced, if so, handle it.
681   auto FI = ForwardRefMDNodes.find(MetadataID);
682   if (FI != ForwardRefMDNodes.end()) {
683     FI->second.first->replaceAllUsesWith(Init);
684     ForwardRefMDNodes.erase(FI);
685 
686     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
687   } else {
688     if (NumberedMetadata.count(MetadataID))
689       return TokError("Metadata id is already used");
690     NumberedMetadata[MetadataID].reset(Init);
691   }
692 
693   return false;
694 }
695 
696 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
697   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
698          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
699 }
700 
701 /// parseIndirectSymbol:
702 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
703 ///                     OptionalDLLStorageClass OptionalThreadLocal
704 ///                     OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
705 ///
706 /// IndirectSymbol
707 ///   ::= TypeAndValue
708 ///
709 /// Everything through OptionalUnnamedAddr has already been parsed.
710 ///
711 bool LLParser::parseIndirectSymbol(
712     const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
713     unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
714     GlobalVariable::UnnamedAddr UnnamedAddr) {
715   bool IsAlias;
716   if (Lex.getKind() == lltok::kw_alias)
717     IsAlias = true;
718   else if (Lex.getKind() == lltok::kw_ifunc)
719     IsAlias = false;
720   else
721     llvm_unreachable("Not an alias or ifunc!");
722   Lex.Lex();
723 
724   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
725 
726   if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
727     return Error(NameLoc, "invalid linkage type for alias");
728 
729   if (!isValidVisibilityForLinkage(Visibility, L))
730     return Error(NameLoc,
731                  "symbol with local linkage must have default visibility");
732 
733   Type *Ty;
734   LocTy ExplicitTypeLoc = Lex.getLoc();
735   if (ParseType(Ty) ||
736       ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
737     return true;
738 
739   Constant *Aliasee;
740   LocTy AliaseeLoc = Lex.getLoc();
741   if (Lex.getKind() != lltok::kw_bitcast &&
742       Lex.getKind() != lltok::kw_getelementptr &&
743       Lex.getKind() != lltok::kw_addrspacecast &&
744       Lex.getKind() != lltok::kw_inttoptr) {
745     if (ParseGlobalTypeAndValue(Aliasee))
746       return true;
747   } else {
748     // The bitcast dest type is not present, it is implied by the dest type.
749     ValID ID;
750     if (ParseValID(ID))
751       return true;
752     if (ID.Kind != ValID::t_Constant)
753       return Error(AliaseeLoc, "invalid aliasee");
754     Aliasee = ID.ConstantVal;
755   }
756 
757   Type *AliaseeType = Aliasee->getType();
758   auto *PTy = dyn_cast<PointerType>(AliaseeType);
759   if (!PTy)
760     return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
761   unsigned AddrSpace = PTy->getAddressSpace();
762 
763   if (IsAlias && Ty != PTy->getElementType())
764     return Error(
765         ExplicitTypeLoc,
766         "explicit pointee type doesn't match operand's pointee type");
767 
768   if (!IsAlias && !PTy->getElementType()->isFunctionTy())
769     return Error(
770         ExplicitTypeLoc,
771         "explicit pointee type should be a function type");
772 
773   GlobalValue *GVal = nullptr;
774 
775   // See if the alias was forward referenced, if so, prepare to replace the
776   // forward reference.
777   if (!Name.empty()) {
778     GVal = M->getNamedValue(Name);
779     if (GVal) {
780       if (!ForwardRefVals.erase(Name))
781         return Error(NameLoc, "redefinition of global '@" + Name + "'");
782     }
783   } else {
784     auto I = ForwardRefValIDs.find(NumberedVals.size());
785     if (I != ForwardRefValIDs.end()) {
786       GVal = I->second.first;
787       ForwardRefValIDs.erase(I);
788     }
789   }
790 
791   // Okay, create the alias but do not insert it into the module yet.
792   std::unique_ptr<GlobalIndirectSymbol> GA;
793   if (IsAlias)
794     GA.reset(GlobalAlias::create(Ty, AddrSpace,
795                                  (GlobalValue::LinkageTypes)Linkage, Name,
796                                  Aliasee, /*Parent*/ nullptr));
797   else
798     GA.reset(GlobalIFunc::create(Ty, AddrSpace,
799                                  (GlobalValue::LinkageTypes)Linkage, Name,
800                                  Aliasee, /*Parent*/ nullptr));
801   GA->setThreadLocalMode(TLM);
802   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
803   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
804   GA->setUnnamedAddr(UnnamedAddr);
805 
806   if (Name.empty())
807     NumberedVals.push_back(GA.get());
808 
809   if (GVal) {
810     // Verify that types agree.
811     if (GVal->getType() != GA->getType())
812       return Error(
813           ExplicitTypeLoc,
814           "forward reference and definition of alias have different types");
815 
816     // If they agree, just RAUW the old value with the alias and remove the
817     // forward ref info.
818     GVal->replaceAllUsesWith(GA.get());
819     GVal->eraseFromParent();
820   }
821 
822   // Insert into the module, we know its name won't collide now.
823   if (IsAlias)
824     M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
825   else
826     M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
827   assert(GA->getName() == Name && "Should not be a name conflict!");
828 
829   // The module owns this now
830   GA.release();
831 
832   return false;
833 }
834 
835 /// ParseGlobal
836 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
837 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
838 ///       OptionalExternallyInitialized GlobalType Type Const
839 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
840 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
841 ///       OptionalExternallyInitialized GlobalType Type Const
842 ///
843 /// Everything up to and including OptionalUnnamedAddr has been parsed
844 /// already.
845 ///
846 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
847                            unsigned Linkage, bool HasLinkage,
848                            unsigned Visibility, unsigned DLLStorageClass,
849                            GlobalVariable::ThreadLocalMode TLM,
850                            GlobalVariable::UnnamedAddr UnnamedAddr) {
851   if (!isValidVisibilityForLinkage(Visibility, Linkage))
852     return Error(NameLoc,
853                  "symbol with local linkage must have default visibility");
854 
855   unsigned AddrSpace;
856   bool IsConstant, IsExternallyInitialized;
857   LocTy IsExternallyInitializedLoc;
858   LocTy TyLoc;
859 
860   Type *Ty = nullptr;
861   if (ParseOptionalAddrSpace(AddrSpace) ||
862       ParseOptionalToken(lltok::kw_externally_initialized,
863                          IsExternallyInitialized,
864                          &IsExternallyInitializedLoc) ||
865       ParseGlobalType(IsConstant) ||
866       ParseType(Ty, TyLoc))
867     return true;
868 
869   // If the linkage is specified and is external, then no initializer is
870   // present.
871   Constant *Init = nullptr;
872   if (!HasLinkage ||
873       !GlobalValue::isValidDeclarationLinkage(
874           (GlobalValue::LinkageTypes)Linkage)) {
875     if (ParseGlobalValue(Ty, Init))
876       return true;
877   }
878 
879   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
880     return Error(TyLoc, "invalid type for global variable");
881 
882   GlobalValue *GVal = nullptr;
883 
884   // See if the global was forward referenced, if so, use the global.
885   if (!Name.empty()) {
886     GVal = M->getNamedValue(Name);
887     if (GVal) {
888       if (!ForwardRefVals.erase(Name))
889         return Error(NameLoc, "redefinition of global '@" + Name + "'");
890     }
891   } else {
892     auto I = ForwardRefValIDs.find(NumberedVals.size());
893     if (I != ForwardRefValIDs.end()) {
894       GVal = I->second.first;
895       ForwardRefValIDs.erase(I);
896     }
897   }
898 
899   GlobalVariable *GV;
900   if (!GVal) {
901     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
902                             Name, nullptr, GlobalVariable::NotThreadLocal,
903                             AddrSpace);
904   } else {
905     if (GVal->getValueType() != Ty)
906       return Error(TyLoc,
907             "forward reference and definition of global have different types");
908 
909     GV = cast<GlobalVariable>(GVal);
910 
911     // Move the forward-reference to the correct spot in the module.
912     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
913   }
914 
915   if (Name.empty())
916     NumberedVals.push_back(GV);
917 
918   // Set the parsed properties on the global.
919   if (Init)
920     GV->setInitializer(Init);
921   GV->setConstant(IsConstant);
922   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
923   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
924   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
925   GV->setExternallyInitialized(IsExternallyInitialized);
926   GV->setThreadLocalMode(TLM);
927   GV->setUnnamedAddr(UnnamedAddr);
928 
929   // Parse attributes on the global.
930   while (Lex.getKind() == lltok::comma) {
931     Lex.Lex();
932 
933     if (Lex.getKind() == lltok::kw_section) {
934       Lex.Lex();
935       GV->setSection(Lex.getStrVal());
936       if (ParseToken(lltok::StringConstant, "expected global section string"))
937         return true;
938     } else if (Lex.getKind() == lltok::kw_align) {
939       unsigned Alignment;
940       if (ParseOptionalAlignment(Alignment)) return true;
941       GV->setAlignment(Alignment);
942     } else if (Lex.getKind() == lltok::MetadataVar) {
943       if (ParseGlobalObjectMetadataAttachment(*GV))
944         return true;
945     } else {
946       Comdat *C;
947       if (parseOptionalComdat(Name, C))
948         return true;
949       if (C)
950         GV->setComdat(C);
951       else
952         return TokError("unknown global variable property!");
953     }
954   }
955 
956   return false;
957 }
958 
959 /// ParseUnnamedAttrGrp
960 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
961 bool LLParser::ParseUnnamedAttrGrp() {
962   assert(Lex.getKind() == lltok::kw_attributes);
963   LocTy AttrGrpLoc = Lex.getLoc();
964   Lex.Lex();
965 
966   if (Lex.getKind() != lltok::AttrGrpID)
967     return TokError("expected attribute group id");
968 
969   unsigned VarID = Lex.getUIntVal();
970   std::vector<unsigned> unused;
971   LocTy BuiltinLoc;
972   Lex.Lex();
973 
974   if (ParseToken(lltok::equal, "expected '=' here") ||
975       ParseToken(lltok::lbrace, "expected '{' here") ||
976       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
977                                  BuiltinLoc) ||
978       ParseToken(lltok::rbrace, "expected end of attribute group"))
979     return true;
980 
981   if (!NumberedAttrBuilders[VarID].hasAttributes())
982     return Error(AttrGrpLoc, "attribute group has no attributes");
983 
984   return false;
985 }
986 
987 /// ParseFnAttributeValuePairs
988 ///   ::= <attr> | <attr> '=' <value>
989 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
990                                           std::vector<unsigned> &FwdRefAttrGrps,
991                                           bool inAttrGrp, LocTy &BuiltinLoc) {
992   bool HaveError = false;
993 
994   B.clear();
995 
996   while (true) {
997     lltok::Kind Token = Lex.getKind();
998     if (Token == lltok::kw_builtin)
999       BuiltinLoc = Lex.getLoc();
1000     switch (Token) {
1001     default:
1002       if (!inAttrGrp) return HaveError;
1003       return Error(Lex.getLoc(), "unterminated attribute group");
1004     case lltok::rbrace:
1005       // Finished.
1006       return false;
1007 
1008     case lltok::AttrGrpID: {
1009       // Allow a function to reference an attribute group:
1010       //
1011       //   define void @foo() #1 { ... }
1012       if (inAttrGrp)
1013         HaveError |=
1014           Error(Lex.getLoc(),
1015               "cannot have an attribute group reference in an attribute group");
1016 
1017       unsigned AttrGrpNum = Lex.getUIntVal();
1018       if (inAttrGrp) break;
1019 
1020       // Save the reference to the attribute group. We'll fill it in later.
1021       FwdRefAttrGrps.push_back(AttrGrpNum);
1022       break;
1023     }
1024     // Target-dependent attributes:
1025     case lltok::StringConstant: {
1026       if (ParseStringAttribute(B))
1027         return true;
1028       continue;
1029     }
1030 
1031     // Target-independent attributes:
1032     case lltok::kw_align: {
1033       // As a hack, we allow function alignment to be initially parsed as an
1034       // attribute on a function declaration/definition or added to an attribute
1035       // group and later moved to the alignment field.
1036       unsigned Alignment;
1037       if (inAttrGrp) {
1038         Lex.Lex();
1039         if (ParseToken(lltok::equal, "expected '=' here") ||
1040             ParseUInt32(Alignment))
1041           return true;
1042       } else {
1043         if (ParseOptionalAlignment(Alignment))
1044           return true;
1045       }
1046       B.addAlignmentAttr(Alignment);
1047       continue;
1048     }
1049     case lltok::kw_alignstack: {
1050       unsigned Alignment;
1051       if (inAttrGrp) {
1052         Lex.Lex();
1053         if (ParseToken(lltok::equal, "expected '=' here") ||
1054             ParseUInt32(Alignment))
1055           return true;
1056       } else {
1057         if (ParseOptionalStackAlignment(Alignment))
1058           return true;
1059       }
1060       B.addStackAlignmentAttr(Alignment);
1061       continue;
1062     }
1063     case lltok::kw_allocsize: {
1064       unsigned ElemSizeArg;
1065       Optional<unsigned> NumElemsArg;
1066       // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1067       if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1068         return true;
1069       B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1070       continue;
1071     }
1072     case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1073     case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1074     case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1075     case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1076     case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1077     case lltok::kw_inaccessiblememonly:
1078       B.addAttribute(Attribute::InaccessibleMemOnly); break;
1079     case lltok::kw_inaccessiblemem_or_argmemonly:
1080       B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1081     case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1082     case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1083     case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1084     case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1085     case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1086     case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1087     case lltok::kw_noimplicitfloat:
1088       B.addAttribute(Attribute::NoImplicitFloat); break;
1089     case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1090     case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1091     case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1092     case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1093     case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1094     case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1095     case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1096     case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1097     case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1098     case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1099     case lltok::kw_returns_twice:
1100       B.addAttribute(Attribute::ReturnsTwice); break;
1101     case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1102     case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1103     case lltok::kw_sspstrong:
1104       B.addAttribute(Attribute::StackProtectStrong); break;
1105     case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1106     case lltok::kw_sanitize_address:
1107       B.addAttribute(Attribute::SanitizeAddress); break;
1108     case lltok::kw_sanitize_thread:
1109       B.addAttribute(Attribute::SanitizeThread); break;
1110     case lltok::kw_sanitize_memory:
1111       B.addAttribute(Attribute::SanitizeMemory); break;
1112     case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1113     case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1114 
1115     // Error handling.
1116     case lltok::kw_inreg:
1117     case lltok::kw_signext:
1118     case lltok::kw_zeroext:
1119       HaveError |=
1120         Error(Lex.getLoc(),
1121               "invalid use of attribute on a function");
1122       break;
1123     case lltok::kw_byval:
1124     case lltok::kw_dereferenceable:
1125     case lltok::kw_dereferenceable_or_null:
1126     case lltok::kw_inalloca:
1127     case lltok::kw_nest:
1128     case lltok::kw_noalias:
1129     case lltok::kw_nocapture:
1130     case lltok::kw_nonnull:
1131     case lltok::kw_returned:
1132     case lltok::kw_sret:
1133     case lltok::kw_swifterror:
1134     case lltok::kw_swiftself:
1135       HaveError |=
1136         Error(Lex.getLoc(),
1137               "invalid use of parameter-only attribute on a function");
1138       break;
1139     }
1140 
1141     Lex.Lex();
1142   }
1143 }
1144 
1145 //===----------------------------------------------------------------------===//
1146 // GlobalValue Reference/Resolution Routines.
1147 //===----------------------------------------------------------------------===//
1148 
1149 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1150                                               const std::string &Name) {
1151   if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1152     return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1153   else
1154     return new GlobalVariable(*M, PTy->getElementType(), false,
1155                               GlobalValue::ExternalWeakLinkage, nullptr, Name,
1156                               nullptr, GlobalVariable::NotThreadLocal,
1157                               PTy->getAddressSpace());
1158 }
1159 
1160 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1161 /// forward reference record if needed.  This can return null if the value
1162 /// exists but does not have the right type.
1163 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1164                                     LocTy Loc) {
1165   PointerType *PTy = dyn_cast<PointerType>(Ty);
1166   if (!PTy) {
1167     Error(Loc, "global variable reference must have pointer type");
1168     return nullptr;
1169   }
1170 
1171   // Look this name up in the normal function symbol table.
1172   GlobalValue *Val =
1173     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1174 
1175   // If this is a forward reference for the value, see if we already created a
1176   // forward ref record.
1177   if (!Val) {
1178     auto I = ForwardRefVals.find(Name);
1179     if (I != ForwardRefVals.end())
1180       Val = I->second.first;
1181   }
1182 
1183   // If we have the value in the symbol table or fwd-ref table, return it.
1184   if (Val) {
1185     if (Val->getType() == Ty) return Val;
1186     Error(Loc, "'@" + Name + "' defined with type '" +
1187           getTypeString(Val->getType()) + "'");
1188     return nullptr;
1189   }
1190 
1191   // Otherwise, create a new forward reference for this value and remember it.
1192   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1193   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1194   return FwdVal;
1195 }
1196 
1197 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1198   PointerType *PTy = dyn_cast<PointerType>(Ty);
1199   if (!PTy) {
1200     Error(Loc, "global variable reference must have pointer type");
1201     return nullptr;
1202   }
1203 
1204   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1205 
1206   // If this is a forward reference for the value, see if we already created a
1207   // forward ref record.
1208   if (!Val) {
1209     auto I = ForwardRefValIDs.find(ID);
1210     if (I != ForwardRefValIDs.end())
1211       Val = I->second.first;
1212   }
1213 
1214   // If we have the value in the symbol table or fwd-ref table, return it.
1215   if (Val) {
1216     if (Val->getType() == Ty) return Val;
1217     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1218           getTypeString(Val->getType()) + "'");
1219     return nullptr;
1220   }
1221 
1222   // Otherwise, create a new forward reference for this value and remember it.
1223   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1224   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1225   return FwdVal;
1226 }
1227 
1228 //===----------------------------------------------------------------------===//
1229 // Comdat Reference/Resolution Routines.
1230 //===----------------------------------------------------------------------===//
1231 
1232 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1233   // Look this name up in the comdat symbol table.
1234   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1235   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1236   if (I != ComdatSymTab.end())
1237     return &I->second;
1238 
1239   // Otherwise, create a new forward reference for this value and remember it.
1240   Comdat *C = M->getOrInsertComdat(Name);
1241   ForwardRefComdats[Name] = Loc;
1242   return C;
1243 }
1244 
1245 //===----------------------------------------------------------------------===//
1246 // Helper Routines.
1247 //===----------------------------------------------------------------------===//
1248 
1249 /// ParseToken - If the current token has the specified kind, eat it and return
1250 /// success.  Otherwise, emit the specified error and return failure.
1251 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1252   if (Lex.getKind() != T)
1253     return TokError(ErrMsg);
1254   Lex.Lex();
1255   return false;
1256 }
1257 
1258 /// ParseStringConstant
1259 ///   ::= StringConstant
1260 bool LLParser::ParseStringConstant(std::string &Result) {
1261   if (Lex.getKind() != lltok::StringConstant)
1262     return TokError("expected string constant");
1263   Result = Lex.getStrVal();
1264   Lex.Lex();
1265   return false;
1266 }
1267 
1268 /// ParseUInt32
1269 ///   ::= uint32
1270 bool LLParser::ParseUInt32(uint32_t &Val) {
1271   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1272     return TokError("expected integer");
1273   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1274   if (Val64 != unsigned(Val64))
1275     return TokError("expected 32-bit integer (too large)");
1276   Val = Val64;
1277   Lex.Lex();
1278   return false;
1279 }
1280 
1281 /// ParseUInt64
1282 ///   ::= uint64
1283 bool LLParser::ParseUInt64(uint64_t &Val) {
1284   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1285     return TokError("expected integer");
1286   Val = Lex.getAPSIntVal().getLimitedValue();
1287   Lex.Lex();
1288   return false;
1289 }
1290 
1291 /// ParseTLSModel
1292 ///   := 'localdynamic'
1293 ///   := 'initialexec'
1294 ///   := 'localexec'
1295 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1296   switch (Lex.getKind()) {
1297     default:
1298       return TokError("expected localdynamic, initialexec or localexec");
1299     case lltok::kw_localdynamic:
1300       TLM = GlobalVariable::LocalDynamicTLSModel;
1301       break;
1302     case lltok::kw_initialexec:
1303       TLM = GlobalVariable::InitialExecTLSModel;
1304       break;
1305     case lltok::kw_localexec:
1306       TLM = GlobalVariable::LocalExecTLSModel;
1307       break;
1308   }
1309 
1310   Lex.Lex();
1311   return false;
1312 }
1313 
1314 /// ParseOptionalThreadLocal
1315 ///   := /*empty*/
1316 ///   := 'thread_local'
1317 ///   := 'thread_local' '(' tlsmodel ')'
1318 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1319   TLM = GlobalVariable::NotThreadLocal;
1320   if (!EatIfPresent(lltok::kw_thread_local))
1321     return false;
1322 
1323   TLM = GlobalVariable::GeneralDynamicTLSModel;
1324   if (Lex.getKind() == lltok::lparen) {
1325     Lex.Lex();
1326     return ParseTLSModel(TLM) ||
1327       ParseToken(lltok::rparen, "expected ')' after thread local model");
1328   }
1329   return false;
1330 }
1331 
1332 /// ParseOptionalAddrSpace
1333 ///   := /*empty*/
1334 ///   := 'addrspace' '(' uint32 ')'
1335 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1336   AddrSpace = 0;
1337   if (!EatIfPresent(lltok::kw_addrspace))
1338     return false;
1339   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1340          ParseUInt32(AddrSpace) ||
1341          ParseToken(lltok::rparen, "expected ')' in address space");
1342 }
1343 
1344 /// ParseStringAttribute
1345 ///   := StringConstant
1346 ///   := StringConstant '=' StringConstant
1347 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1348   std::string Attr = Lex.getStrVal();
1349   Lex.Lex();
1350   std::string Val;
1351   if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1352     return true;
1353   B.addAttribute(Attr, Val);
1354   return false;
1355 }
1356 
1357 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1358 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1359   bool HaveError = false;
1360 
1361   B.clear();
1362 
1363   while (true) {
1364     lltok::Kind Token = Lex.getKind();
1365     switch (Token) {
1366     default:  // End of attributes.
1367       return HaveError;
1368     case lltok::StringConstant: {
1369       if (ParseStringAttribute(B))
1370         return true;
1371       continue;
1372     }
1373     case lltok::kw_align: {
1374       unsigned Alignment;
1375       if (ParseOptionalAlignment(Alignment))
1376         return true;
1377       B.addAlignmentAttr(Alignment);
1378       continue;
1379     }
1380     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1381     case lltok::kw_dereferenceable: {
1382       uint64_t Bytes;
1383       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1384         return true;
1385       B.addDereferenceableAttr(Bytes);
1386       continue;
1387     }
1388     case lltok::kw_dereferenceable_or_null: {
1389       uint64_t Bytes;
1390       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1391         return true;
1392       B.addDereferenceableOrNullAttr(Bytes);
1393       continue;
1394     }
1395     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1396     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1397     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1398     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1399     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1400     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1401     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1402     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1403     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1404     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1405     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1406     case lltok::kw_swifterror:      B.addAttribute(Attribute::SwiftError); break;
1407     case lltok::kw_swiftself:       B.addAttribute(Attribute::SwiftSelf); break;
1408     case lltok::kw_writeonly:       B.addAttribute(Attribute::WriteOnly); break;
1409     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1410 
1411     case lltok::kw_alignstack:
1412     case lltok::kw_alwaysinline:
1413     case lltok::kw_argmemonly:
1414     case lltok::kw_builtin:
1415     case lltok::kw_inlinehint:
1416     case lltok::kw_jumptable:
1417     case lltok::kw_minsize:
1418     case lltok::kw_naked:
1419     case lltok::kw_nobuiltin:
1420     case lltok::kw_noduplicate:
1421     case lltok::kw_noimplicitfloat:
1422     case lltok::kw_noinline:
1423     case lltok::kw_nonlazybind:
1424     case lltok::kw_noredzone:
1425     case lltok::kw_noreturn:
1426     case lltok::kw_nounwind:
1427     case lltok::kw_optnone:
1428     case lltok::kw_optsize:
1429     case lltok::kw_returns_twice:
1430     case lltok::kw_sanitize_address:
1431     case lltok::kw_sanitize_memory:
1432     case lltok::kw_sanitize_thread:
1433     case lltok::kw_ssp:
1434     case lltok::kw_sspreq:
1435     case lltok::kw_sspstrong:
1436     case lltok::kw_safestack:
1437     case lltok::kw_uwtable:
1438       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1439       break;
1440     }
1441 
1442     Lex.Lex();
1443   }
1444 }
1445 
1446 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1447 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1448   bool HaveError = false;
1449 
1450   B.clear();
1451 
1452   while (true) {
1453     lltok::Kind Token = Lex.getKind();
1454     switch (Token) {
1455     default:  // End of attributes.
1456       return HaveError;
1457     case lltok::StringConstant: {
1458       if (ParseStringAttribute(B))
1459         return true;
1460       continue;
1461     }
1462     case lltok::kw_dereferenceable: {
1463       uint64_t Bytes;
1464       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1465         return true;
1466       B.addDereferenceableAttr(Bytes);
1467       continue;
1468     }
1469     case lltok::kw_dereferenceable_or_null: {
1470       uint64_t Bytes;
1471       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1472         return true;
1473       B.addDereferenceableOrNullAttr(Bytes);
1474       continue;
1475     }
1476     case lltok::kw_align: {
1477       unsigned Alignment;
1478       if (ParseOptionalAlignment(Alignment))
1479         return true;
1480       B.addAlignmentAttr(Alignment);
1481       continue;
1482     }
1483     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1484     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1485     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1486     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1487     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1488 
1489     // Error handling.
1490     case lltok::kw_byval:
1491     case lltok::kw_inalloca:
1492     case lltok::kw_nest:
1493     case lltok::kw_nocapture:
1494     case lltok::kw_returned:
1495     case lltok::kw_sret:
1496     case lltok::kw_swifterror:
1497     case lltok::kw_swiftself:
1498       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1499       break;
1500 
1501     case lltok::kw_alignstack:
1502     case lltok::kw_alwaysinline:
1503     case lltok::kw_argmemonly:
1504     case lltok::kw_builtin:
1505     case lltok::kw_cold:
1506     case lltok::kw_inlinehint:
1507     case lltok::kw_jumptable:
1508     case lltok::kw_minsize:
1509     case lltok::kw_naked:
1510     case lltok::kw_nobuiltin:
1511     case lltok::kw_noduplicate:
1512     case lltok::kw_noimplicitfloat:
1513     case lltok::kw_noinline:
1514     case lltok::kw_nonlazybind:
1515     case lltok::kw_noredzone:
1516     case lltok::kw_noreturn:
1517     case lltok::kw_nounwind:
1518     case lltok::kw_optnone:
1519     case lltok::kw_optsize:
1520     case lltok::kw_returns_twice:
1521     case lltok::kw_sanitize_address:
1522     case lltok::kw_sanitize_memory:
1523     case lltok::kw_sanitize_thread:
1524     case lltok::kw_ssp:
1525     case lltok::kw_sspreq:
1526     case lltok::kw_sspstrong:
1527     case lltok::kw_safestack:
1528     case lltok::kw_uwtable:
1529       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1530       break;
1531 
1532     case lltok::kw_readnone:
1533     case lltok::kw_readonly:
1534       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1535     }
1536 
1537     Lex.Lex();
1538   }
1539 }
1540 
1541 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1542   HasLinkage = true;
1543   switch (Kind) {
1544   default:
1545     HasLinkage = false;
1546     return GlobalValue::ExternalLinkage;
1547   case lltok::kw_private:
1548     return GlobalValue::PrivateLinkage;
1549   case lltok::kw_internal:
1550     return GlobalValue::InternalLinkage;
1551   case lltok::kw_weak:
1552     return GlobalValue::WeakAnyLinkage;
1553   case lltok::kw_weak_odr:
1554     return GlobalValue::WeakODRLinkage;
1555   case lltok::kw_linkonce:
1556     return GlobalValue::LinkOnceAnyLinkage;
1557   case lltok::kw_linkonce_odr:
1558     return GlobalValue::LinkOnceODRLinkage;
1559   case lltok::kw_available_externally:
1560     return GlobalValue::AvailableExternallyLinkage;
1561   case lltok::kw_appending:
1562     return GlobalValue::AppendingLinkage;
1563   case lltok::kw_common:
1564     return GlobalValue::CommonLinkage;
1565   case lltok::kw_extern_weak:
1566     return GlobalValue::ExternalWeakLinkage;
1567   case lltok::kw_external:
1568     return GlobalValue::ExternalLinkage;
1569   }
1570 }
1571 
1572 /// ParseOptionalLinkage
1573 ///   ::= /*empty*/
1574 ///   ::= 'private'
1575 ///   ::= 'internal'
1576 ///   ::= 'weak'
1577 ///   ::= 'weak_odr'
1578 ///   ::= 'linkonce'
1579 ///   ::= 'linkonce_odr'
1580 ///   ::= 'available_externally'
1581 ///   ::= 'appending'
1582 ///   ::= 'common'
1583 ///   ::= 'extern_weak'
1584 ///   ::= 'external'
1585 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1586                                     unsigned &Visibility,
1587                                     unsigned &DLLStorageClass) {
1588   Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1589   if (HasLinkage)
1590     Lex.Lex();
1591   ParseOptionalVisibility(Visibility);
1592   ParseOptionalDLLStorageClass(DLLStorageClass);
1593   return false;
1594 }
1595 
1596 /// ParseOptionalVisibility
1597 ///   ::= /*empty*/
1598 ///   ::= 'default'
1599 ///   ::= 'hidden'
1600 ///   ::= 'protected'
1601 ///
1602 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1603   switch (Lex.getKind()) {
1604   default:
1605     Res = GlobalValue::DefaultVisibility;
1606     return;
1607   case lltok::kw_default:
1608     Res = GlobalValue::DefaultVisibility;
1609     break;
1610   case lltok::kw_hidden:
1611     Res = GlobalValue::HiddenVisibility;
1612     break;
1613   case lltok::kw_protected:
1614     Res = GlobalValue::ProtectedVisibility;
1615     break;
1616   }
1617   Lex.Lex();
1618 }
1619 
1620 /// ParseOptionalDLLStorageClass
1621 ///   ::= /*empty*/
1622 ///   ::= 'dllimport'
1623 ///   ::= 'dllexport'
1624 ///
1625 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1626   switch (Lex.getKind()) {
1627   default:
1628     Res = GlobalValue::DefaultStorageClass;
1629     return;
1630   case lltok::kw_dllimport:
1631     Res = GlobalValue::DLLImportStorageClass;
1632     break;
1633   case lltok::kw_dllexport:
1634     Res = GlobalValue::DLLExportStorageClass;
1635     break;
1636   }
1637   Lex.Lex();
1638 }
1639 
1640 /// ParseOptionalCallingConv
1641 ///   ::= /*empty*/
1642 ///   ::= 'ccc'
1643 ///   ::= 'fastcc'
1644 ///   ::= 'intel_ocl_bicc'
1645 ///   ::= 'coldcc'
1646 ///   ::= 'x86_stdcallcc'
1647 ///   ::= 'x86_fastcallcc'
1648 ///   ::= 'x86_thiscallcc'
1649 ///   ::= 'x86_vectorcallcc'
1650 ///   ::= 'arm_apcscc'
1651 ///   ::= 'arm_aapcscc'
1652 ///   ::= 'arm_aapcs_vfpcc'
1653 ///   ::= 'msp430_intrcc'
1654 ///   ::= 'avr_intrcc'
1655 ///   ::= 'avr_signalcc'
1656 ///   ::= 'ptx_kernel'
1657 ///   ::= 'ptx_device'
1658 ///   ::= 'spir_func'
1659 ///   ::= 'spir_kernel'
1660 ///   ::= 'x86_64_sysvcc'
1661 ///   ::= 'x86_64_win64cc'
1662 ///   ::= 'webkit_jscc'
1663 ///   ::= 'anyregcc'
1664 ///   ::= 'preserve_mostcc'
1665 ///   ::= 'preserve_allcc'
1666 ///   ::= 'ghccc'
1667 ///   ::= 'swiftcc'
1668 ///   ::= 'x86_intrcc'
1669 ///   ::= 'hhvmcc'
1670 ///   ::= 'hhvm_ccc'
1671 ///   ::= 'cxx_fast_tlscc'
1672 ///   ::= 'amdgpu_vs'
1673 ///   ::= 'amdgpu_tcs'
1674 ///   ::= 'amdgpu_tes'
1675 ///   ::= 'amdgpu_gs'
1676 ///   ::= 'amdgpu_ps'
1677 ///   ::= 'amdgpu_cs'
1678 ///   ::= 'amdgpu_kernel'
1679 ///   ::= 'cc' UINT
1680 ///
1681 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1682   switch (Lex.getKind()) {
1683   default:                       CC = CallingConv::C; return false;
1684   case lltok::kw_ccc:            CC = CallingConv::C; break;
1685   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1686   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1687   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1688   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1689   case lltok::kw_x86_regcallcc:  CC = CallingConv::X86_RegCall; break;
1690   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1691   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1692   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1693   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1694   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1695   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1696   case lltok::kw_avr_intrcc:     CC = CallingConv::AVR_INTR; break;
1697   case lltok::kw_avr_signalcc:   CC = CallingConv::AVR_SIGNAL; break;
1698   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1699   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1700   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1701   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1702   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1703   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1704   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1705   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1706   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1707   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1708   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1709   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1710   case lltok::kw_swiftcc:        CC = CallingConv::Swift; break;
1711   case lltok::kw_x86_intrcc:     CC = CallingConv::X86_INTR; break;
1712   case lltok::kw_hhvmcc:         CC = CallingConv::HHVM; break;
1713   case lltok::kw_hhvm_ccc:       CC = CallingConv::HHVM_C; break;
1714   case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1715   case lltok::kw_amdgpu_vs:      CC = CallingConv::AMDGPU_VS; break;
1716   case lltok::kw_amdgpu_gs:      CC = CallingConv::AMDGPU_GS; break;
1717   case lltok::kw_amdgpu_ps:      CC = CallingConv::AMDGPU_PS; break;
1718   case lltok::kw_amdgpu_cs:      CC = CallingConv::AMDGPU_CS; break;
1719   case lltok::kw_amdgpu_kernel:  CC = CallingConv::AMDGPU_KERNEL; break;
1720   case lltok::kw_cc: {
1721       Lex.Lex();
1722       return ParseUInt32(CC);
1723     }
1724   }
1725 
1726   Lex.Lex();
1727   return false;
1728 }
1729 
1730 /// ParseMetadataAttachment
1731 ///   ::= !dbg !42
1732 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1733   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1734 
1735   std::string Name = Lex.getStrVal();
1736   Kind = M->getMDKindID(Name);
1737   Lex.Lex();
1738 
1739   return ParseMDNode(MD);
1740 }
1741 
1742 /// ParseInstructionMetadata
1743 ///   ::= !dbg !42 (',' !dbg !57)*
1744 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1745   do {
1746     if (Lex.getKind() != lltok::MetadataVar)
1747       return TokError("expected metadata after comma");
1748 
1749     unsigned MDK;
1750     MDNode *N;
1751     if (ParseMetadataAttachment(MDK, N))
1752       return true;
1753 
1754     Inst.setMetadata(MDK, N);
1755     if (MDK == LLVMContext::MD_tbaa)
1756       InstsWithTBAATag.push_back(&Inst);
1757 
1758     // If this is the end of the list, we're done.
1759   } while (EatIfPresent(lltok::comma));
1760   return false;
1761 }
1762 
1763 /// ParseGlobalObjectMetadataAttachment
1764 ///   ::= !dbg !57
1765 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1766   unsigned MDK;
1767   MDNode *N;
1768   if (ParseMetadataAttachment(MDK, N))
1769     return true;
1770 
1771   GO.addMetadata(MDK, *N);
1772   return false;
1773 }
1774 
1775 /// ParseOptionalFunctionMetadata
1776 ///   ::= (!dbg !57)*
1777 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1778   while (Lex.getKind() == lltok::MetadataVar)
1779     if (ParseGlobalObjectMetadataAttachment(F))
1780       return true;
1781   return false;
1782 }
1783 
1784 /// ParseOptionalAlignment
1785 ///   ::= /* empty */
1786 ///   ::= 'align' 4
1787 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1788   Alignment = 0;
1789   if (!EatIfPresent(lltok::kw_align))
1790     return false;
1791   LocTy AlignLoc = Lex.getLoc();
1792   if (ParseUInt32(Alignment)) return true;
1793   if (!isPowerOf2_32(Alignment))
1794     return Error(AlignLoc, "alignment is not a power of two");
1795   if (Alignment > Value::MaximumAlignment)
1796     return Error(AlignLoc, "huge alignments are not supported yet");
1797   return false;
1798 }
1799 
1800 /// ParseOptionalDerefAttrBytes
1801 ///   ::= /* empty */
1802 ///   ::= AttrKind '(' 4 ')'
1803 ///
1804 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1805 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1806                                            uint64_t &Bytes) {
1807   assert((AttrKind == lltok::kw_dereferenceable ||
1808           AttrKind == lltok::kw_dereferenceable_or_null) &&
1809          "contract!");
1810 
1811   Bytes = 0;
1812   if (!EatIfPresent(AttrKind))
1813     return false;
1814   LocTy ParenLoc = Lex.getLoc();
1815   if (!EatIfPresent(lltok::lparen))
1816     return Error(ParenLoc, "expected '('");
1817   LocTy DerefLoc = Lex.getLoc();
1818   if (ParseUInt64(Bytes)) return true;
1819   ParenLoc = Lex.getLoc();
1820   if (!EatIfPresent(lltok::rparen))
1821     return Error(ParenLoc, "expected ')'");
1822   if (!Bytes)
1823     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1824   return false;
1825 }
1826 
1827 /// ParseOptionalCommaAlign
1828 ///   ::=
1829 ///   ::= ',' align 4
1830 ///
1831 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1832 /// end.
1833 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1834                                        bool &AteExtraComma) {
1835   AteExtraComma = false;
1836   while (EatIfPresent(lltok::comma)) {
1837     // Metadata at the end is an early exit.
1838     if (Lex.getKind() == lltok::MetadataVar) {
1839       AteExtraComma = true;
1840       return false;
1841     }
1842 
1843     if (Lex.getKind() != lltok::kw_align)
1844       return Error(Lex.getLoc(), "expected metadata or 'align'");
1845 
1846     if (ParseOptionalAlignment(Alignment)) return true;
1847   }
1848 
1849   return false;
1850 }
1851 
1852 /// ParseOptionalCommaAddrSpace
1853 ///   ::=
1854 ///   ::= ',' addrspace(1)
1855 ///
1856 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1857 /// end.
1858 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1859                                            LocTy &Loc,
1860                                            bool &AteExtraComma) {
1861   AteExtraComma = false;
1862   while (EatIfPresent(lltok::comma)) {
1863     // Metadata at the end is an early exit.
1864     if (Lex.getKind() == lltok::MetadataVar) {
1865       AteExtraComma = true;
1866       return false;
1867     }
1868 
1869     Loc = Lex.getLoc();
1870     if (Lex.getKind() != lltok::kw_addrspace)
1871       return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1872 
1873     if (ParseOptionalAddrSpace(AddrSpace))
1874       return true;
1875   }
1876 
1877   return false;
1878 }
1879 
1880 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1881                                        Optional<unsigned> &HowManyArg) {
1882   Lex.Lex();
1883 
1884   auto StartParen = Lex.getLoc();
1885   if (!EatIfPresent(lltok::lparen))
1886     return Error(StartParen, "expected '('");
1887 
1888   if (ParseUInt32(BaseSizeArg))
1889     return true;
1890 
1891   if (EatIfPresent(lltok::comma)) {
1892     auto HowManyAt = Lex.getLoc();
1893     unsigned HowMany;
1894     if (ParseUInt32(HowMany))
1895       return true;
1896     if (HowMany == BaseSizeArg)
1897       return Error(HowManyAt,
1898                    "'allocsize' indices can't refer to the same parameter");
1899     HowManyArg = HowMany;
1900   } else
1901     HowManyArg = None;
1902 
1903   auto EndParen = Lex.getLoc();
1904   if (!EatIfPresent(lltok::rparen))
1905     return Error(EndParen, "expected ')'");
1906   return false;
1907 }
1908 
1909 /// ParseScopeAndOrdering
1910 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1911 ///   else: ::=
1912 ///
1913 /// This sets Scope and Ordering to the parsed values.
1914 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1915                                      AtomicOrdering &Ordering) {
1916   if (!isAtomic)
1917     return false;
1918 
1919   Scope = CrossThread;
1920   if (EatIfPresent(lltok::kw_singlethread))
1921     Scope = SingleThread;
1922 
1923   return ParseOrdering(Ordering);
1924 }
1925 
1926 /// ParseOrdering
1927 ///   ::= AtomicOrdering
1928 ///
1929 /// This sets Ordering to the parsed value.
1930 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1931   switch (Lex.getKind()) {
1932   default: return TokError("Expected ordering on atomic instruction");
1933   case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1934   case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1935   // Not specified yet:
1936   // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1937   case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1938   case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1939   case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1940   case lltok::kw_seq_cst:
1941     Ordering = AtomicOrdering::SequentiallyConsistent;
1942     break;
1943   }
1944   Lex.Lex();
1945   return false;
1946 }
1947 
1948 /// ParseOptionalStackAlignment
1949 ///   ::= /* empty */
1950 ///   ::= 'alignstack' '(' 4 ')'
1951 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1952   Alignment = 0;
1953   if (!EatIfPresent(lltok::kw_alignstack))
1954     return false;
1955   LocTy ParenLoc = Lex.getLoc();
1956   if (!EatIfPresent(lltok::lparen))
1957     return Error(ParenLoc, "expected '('");
1958   LocTy AlignLoc = Lex.getLoc();
1959   if (ParseUInt32(Alignment)) return true;
1960   ParenLoc = Lex.getLoc();
1961   if (!EatIfPresent(lltok::rparen))
1962     return Error(ParenLoc, "expected ')'");
1963   if (!isPowerOf2_32(Alignment))
1964     return Error(AlignLoc, "stack alignment is not a power of two");
1965   return false;
1966 }
1967 
1968 /// ParseIndexList - This parses the index list for an insert/extractvalue
1969 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1970 /// comma at the end of the line and find that it is followed by metadata.
1971 /// Clients that don't allow metadata can call the version of this function that
1972 /// only takes one argument.
1973 ///
1974 /// ParseIndexList
1975 ///    ::=  (',' uint32)+
1976 ///
1977 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1978                               bool &AteExtraComma) {
1979   AteExtraComma = false;
1980 
1981   if (Lex.getKind() != lltok::comma)
1982     return TokError("expected ',' as start of index list");
1983 
1984   while (EatIfPresent(lltok::comma)) {
1985     if (Lex.getKind() == lltok::MetadataVar) {
1986       if (Indices.empty()) return TokError("expected index");
1987       AteExtraComma = true;
1988       return false;
1989     }
1990     unsigned Idx = 0;
1991     if (ParseUInt32(Idx)) return true;
1992     Indices.push_back(Idx);
1993   }
1994 
1995   return false;
1996 }
1997 
1998 //===----------------------------------------------------------------------===//
1999 // Type Parsing.
2000 //===----------------------------------------------------------------------===//
2001 
2002 /// ParseType - Parse a type.
2003 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2004   SMLoc TypeLoc = Lex.getLoc();
2005   switch (Lex.getKind()) {
2006   default:
2007     return TokError(Msg);
2008   case lltok::Type:
2009     // Type ::= 'float' | 'void' (etc)
2010     Result = Lex.getTyVal();
2011     Lex.Lex();
2012     break;
2013   case lltok::lbrace:
2014     // Type ::= StructType
2015     if (ParseAnonStructType(Result, false))
2016       return true;
2017     break;
2018   case lltok::lsquare:
2019     // Type ::= '[' ... ']'
2020     Lex.Lex(); // eat the lsquare.
2021     if (ParseArrayVectorType(Result, false))
2022       return true;
2023     break;
2024   case lltok::less: // Either vector or packed struct.
2025     // Type ::= '<' ... '>'
2026     Lex.Lex();
2027     if (Lex.getKind() == lltok::lbrace) {
2028       if (ParseAnonStructType(Result, true) ||
2029           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2030         return true;
2031     } else if (ParseArrayVectorType(Result, true))
2032       return true;
2033     break;
2034   case lltok::LocalVar: {
2035     // Type ::= %foo
2036     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2037 
2038     // If the type hasn't been defined yet, create a forward definition and
2039     // remember where that forward def'n was seen (in case it never is defined).
2040     if (!Entry.first) {
2041       Entry.first = StructType::create(Context, Lex.getStrVal());
2042       Entry.second = Lex.getLoc();
2043     }
2044     Result = Entry.first;
2045     Lex.Lex();
2046     break;
2047   }
2048 
2049   case lltok::LocalVarID: {
2050     // Type ::= %4
2051     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2052 
2053     // If the type hasn't been defined yet, create a forward definition and
2054     // remember where that forward def'n was seen (in case it never is defined).
2055     if (!Entry.first) {
2056       Entry.first = StructType::create(Context);
2057       Entry.second = Lex.getLoc();
2058     }
2059     Result = Entry.first;
2060     Lex.Lex();
2061     break;
2062   }
2063   }
2064 
2065   // Parse the type suffixes.
2066   while (true) {
2067     switch (Lex.getKind()) {
2068     // End of type.
2069     default:
2070       if (!AllowVoid && Result->isVoidTy())
2071         return Error(TypeLoc, "void type only allowed for function results");
2072       return false;
2073 
2074     // Type ::= Type '*'
2075     case lltok::star:
2076       if (Result->isLabelTy())
2077         return TokError("basic block pointers are invalid");
2078       if (Result->isVoidTy())
2079         return TokError("pointers to void are invalid - use i8* instead");
2080       if (!PointerType::isValidElementType(Result))
2081         return TokError("pointer to this type is invalid");
2082       Result = PointerType::getUnqual(Result);
2083       Lex.Lex();
2084       break;
2085 
2086     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2087     case lltok::kw_addrspace: {
2088       if (Result->isLabelTy())
2089         return TokError("basic block pointers are invalid");
2090       if (Result->isVoidTy())
2091         return TokError("pointers to void are invalid; use i8* instead");
2092       if (!PointerType::isValidElementType(Result))
2093         return TokError("pointer to this type is invalid");
2094       unsigned AddrSpace;
2095       if (ParseOptionalAddrSpace(AddrSpace) ||
2096           ParseToken(lltok::star, "expected '*' in address space"))
2097         return true;
2098 
2099       Result = PointerType::get(Result, AddrSpace);
2100       break;
2101     }
2102 
2103     /// Types '(' ArgTypeListI ')' OptFuncAttrs
2104     case lltok::lparen:
2105       if (ParseFunctionType(Result))
2106         return true;
2107       break;
2108     }
2109   }
2110 }
2111 
2112 /// ParseParameterList
2113 ///    ::= '(' ')'
2114 ///    ::= '(' Arg (',' Arg)* ')'
2115 ///  Arg
2116 ///    ::= Type OptionalAttributes Value OptionalAttributes
2117 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2118                                   PerFunctionState &PFS, bool IsMustTailCall,
2119                                   bool InVarArgsFunc) {
2120   if (ParseToken(lltok::lparen, "expected '(' in call"))
2121     return true;
2122 
2123   while (Lex.getKind() != lltok::rparen) {
2124     // If this isn't the first argument, we need a comma.
2125     if (!ArgList.empty() &&
2126         ParseToken(lltok::comma, "expected ',' in argument list"))
2127       return true;
2128 
2129     // Parse an ellipsis if this is a musttail call in a variadic function.
2130     if (Lex.getKind() == lltok::dotdotdot) {
2131       const char *Msg = "unexpected ellipsis in argument list for ";
2132       if (!IsMustTailCall)
2133         return TokError(Twine(Msg) + "non-musttail call");
2134       if (!InVarArgsFunc)
2135         return TokError(Twine(Msg) + "musttail call in non-varargs function");
2136       Lex.Lex();  // Lex the '...', it is purely for readability.
2137       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2138     }
2139 
2140     // Parse the argument.
2141     LocTy ArgLoc;
2142     Type *ArgTy = nullptr;
2143     AttrBuilder ArgAttrs;
2144     Value *V;
2145     if (ParseType(ArgTy, ArgLoc))
2146       return true;
2147 
2148     if (ArgTy->isMetadataTy()) {
2149       if (ParseMetadataAsValue(V, PFS))
2150         return true;
2151     } else {
2152       // Otherwise, handle normal operands.
2153       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2154         return true;
2155     }
2156     ArgList.push_back(ParamInfo(
2157         ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2158   }
2159 
2160   if (IsMustTailCall && InVarArgsFunc)
2161     return TokError("expected '...' at end of argument list for musttail call "
2162                     "in varargs function");
2163 
2164   Lex.Lex();  // Lex the ')'.
2165   return false;
2166 }
2167 
2168 /// ParseOptionalOperandBundles
2169 ///    ::= /*empty*/
2170 ///    ::= '[' OperandBundle [, OperandBundle ]* ']'
2171 ///
2172 /// OperandBundle
2173 ///    ::= bundle-tag '(' ')'
2174 ///    ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2175 ///
2176 /// bundle-tag ::= String Constant
2177 bool LLParser::ParseOptionalOperandBundles(
2178     SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2179   LocTy BeginLoc = Lex.getLoc();
2180   if (!EatIfPresent(lltok::lsquare))
2181     return false;
2182 
2183   while (Lex.getKind() != lltok::rsquare) {
2184     // If this isn't the first operand bundle, we need a comma.
2185     if (!BundleList.empty() &&
2186         ParseToken(lltok::comma, "expected ',' in input list"))
2187       return true;
2188 
2189     std::string Tag;
2190     if (ParseStringConstant(Tag))
2191       return true;
2192 
2193     if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2194       return true;
2195 
2196     std::vector<Value *> Inputs;
2197     while (Lex.getKind() != lltok::rparen) {
2198       // If this isn't the first input, we need a comma.
2199       if (!Inputs.empty() &&
2200           ParseToken(lltok::comma, "expected ',' in input list"))
2201         return true;
2202 
2203       Type *Ty = nullptr;
2204       Value *Input = nullptr;
2205       if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2206         return true;
2207       Inputs.push_back(Input);
2208     }
2209 
2210     BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2211 
2212     Lex.Lex(); // Lex the ')'.
2213   }
2214 
2215   if (BundleList.empty())
2216     return Error(BeginLoc, "operand bundle set must not be empty");
2217 
2218   Lex.Lex(); // Lex the ']'.
2219   return false;
2220 }
2221 
2222 /// ParseArgumentList - Parse the argument list for a function type or function
2223 /// prototype.
2224 ///   ::= '(' ArgTypeListI ')'
2225 /// ArgTypeListI
2226 ///   ::= /*empty*/
2227 ///   ::= '...'
2228 ///   ::= ArgTypeList ',' '...'
2229 ///   ::= ArgType (',' ArgType)*
2230 ///
2231 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2232                                  bool &isVarArg){
2233   isVarArg = false;
2234   assert(Lex.getKind() == lltok::lparen);
2235   Lex.Lex(); // eat the (.
2236 
2237   if (Lex.getKind() == lltok::rparen) {
2238     // empty
2239   } else if (Lex.getKind() == lltok::dotdotdot) {
2240     isVarArg = true;
2241     Lex.Lex();
2242   } else {
2243     LocTy TypeLoc = Lex.getLoc();
2244     Type *ArgTy = nullptr;
2245     AttrBuilder Attrs;
2246     std::string Name;
2247 
2248     if (ParseType(ArgTy) ||
2249         ParseOptionalParamAttrs(Attrs)) return true;
2250 
2251     if (ArgTy->isVoidTy())
2252       return Error(TypeLoc, "argument can not have void type");
2253 
2254     if (Lex.getKind() == lltok::LocalVar) {
2255       Name = Lex.getStrVal();
2256       Lex.Lex();
2257     }
2258 
2259     if (!FunctionType::isValidArgumentType(ArgTy))
2260       return Error(TypeLoc, "invalid type for function argument");
2261 
2262     ArgList.emplace_back(TypeLoc, ArgTy,
2263                          AttributeSet::get(ArgTy->getContext(), Attrs),
2264                          std::move(Name));
2265 
2266     while (EatIfPresent(lltok::comma)) {
2267       // Handle ... at end of arg list.
2268       if (EatIfPresent(lltok::dotdotdot)) {
2269         isVarArg = true;
2270         break;
2271       }
2272 
2273       // Otherwise must be an argument type.
2274       TypeLoc = Lex.getLoc();
2275       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2276 
2277       if (ArgTy->isVoidTy())
2278         return Error(TypeLoc, "argument can not have void type");
2279 
2280       if (Lex.getKind() == lltok::LocalVar) {
2281         Name = Lex.getStrVal();
2282         Lex.Lex();
2283       } else {
2284         Name = "";
2285       }
2286 
2287       if (!ArgTy->isFirstClassType())
2288         return Error(TypeLoc, "invalid type for function argument");
2289 
2290       ArgList.emplace_back(TypeLoc, ArgTy,
2291                            AttributeSet::get(ArgTy->getContext(), Attrs),
2292                            std::move(Name));
2293     }
2294   }
2295 
2296   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2297 }
2298 
2299 /// ParseFunctionType
2300 ///  ::= Type ArgumentList OptionalAttrs
2301 bool LLParser::ParseFunctionType(Type *&Result) {
2302   assert(Lex.getKind() == lltok::lparen);
2303 
2304   if (!FunctionType::isValidReturnType(Result))
2305     return TokError("invalid function return type");
2306 
2307   SmallVector<ArgInfo, 8> ArgList;
2308   bool isVarArg;
2309   if (ParseArgumentList(ArgList, isVarArg))
2310     return true;
2311 
2312   // Reject names on the arguments lists.
2313   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2314     if (!ArgList[i].Name.empty())
2315       return Error(ArgList[i].Loc, "argument name invalid in function type");
2316     if (ArgList[i].Attrs.hasAttributes())
2317       return Error(ArgList[i].Loc,
2318                    "argument attributes invalid in function type");
2319   }
2320 
2321   SmallVector<Type*, 16> ArgListTy;
2322   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2323     ArgListTy.push_back(ArgList[i].Ty);
2324 
2325   Result = FunctionType::get(Result, ArgListTy, isVarArg);
2326   return false;
2327 }
2328 
2329 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2330 /// other structs.
2331 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2332   SmallVector<Type*, 8> Elts;
2333   if (ParseStructBody(Elts)) return true;
2334 
2335   Result = StructType::get(Context, Elts, Packed);
2336   return false;
2337 }
2338 
2339 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2340 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2341                                      std::pair<Type*, LocTy> &Entry,
2342                                      Type *&ResultTy) {
2343   // If the type was already defined, diagnose the redefinition.
2344   if (Entry.first && !Entry.second.isValid())
2345     return Error(TypeLoc, "redefinition of type");
2346 
2347   // If we have opaque, just return without filling in the definition for the
2348   // struct.  This counts as a definition as far as the .ll file goes.
2349   if (EatIfPresent(lltok::kw_opaque)) {
2350     // This type is being defined, so clear the location to indicate this.
2351     Entry.second = SMLoc();
2352 
2353     // If this type number has never been uttered, create it.
2354     if (!Entry.first)
2355       Entry.first = StructType::create(Context, Name);
2356     ResultTy = Entry.first;
2357     return false;
2358   }
2359 
2360   // If the type starts with '<', then it is either a packed struct or a vector.
2361   bool isPacked = EatIfPresent(lltok::less);
2362 
2363   // If we don't have a struct, then we have a random type alias, which we
2364   // accept for compatibility with old files.  These types are not allowed to be
2365   // forward referenced and not allowed to be recursive.
2366   if (Lex.getKind() != lltok::lbrace) {
2367     if (Entry.first)
2368       return Error(TypeLoc, "forward references to non-struct type");
2369 
2370     ResultTy = nullptr;
2371     if (isPacked)
2372       return ParseArrayVectorType(ResultTy, true);
2373     return ParseType(ResultTy);
2374   }
2375 
2376   // This type is being defined, so clear the location to indicate this.
2377   Entry.second = SMLoc();
2378 
2379   // If this type number has never been uttered, create it.
2380   if (!Entry.first)
2381     Entry.first = StructType::create(Context, Name);
2382 
2383   StructType *STy = cast<StructType>(Entry.first);
2384 
2385   SmallVector<Type*, 8> Body;
2386   if (ParseStructBody(Body) ||
2387       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2388     return true;
2389 
2390   STy->setBody(Body, isPacked);
2391   ResultTy = STy;
2392   return false;
2393 }
2394 
2395 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2396 ///   StructType
2397 ///     ::= '{' '}'
2398 ///     ::= '{' Type (',' Type)* '}'
2399 ///     ::= '<' '{' '}' '>'
2400 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2401 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2402   assert(Lex.getKind() == lltok::lbrace);
2403   Lex.Lex(); // Consume the '{'
2404 
2405   // Handle the empty struct.
2406   if (EatIfPresent(lltok::rbrace))
2407     return false;
2408 
2409   LocTy EltTyLoc = Lex.getLoc();
2410   Type *Ty = nullptr;
2411   if (ParseType(Ty)) return true;
2412   Body.push_back(Ty);
2413 
2414   if (!StructType::isValidElementType(Ty))
2415     return Error(EltTyLoc, "invalid element type for struct");
2416 
2417   while (EatIfPresent(lltok::comma)) {
2418     EltTyLoc = Lex.getLoc();
2419     if (ParseType(Ty)) return true;
2420 
2421     if (!StructType::isValidElementType(Ty))
2422       return Error(EltTyLoc, "invalid element type for struct");
2423 
2424     Body.push_back(Ty);
2425   }
2426 
2427   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2428 }
2429 
2430 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2431 /// token has already been consumed.
2432 ///   Type
2433 ///     ::= '[' APSINTVAL 'x' Types ']'
2434 ///     ::= '<' APSINTVAL 'x' Types '>'
2435 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2436   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2437       Lex.getAPSIntVal().getBitWidth() > 64)
2438     return TokError("expected number in address space");
2439 
2440   LocTy SizeLoc = Lex.getLoc();
2441   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2442   Lex.Lex();
2443 
2444   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2445       return true;
2446 
2447   LocTy TypeLoc = Lex.getLoc();
2448   Type *EltTy = nullptr;
2449   if (ParseType(EltTy)) return true;
2450 
2451   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2452                  "expected end of sequential type"))
2453     return true;
2454 
2455   if (isVector) {
2456     if (Size == 0)
2457       return Error(SizeLoc, "zero element vector is illegal");
2458     if ((unsigned)Size != Size)
2459       return Error(SizeLoc, "size too large for vector");
2460     if (!VectorType::isValidElementType(EltTy))
2461       return Error(TypeLoc, "invalid vector element type");
2462     Result = VectorType::get(EltTy, unsigned(Size));
2463   } else {
2464     if (!ArrayType::isValidElementType(EltTy))
2465       return Error(TypeLoc, "invalid array element type");
2466     Result = ArrayType::get(EltTy, Size);
2467   }
2468   return false;
2469 }
2470 
2471 //===----------------------------------------------------------------------===//
2472 // Function Semantic Analysis.
2473 //===----------------------------------------------------------------------===//
2474 
2475 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2476                                              int functionNumber)
2477   : P(p), F(f), FunctionNumber(functionNumber) {
2478 
2479   // Insert unnamed arguments into the NumberedVals list.
2480   for (Argument &A : F.args())
2481     if (!A.hasName())
2482       NumberedVals.push_back(&A);
2483 }
2484 
2485 LLParser::PerFunctionState::~PerFunctionState() {
2486   // If there were any forward referenced non-basicblock values, delete them.
2487 
2488   for (const auto &P : ForwardRefVals) {
2489     if (isa<BasicBlock>(P.second.first))
2490       continue;
2491     P.second.first->replaceAllUsesWith(
2492         UndefValue::get(P.second.first->getType()));
2493     delete P.second.first;
2494   }
2495 
2496   for (const auto &P : ForwardRefValIDs) {
2497     if (isa<BasicBlock>(P.second.first))
2498       continue;
2499     P.second.first->replaceAllUsesWith(
2500         UndefValue::get(P.second.first->getType()));
2501     delete P.second.first;
2502   }
2503 }
2504 
2505 bool LLParser::PerFunctionState::FinishFunction() {
2506   if (!ForwardRefVals.empty())
2507     return P.Error(ForwardRefVals.begin()->second.second,
2508                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2509                    "'");
2510   if (!ForwardRefValIDs.empty())
2511     return P.Error(ForwardRefValIDs.begin()->second.second,
2512                    "use of undefined value '%" +
2513                    Twine(ForwardRefValIDs.begin()->first) + "'");
2514   return false;
2515 }
2516 
2517 /// GetVal - Get a value with the specified name or ID, creating a
2518 /// forward reference record if needed.  This can return null if the value
2519 /// exists but does not have the right type.
2520 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2521                                           LocTy Loc) {
2522   // Look this name up in the normal function symbol table.
2523   Value *Val = F.getValueSymbolTable()->lookup(Name);
2524 
2525   // If this is a forward reference for the value, see if we already created a
2526   // forward ref record.
2527   if (!Val) {
2528     auto I = ForwardRefVals.find(Name);
2529     if (I != ForwardRefVals.end())
2530       Val = I->second.first;
2531   }
2532 
2533   // If we have the value in the symbol table or fwd-ref table, return it.
2534   if (Val) {
2535     if (Val->getType() == Ty) return Val;
2536     if (Ty->isLabelTy())
2537       P.Error(Loc, "'%" + Name + "' is not a basic block");
2538     else
2539       P.Error(Loc, "'%" + Name + "' defined with type '" +
2540               getTypeString(Val->getType()) + "'");
2541     return nullptr;
2542   }
2543 
2544   // Don't make placeholders with invalid type.
2545   if (!Ty->isFirstClassType()) {
2546     P.Error(Loc, "invalid use of a non-first-class type");
2547     return nullptr;
2548   }
2549 
2550   // Otherwise, create a new forward reference for this value and remember it.
2551   Value *FwdVal;
2552   if (Ty->isLabelTy()) {
2553     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2554   } else {
2555     FwdVal = new Argument(Ty, Name);
2556   }
2557 
2558   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2559   return FwdVal;
2560 }
2561 
2562 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2563   // Look this name up in the normal function symbol table.
2564   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2565 
2566   // If this is a forward reference for the value, see if we already created a
2567   // forward ref record.
2568   if (!Val) {
2569     auto I = ForwardRefValIDs.find(ID);
2570     if (I != ForwardRefValIDs.end())
2571       Val = I->second.first;
2572   }
2573 
2574   // If we have the value in the symbol table or fwd-ref table, return it.
2575   if (Val) {
2576     if (Val->getType() == Ty) return Val;
2577     if (Ty->isLabelTy())
2578       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2579     else
2580       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2581               getTypeString(Val->getType()) + "'");
2582     return nullptr;
2583   }
2584 
2585   if (!Ty->isFirstClassType()) {
2586     P.Error(Loc, "invalid use of a non-first-class type");
2587     return nullptr;
2588   }
2589 
2590   // Otherwise, create a new forward reference for this value and remember it.
2591   Value *FwdVal;
2592   if (Ty->isLabelTy()) {
2593     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2594   } else {
2595     FwdVal = new Argument(Ty);
2596   }
2597 
2598   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2599   return FwdVal;
2600 }
2601 
2602 /// SetInstName - After an instruction is parsed and inserted into its
2603 /// basic block, this installs its name.
2604 bool LLParser::PerFunctionState::SetInstName(int NameID,
2605                                              const std::string &NameStr,
2606                                              LocTy NameLoc, Instruction *Inst) {
2607   // If this instruction has void type, it cannot have a name or ID specified.
2608   if (Inst->getType()->isVoidTy()) {
2609     if (NameID != -1 || !NameStr.empty())
2610       return P.Error(NameLoc, "instructions returning void cannot have a name");
2611     return false;
2612   }
2613 
2614   // If this was a numbered instruction, verify that the instruction is the
2615   // expected value and resolve any forward references.
2616   if (NameStr.empty()) {
2617     // If neither a name nor an ID was specified, just use the next ID.
2618     if (NameID == -1)
2619       NameID = NumberedVals.size();
2620 
2621     if (unsigned(NameID) != NumberedVals.size())
2622       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2623                      Twine(NumberedVals.size()) + "'");
2624 
2625     auto FI = ForwardRefValIDs.find(NameID);
2626     if (FI != ForwardRefValIDs.end()) {
2627       Value *Sentinel = FI->second.first;
2628       if (Sentinel->getType() != Inst->getType())
2629         return P.Error(NameLoc, "instruction forward referenced with type '" +
2630                        getTypeString(FI->second.first->getType()) + "'");
2631 
2632       Sentinel->replaceAllUsesWith(Inst);
2633       delete Sentinel;
2634       ForwardRefValIDs.erase(FI);
2635     }
2636 
2637     NumberedVals.push_back(Inst);
2638     return false;
2639   }
2640 
2641   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2642   auto FI = ForwardRefVals.find(NameStr);
2643   if (FI != ForwardRefVals.end()) {
2644     Value *Sentinel = FI->second.first;
2645     if (Sentinel->getType() != Inst->getType())
2646       return P.Error(NameLoc, "instruction forward referenced with type '" +
2647                      getTypeString(FI->second.first->getType()) + "'");
2648 
2649     Sentinel->replaceAllUsesWith(Inst);
2650     delete Sentinel;
2651     ForwardRefVals.erase(FI);
2652   }
2653 
2654   // Set the name on the instruction.
2655   Inst->setName(NameStr);
2656 
2657   if (Inst->getName() != NameStr)
2658     return P.Error(NameLoc, "multiple definition of local value named '" +
2659                    NameStr + "'");
2660   return false;
2661 }
2662 
2663 /// GetBB - Get a basic block with the specified name or ID, creating a
2664 /// forward reference record if needed.
2665 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2666                                               LocTy Loc) {
2667   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2668                                       Type::getLabelTy(F.getContext()), Loc));
2669 }
2670 
2671 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2672   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2673                                       Type::getLabelTy(F.getContext()), Loc));
2674 }
2675 
2676 /// DefineBB - Define the specified basic block, which is either named or
2677 /// unnamed.  If there is an error, this returns null otherwise it returns
2678 /// the block being defined.
2679 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2680                                                  LocTy Loc) {
2681   BasicBlock *BB;
2682   if (Name.empty())
2683     BB = GetBB(NumberedVals.size(), Loc);
2684   else
2685     BB = GetBB(Name, Loc);
2686   if (!BB) return nullptr; // Already diagnosed error.
2687 
2688   // Move the block to the end of the function.  Forward ref'd blocks are
2689   // inserted wherever they happen to be referenced.
2690   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2691 
2692   // Remove the block from forward ref sets.
2693   if (Name.empty()) {
2694     ForwardRefValIDs.erase(NumberedVals.size());
2695     NumberedVals.push_back(BB);
2696   } else {
2697     // BB forward references are already in the function symbol table.
2698     ForwardRefVals.erase(Name);
2699   }
2700 
2701   return BB;
2702 }
2703 
2704 //===----------------------------------------------------------------------===//
2705 // Constants.
2706 //===----------------------------------------------------------------------===//
2707 
2708 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2709 /// type implied.  For example, if we parse "4" we don't know what integer type
2710 /// it has.  The value will later be combined with its type and checked for
2711 /// sanity.  PFS is used to convert function-local operands of metadata (since
2712 /// metadata operands are not just parsed here but also converted to values).
2713 /// PFS can be null when we are not parsing metadata values inside a function.
2714 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2715   ID.Loc = Lex.getLoc();
2716   switch (Lex.getKind()) {
2717   default: return TokError("expected value token");
2718   case lltok::GlobalID:  // @42
2719     ID.UIntVal = Lex.getUIntVal();
2720     ID.Kind = ValID::t_GlobalID;
2721     break;
2722   case lltok::GlobalVar:  // @foo
2723     ID.StrVal = Lex.getStrVal();
2724     ID.Kind = ValID::t_GlobalName;
2725     break;
2726   case lltok::LocalVarID:  // %42
2727     ID.UIntVal = Lex.getUIntVal();
2728     ID.Kind = ValID::t_LocalID;
2729     break;
2730   case lltok::LocalVar:  // %foo
2731     ID.StrVal = Lex.getStrVal();
2732     ID.Kind = ValID::t_LocalName;
2733     break;
2734   case lltok::APSInt:
2735     ID.APSIntVal = Lex.getAPSIntVal();
2736     ID.Kind = ValID::t_APSInt;
2737     break;
2738   case lltok::APFloat:
2739     ID.APFloatVal = Lex.getAPFloatVal();
2740     ID.Kind = ValID::t_APFloat;
2741     break;
2742   case lltok::kw_true:
2743     ID.ConstantVal = ConstantInt::getTrue(Context);
2744     ID.Kind = ValID::t_Constant;
2745     break;
2746   case lltok::kw_false:
2747     ID.ConstantVal = ConstantInt::getFalse(Context);
2748     ID.Kind = ValID::t_Constant;
2749     break;
2750   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2751   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2752   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2753   case lltok::kw_none: ID.Kind = ValID::t_None; break;
2754 
2755   case lltok::lbrace: {
2756     // ValID ::= '{' ConstVector '}'
2757     Lex.Lex();
2758     SmallVector<Constant*, 16> Elts;
2759     if (ParseGlobalValueVector(Elts) ||
2760         ParseToken(lltok::rbrace, "expected end of struct constant"))
2761       return true;
2762 
2763     ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2764     ID.UIntVal = Elts.size();
2765     memcpy(ID.ConstantStructElts.get(), Elts.data(),
2766            Elts.size() * sizeof(Elts[0]));
2767     ID.Kind = ValID::t_ConstantStruct;
2768     return false;
2769   }
2770   case lltok::less: {
2771     // ValID ::= '<' ConstVector '>'         --> Vector.
2772     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2773     Lex.Lex();
2774     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2775 
2776     SmallVector<Constant*, 16> Elts;
2777     LocTy FirstEltLoc = Lex.getLoc();
2778     if (ParseGlobalValueVector(Elts) ||
2779         (isPackedStruct &&
2780          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2781         ParseToken(lltok::greater, "expected end of constant"))
2782       return true;
2783 
2784     if (isPackedStruct) {
2785       ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2786       memcpy(ID.ConstantStructElts.get(), Elts.data(),
2787              Elts.size() * sizeof(Elts[0]));
2788       ID.UIntVal = Elts.size();
2789       ID.Kind = ValID::t_PackedConstantStruct;
2790       return false;
2791     }
2792 
2793     if (Elts.empty())
2794       return Error(ID.Loc, "constant vector must not be empty");
2795 
2796     if (!Elts[0]->getType()->isIntegerTy() &&
2797         !Elts[0]->getType()->isFloatingPointTy() &&
2798         !Elts[0]->getType()->isPointerTy())
2799       return Error(FirstEltLoc,
2800             "vector elements must have integer, pointer or floating point type");
2801 
2802     // Verify that all the vector elements have the same type.
2803     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2804       if (Elts[i]->getType() != Elts[0]->getType())
2805         return Error(FirstEltLoc,
2806                      "vector element #" + Twine(i) +
2807                     " is not of type '" + getTypeString(Elts[0]->getType()));
2808 
2809     ID.ConstantVal = ConstantVector::get(Elts);
2810     ID.Kind = ValID::t_Constant;
2811     return false;
2812   }
2813   case lltok::lsquare: {   // Array Constant
2814     Lex.Lex();
2815     SmallVector<Constant*, 16> Elts;
2816     LocTy FirstEltLoc = Lex.getLoc();
2817     if (ParseGlobalValueVector(Elts) ||
2818         ParseToken(lltok::rsquare, "expected end of array constant"))
2819       return true;
2820 
2821     // Handle empty element.
2822     if (Elts.empty()) {
2823       // Use undef instead of an array because it's inconvenient to determine
2824       // the element type at this point, there being no elements to examine.
2825       ID.Kind = ValID::t_EmptyArray;
2826       return false;
2827     }
2828 
2829     if (!Elts[0]->getType()->isFirstClassType())
2830       return Error(FirstEltLoc, "invalid array element type: " +
2831                    getTypeString(Elts[0]->getType()));
2832 
2833     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2834 
2835     // Verify all elements are correct type!
2836     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2837       if (Elts[i]->getType() != Elts[0]->getType())
2838         return Error(FirstEltLoc,
2839                      "array element #" + Twine(i) +
2840                      " is not of type '" + getTypeString(Elts[0]->getType()));
2841     }
2842 
2843     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2844     ID.Kind = ValID::t_Constant;
2845     return false;
2846   }
2847   case lltok::kw_c:  // c "foo"
2848     Lex.Lex();
2849     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2850                                                   false);
2851     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2852     ID.Kind = ValID::t_Constant;
2853     return false;
2854 
2855   case lltok::kw_asm: {
2856     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2857     //             STRINGCONSTANT
2858     bool HasSideEffect, AlignStack, AsmDialect;
2859     Lex.Lex();
2860     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2861         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2862         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2863         ParseStringConstant(ID.StrVal) ||
2864         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2865         ParseToken(lltok::StringConstant, "expected constraint string"))
2866       return true;
2867     ID.StrVal2 = Lex.getStrVal();
2868     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2869       (unsigned(AsmDialect)<<2);
2870     ID.Kind = ValID::t_InlineAsm;
2871     return false;
2872   }
2873 
2874   case lltok::kw_blockaddress: {
2875     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2876     Lex.Lex();
2877 
2878     ValID Fn, Label;
2879 
2880     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2881         ParseValID(Fn) ||
2882         ParseToken(lltok::comma, "expected comma in block address expression")||
2883         ParseValID(Label) ||
2884         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2885       return true;
2886 
2887     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2888       return Error(Fn.Loc, "expected function name in blockaddress");
2889     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2890       return Error(Label.Loc, "expected basic block name in blockaddress");
2891 
2892     // Try to find the function (but skip it if it's forward-referenced).
2893     GlobalValue *GV = nullptr;
2894     if (Fn.Kind == ValID::t_GlobalID) {
2895       if (Fn.UIntVal < NumberedVals.size())
2896         GV = NumberedVals[Fn.UIntVal];
2897     } else if (!ForwardRefVals.count(Fn.StrVal)) {
2898       GV = M->getNamedValue(Fn.StrVal);
2899     }
2900     Function *F = nullptr;
2901     if (GV) {
2902       // Confirm that it's actually a function with a definition.
2903       if (!isa<Function>(GV))
2904         return Error(Fn.Loc, "expected function name in blockaddress");
2905       F = cast<Function>(GV);
2906       if (F->isDeclaration())
2907         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2908     }
2909 
2910     if (!F) {
2911       // Make a global variable as a placeholder for this reference.
2912       GlobalValue *&FwdRef =
2913           ForwardRefBlockAddresses.insert(std::make_pair(
2914                                               std::move(Fn),
2915                                               std::map<ValID, GlobalValue *>()))
2916               .first->second.insert(std::make_pair(std::move(Label), nullptr))
2917               .first->second;
2918       if (!FwdRef)
2919         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2920                                     GlobalValue::InternalLinkage, nullptr, "");
2921       ID.ConstantVal = FwdRef;
2922       ID.Kind = ValID::t_Constant;
2923       return false;
2924     }
2925 
2926     // We found the function; now find the basic block.  Don't use PFS, since we
2927     // might be inside a constant expression.
2928     BasicBlock *BB;
2929     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2930       if (Label.Kind == ValID::t_LocalID)
2931         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2932       else
2933         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2934       if (!BB)
2935         return Error(Label.Loc, "referenced value is not a basic block");
2936     } else {
2937       if (Label.Kind == ValID::t_LocalID)
2938         return Error(Label.Loc, "cannot take address of numeric label after "
2939                                 "the function is defined");
2940       BB = dyn_cast_or_null<BasicBlock>(
2941           F->getValueSymbolTable()->lookup(Label.StrVal));
2942       if (!BB)
2943         return Error(Label.Loc, "referenced value is not a basic block");
2944     }
2945 
2946     ID.ConstantVal = BlockAddress::get(F, BB);
2947     ID.Kind = ValID::t_Constant;
2948     return false;
2949   }
2950 
2951   case lltok::kw_trunc:
2952   case lltok::kw_zext:
2953   case lltok::kw_sext:
2954   case lltok::kw_fptrunc:
2955   case lltok::kw_fpext:
2956   case lltok::kw_bitcast:
2957   case lltok::kw_addrspacecast:
2958   case lltok::kw_uitofp:
2959   case lltok::kw_sitofp:
2960   case lltok::kw_fptoui:
2961   case lltok::kw_fptosi:
2962   case lltok::kw_inttoptr:
2963   case lltok::kw_ptrtoint: {
2964     unsigned Opc = Lex.getUIntVal();
2965     Type *DestTy = nullptr;
2966     Constant *SrcVal;
2967     Lex.Lex();
2968     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2969         ParseGlobalTypeAndValue(SrcVal) ||
2970         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2971         ParseType(DestTy) ||
2972         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2973       return true;
2974     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2975       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2976                    getTypeString(SrcVal->getType()) + "' to '" +
2977                    getTypeString(DestTy) + "'");
2978     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2979                                                  SrcVal, DestTy);
2980     ID.Kind = ValID::t_Constant;
2981     return false;
2982   }
2983   case lltok::kw_extractvalue: {
2984     Lex.Lex();
2985     Constant *Val;
2986     SmallVector<unsigned, 4> Indices;
2987     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2988         ParseGlobalTypeAndValue(Val) ||
2989         ParseIndexList(Indices) ||
2990         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2991       return true;
2992 
2993     if (!Val->getType()->isAggregateType())
2994       return Error(ID.Loc, "extractvalue operand must be aggregate type");
2995     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2996       return Error(ID.Loc, "invalid indices for extractvalue");
2997     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2998     ID.Kind = ValID::t_Constant;
2999     return false;
3000   }
3001   case lltok::kw_insertvalue: {
3002     Lex.Lex();
3003     Constant *Val0, *Val1;
3004     SmallVector<unsigned, 4> Indices;
3005     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3006         ParseGlobalTypeAndValue(Val0) ||
3007         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3008         ParseGlobalTypeAndValue(Val1) ||
3009         ParseIndexList(Indices) ||
3010         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3011       return true;
3012     if (!Val0->getType()->isAggregateType())
3013       return Error(ID.Loc, "insertvalue operand must be aggregate type");
3014     Type *IndexedType =
3015         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3016     if (!IndexedType)
3017       return Error(ID.Loc, "invalid indices for insertvalue");
3018     if (IndexedType != Val1->getType())
3019       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3020                                getTypeString(Val1->getType()) +
3021                                "' instead of '" + getTypeString(IndexedType) +
3022                                "'");
3023     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3024     ID.Kind = ValID::t_Constant;
3025     return false;
3026   }
3027   case lltok::kw_icmp:
3028   case lltok::kw_fcmp: {
3029     unsigned PredVal, Opc = Lex.getUIntVal();
3030     Constant *Val0, *Val1;
3031     Lex.Lex();
3032     if (ParseCmpPredicate(PredVal, Opc) ||
3033         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3034         ParseGlobalTypeAndValue(Val0) ||
3035         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3036         ParseGlobalTypeAndValue(Val1) ||
3037         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3038       return true;
3039 
3040     if (Val0->getType() != Val1->getType())
3041       return Error(ID.Loc, "compare operands must have the same type");
3042 
3043     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3044 
3045     if (Opc == Instruction::FCmp) {
3046       if (!Val0->getType()->isFPOrFPVectorTy())
3047         return Error(ID.Loc, "fcmp requires floating point operands");
3048       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3049     } else {
3050       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3051       if (!Val0->getType()->isIntOrIntVectorTy() &&
3052           !Val0->getType()->getScalarType()->isPointerTy())
3053         return Error(ID.Loc, "icmp requires pointer or integer operands");
3054       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3055     }
3056     ID.Kind = ValID::t_Constant;
3057     return false;
3058   }
3059 
3060   // Binary Operators.
3061   case lltok::kw_add:
3062   case lltok::kw_fadd:
3063   case lltok::kw_sub:
3064   case lltok::kw_fsub:
3065   case lltok::kw_mul:
3066   case lltok::kw_fmul:
3067   case lltok::kw_udiv:
3068   case lltok::kw_sdiv:
3069   case lltok::kw_fdiv:
3070   case lltok::kw_urem:
3071   case lltok::kw_srem:
3072   case lltok::kw_frem:
3073   case lltok::kw_shl:
3074   case lltok::kw_lshr:
3075   case lltok::kw_ashr: {
3076     bool NUW = false;
3077     bool NSW = false;
3078     bool Exact = false;
3079     unsigned Opc = Lex.getUIntVal();
3080     Constant *Val0, *Val1;
3081     Lex.Lex();
3082     LocTy ModifierLoc = Lex.getLoc();
3083     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3084         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3085       if (EatIfPresent(lltok::kw_nuw))
3086         NUW = true;
3087       if (EatIfPresent(lltok::kw_nsw)) {
3088         NSW = true;
3089         if (EatIfPresent(lltok::kw_nuw))
3090           NUW = true;
3091       }
3092     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3093                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3094       if (EatIfPresent(lltok::kw_exact))
3095         Exact = true;
3096     }
3097     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3098         ParseGlobalTypeAndValue(Val0) ||
3099         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3100         ParseGlobalTypeAndValue(Val1) ||
3101         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3102       return true;
3103     if (Val0->getType() != Val1->getType())
3104       return Error(ID.Loc, "operands of constexpr must have same type");
3105     if (!Val0->getType()->isIntOrIntVectorTy()) {
3106       if (NUW)
3107         return Error(ModifierLoc, "nuw only applies to integer operations");
3108       if (NSW)
3109         return Error(ModifierLoc, "nsw only applies to integer operations");
3110     }
3111     // Check that the type is valid for the operator.
3112     switch (Opc) {
3113     case Instruction::Add:
3114     case Instruction::Sub:
3115     case Instruction::Mul:
3116     case Instruction::UDiv:
3117     case Instruction::SDiv:
3118     case Instruction::URem:
3119     case Instruction::SRem:
3120     case Instruction::Shl:
3121     case Instruction::AShr:
3122     case Instruction::LShr:
3123       if (!Val0->getType()->isIntOrIntVectorTy())
3124         return Error(ID.Loc, "constexpr requires integer operands");
3125       break;
3126     case Instruction::FAdd:
3127     case Instruction::FSub:
3128     case Instruction::FMul:
3129     case Instruction::FDiv:
3130     case Instruction::FRem:
3131       if (!Val0->getType()->isFPOrFPVectorTy())
3132         return Error(ID.Loc, "constexpr requires fp operands");
3133       break;
3134     default: llvm_unreachable("Unknown binary operator!");
3135     }
3136     unsigned Flags = 0;
3137     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3138     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3139     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3140     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3141     ID.ConstantVal = C;
3142     ID.Kind = ValID::t_Constant;
3143     return false;
3144   }
3145 
3146   // Logical Operations
3147   case lltok::kw_and:
3148   case lltok::kw_or:
3149   case lltok::kw_xor: {
3150     unsigned Opc = Lex.getUIntVal();
3151     Constant *Val0, *Val1;
3152     Lex.Lex();
3153     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3154         ParseGlobalTypeAndValue(Val0) ||
3155         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3156         ParseGlobalTypeAndValue(Val1) ||
3157         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3158       return true;
3159     if (Val0->getType() != Val1->getType())
3160       return Error(ID.Loc, "operands of constexpr must have same type");
3161     if (!Val0->getType()->isIntOrIntVectorTy())
3162       return Error(ID.Loc,
3163                    "constexpr requires integer or integer vector operands");
3164     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3165     ID.Kind = ValID::t_Constant;
3166     return false;
3167   }
3168 
3169   case lltok::kw_getelementptr:
3170   case lltok::kw_shufflevector:
3171   case lltok::kw_insertelement:
3172   case lltok::kw_extractelement:
3173   case lltok::kw_select: {
3174     unsigned Opc = Lex.getUIntVal();
3175     SmallVector<Constant*, 16> Elts;
3176     bool InBounds = false;
3177     Type *Ty;
3178     Lex.Lex();
3179 
3180     if (Opc == Instruction::GetElementPtr)
3181       InBounds = EatIfPresent(lltok::kw_inbounds);
3182 
3183     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3184       return true;
3185 
3186     LocTy ExplicitTypeLoc = Lex.getLoc();
3187     if (Opc == Instruction::GetElementPtr) {
3188       if (ParseType(Ty) ||
3189           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3190         return true;
3191     }
3192 
3193     Optional<unsigned> InRangeOp;
3194     if (ParseGlobalValueVector(
3195             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3196         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3197       return true;
3198 
3199     if (Opc == Instruction::GetElementPtr) {
3200       if (Elts.size() == 0 ||
3201           !Elts[0]->getType()->getScalarType()->isPointerTy())
3202         return Error(ID.Loc, "base of getelementptr must be a pointer");
3203 
3204       Type *BaseType = Elts[0]->getType();
3205       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3206       if (Ty != BasePointerType->getElementType())
3207         return Error(
3208             ExplicitTypeLoc,
3209             "explicit pointee type doesn't match operand's pointee type");
3210 
3211       unsigned GEPWidth =
3212           BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3213 
3214       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3215       for (Constant *Val : Indices) {
3216         Type *ValTy = Val->getType();
3217         if (!ValTy->getScalarType()->isIntegerTy())
3218           return Error(ID.Loc, "getelementptr index must be an integer");
3219         if (ValTy->isVectorTy()) {
3220           unsigned ValNumEl = ValTy->getVectorNumElements();
3221           if (GEPWidth && (ValNumEl != GEPWidth))
3222             return Error(
3223                 ID.Loc,
3224                 "getelementptr vector index has a wrong number of elements");
3225           // GEPWidth may have been unknown because the base is a scalar,
3226           // but it is known now.
3227           GEPWidth = ValNumEl;
3228         }
3229       }
3230 
3231       SmallPtrSet<Type*, 4> Visited;
3232       if (!Indices.empty() && !Ty->isSized(&Visited))
3233         return Error(ID.Loc, "base element of getelementptr must be sized");
3234 
3235       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3236         return Error(ID.Loc, "invalid getelementptr indices");
3237 
3238       if (InRangeOp) {
3239         if (*InRangeOp == 0)
3240           return Error(ID.Loc,
3241                        "inrange keyword may not appear on pointer operand");
3242         --*InRangeOp;
3243       }
3244 
3245       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3246                                                       InBounds, InRangeOp);
3247     } else if (Opc == Instruction::Select) {
3248       if (Elts.size() != 3)
3249         return Error(ID.Loc, "expected three operands to select");
3250       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3251                                                               Elts[2]))
3252         return Error(ID.Loc, Reason);
3253       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3254     } else if (Opc == Instruction::ShuffleVector) {
3255       if (Elts.size() != 3)
3256         return Error(ID.Loc, "expected three operands to shufflevector");
3257       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3258         return Error(ID.Loc, "invalid operands to shufflevector");
3259       ID.ConstantVal =
3260                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3261     } else if (Opc == Instruction::ExtractElement) {
3262       if (Elts.size() != 2)
3263         return Error(ID.Loc, "expected two operands to extractelement");
3264       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3265         return Error(ID.Loc, "invalid extractelement operands");
3266       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3267     } else {
3268       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3269       if (Elts.size() != 3)
3270       return Error(ID.Loc, "expected three operands to insertelement");
3271       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3272         return Error(ID.Loc, "invalid insertelement operands");
3273       ID.ConstantVal =
3274                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3275     }
3276 
3277     ID.Kind = ValID::t_Constant;
3278     return false;
3279   }
3280   }
3281 
3282   Lex.Lex();
3283   return false;
3284 }
3285 
3286 /// ParseGlobalValue - Parse a global value with the specified type.
3287 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3288   C = nullptr;
3289   ValID ID;
3290   Value *V = nullptr;
3291   bool Parsed = ParseValID(ID) ||
3292                 ConvertValIDToValue(Ty, ID, V, nullptr);
3293   if (V && !(C = dyn_cast<Constant>(V)))
3294     return Error(ID.Loc, "global values must be constants");
3295   return Parsed;
3296 }
3297 
3298 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3299   Type *Ty = nullptr;
3300   return ParseType(Ty) ||
3301          ParseGlobalValue(Ty, V);
3302 }
3303 
3304 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3305   C = nullptr;
3306 
3307   LocTy KwLoc = Lex.getLoc();
3308   if (!EatIfPresent(lltok::kw_comdat))
3309     return false;
3310 
3311   if (EatIfPresent(lltok::lparen)) {
3312     if (Lex.getKind() != lltok::ComdatVar)
3313       return TokError("expected comdat variable");
3314     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3315     Lex.Lex();
3316     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3317       return true;
3318   } else {
3319     if (GlobalName.empty())
3320       return TokError("comdat cannot be unnamed");
3321     C = getComdat(GlobalName, KwLoc);
3322   }
3323 
3324   return false;
3325 }
3326 
3327 /// ParseGlobalValueVector
3328 ///   ::= /*empty*/
3329 ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3330 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3331                                       Optional<unsigned> *InRangeOp) {
3332   // Empty list.
3333   if (Lex.getKind() == lltok::rbrace ||
3334       Lex.getKind() == lltok::rsquare ||
3335       Lex.getKind() == lltok::greater ||
3336       Lex.getKind() == lltok::rparen)
3337     return false;
3338 
3339   do {
3340     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3341       *InRangeOp = Elts.size();
3342 
3343     Constant *C;
3344     if (ParseGlobalTypeAndValue(C)) return true;
3345     Elts.push_back(C);
3346   } while (EatIfPresent(lltok::comma));
3347 
3348   return false;
3349 }
3350 
3351 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3352   SmallVector<Metadata *, 16> Elts;
3353   if (ParseMDNodeVector(Elts))
3354     return true;
3355 
3356   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3357   return false;
3358 }
3359 
3360 /// MDNode:
3361 ///  ::= !{ ... }
3362 ///  ::= !7
3363 ///  ::= !DILocation(...)
3364 bool LLParser::ParseMDNode(MDNode *&N) {
3365   if (Lex.getKind() == lltok::MetadataVar)
3366     return ParseSpecializedMDNode(N);
3367 
3368   return ParseToken(lltok::exclaim, "expected '!' here") ||
3369          ParseMDNodeTail(N);
3370 }
3371 
3372 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3373   // !{ ... }
3374   if (Lex.getKind() == lltok::lbrace)
3375     return ParseMDTuple(N);
3376 
3377   // !42
3378   return ParseMDNodeID(N);
3379 }
3380 
3381 namespace {
3382 
3383 /// Structure to represent an optional metadata field.
3384 template <class FieldTy> struct MDFieldImpl {
3385   typedef MDFieldImpl ImplTy;
3386   FieldTy Val;
3387   bool Seen;
3388 
3389   void assign(FieldTy Val) {
3390     Seen = true;
3391     this->Val = std::move(Val);
3392   }
3393 
3394   explicit MDFieldImpl(FieldTy Default)
3395       : Val(std::move(Default)), Seen(false) {}
3396 };
3397 
3398 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3399   uint64_t Max;
3400 
3401   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3402       : ImplTy(Default), Max(Max) {}
3403 };
3404 
3405 struct LineField : public MDUnsignedField {
3406   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3407 };
3408 
3409 struct ColumnField : public MDUnsignedField {
3410   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3411 };
3412 
3413 struct DwarfTagField : public MDUnsignedField {
3414   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3415   DwarfTagField(dwarf::Tag DefaultTag)
3416       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3417 };
3418 
3419 struct DwarfMacinfoTypeField : public MDUnsignedField {
3420   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3421   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3422     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3423 };
3424 
3425 struct DwarfAttEncodingField : public MDUnsignedField {
3426   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3427 };
3428 
3429 struct DwarfVirtualityField : public MDUnsignedField {
3430   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3431 };
3432 
3433 struct DwarfLangField : public MDUnsignedField {
3434   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3435 };
3436 
3437 struct DwarfCCField : public MDUnsignedField {
3438   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3439 };
3440 
3441 struct EmissionKindField : public MDUnsignedField {
3442   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3443 };
3444 
3445 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3446   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3447 };
3448 
3449 struct MDSignedField : public MDFieldImpl<int64_t> {
3450   int64_t Min;
3451   int64_t Max;
3452 
3453   MDSignedField(int64_t Default = 0)
3454       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3455   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3456       : ImplTy(Default), Min(Min), Max(Max) {}
3457 };
3458 
3459 struct MDBoolField : public MDFieldImpl<bool> {
3460   MDBoolField(bool Default = false) : ImplTy(Default) {}
3461 };
3462 
3463 struct MDField : public MDFieldImpl<Metadata *> {
3464   bool AllowNull;
3465 
3466   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3467 };
3468 
3469 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3470   MDConstant() : ImplTy(nullptr) {}
3471 };
3472 
3473 struct MDStringField : public MDFieldImpl<MDString *> {
3474   bool AllowEmpty;
3475   MDStringField(bool AllowEmpty = true)
3476       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3477 };
3478 
3479 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3480   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3481 };
3482 
3483 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3484   ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3485   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3486 };
3487 
3488 } // end anonymous namespace
3489 
3490 namespace llvm {
3491 
3492 template <>
3493 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3494                             MDUnsignedField &Result) {
3495   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3496     return TokError("expected unsigned integer");
3497 
3498   auto &U = Lex.getAPSIntVal();
3499   if (U.ugt(Result.Max))
3500     return TokError("value for '" + Name + "' too large, limit is " +
3501                     Twine(Result.Max));
3502   Result.assign(U.getZExtValue());
3503   assert(Result.Val <= Result.Max && "Expected value in range");
3504   Lex.Lex();
3505   return false;
3506 }
3507 
3508 template <>
3509 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3510   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3511 }
3512 template <>
3513 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3514   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3515 }
3516 
3517 template <>
3518 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3519   if (Lex.getKind() == lltok::APSInt)
3520     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3521 
3522   if (Lex.getKind() != lltok::DwarfTag)
3523     return TokError("expected DWARF tag");
3524 
3525   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3526   if (Tag == dwarf::DW_TAG_invalid)
3527     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3528   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3529 
3530   Result.assign(Tag);
3531   Lex.Lex();
3532   return false;
3533 }
3534 
3535 template <>
3536 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3537                             DwarfMacinfoTypeField &Result) {
3538   if (Lex.getKind() == lltok::APSInt)
3539     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3540 
3541   if (Lex.getKind() != lltok::DwarfMacinfo)
3542     return TokError("expected DWARF macinfo type");
3543 
3544   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3545   if (Macinfo == dwarf::DW_MACINFO_invalid)
3546     return TokError(
3547         "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3548   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3549 
3550   Result.assign(Macinfo);
3551   Lex.Lex();
3552   return false;
3553 }
3554 
3555 template <>
3556 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3557                             DwarfVirtualityField &Result) {
3558   if (Lex.getKind() == lltok::APSInt)
3559     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3560 
3561   if (Lex.getKind() != lltok::DwarfVirtuality)
3562     return TokError("expected DWARF virtuality code");
3563 
3564   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3565   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3566     return TokError("invalid DWARF virtuality code" + Twine(" '") +
3567                     Lex.getStrVal() + "'");
3568   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3569   Result.assign(Virtuality);
3570   Lex.Lex();
3571   return false;
3572 }
3573 
3574 template <>
3575 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3576   if (Lex.getKind() == lltok::APSInt)
3577     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3578 
3579   if (Lex.getKind() != lltok::DwarfLang)
3580     return TokError("expected DWARF language");
3581 
3582   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3583   if (!Lang)
3584     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3585                     "'");
3586   assert(Lang <= Result.Max && "Expected valid DWARF language");
3587   Result.assign(Lang);
3588   Lex.Lex();
3589   return false;
3590 }
3591 
3592 template <>
3593 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3594   if (Lex.getKind() == lltok::APSInt)
3595     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3596 
3597   if (Lex.getKind() != lltok::DwarfCC)
3598     return TokError("expected DWARF calling convention");
3599 
3600   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3601   if (!CC)
3602     return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3603                     "'");
3604   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3605   Result.assign(CC);
3606   Lex.Lex();
3607   return false;
3608 }
3609 
3610 template <>
3611 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3612   if (Lex.getKind() == lltok::APSInt)
3613     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3614 
3615   if (Lex.getKind() != lltok::EmissionKind)
3616     return TokError("expected emission kind");
3617 
3618   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3619   if (!Kind)
3620     return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3621                     "'");
3622   assert(*Kind <= Result.Max && "Expected valid emission kind");
3623   Result.assign(*Kind);
3624   Lex.Lex();
3625   return false;
3626 }
3627 
3628 template <>
3629 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3630                             DwarfAttEncodingField &Result) {
3631   if (Lex.getKind() == lltok::APSInt)
3632     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3633 
3634   if (Lex.getKind() != lltok::DwarfAttEncoding)
3635     return TokError("expected DWARF type attribute encoding");
3636 
3637   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3638   if (!Encoding)
3639     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3640                     Lex.getStrVal() + "'");
3641   assert(Encoding <= Result.Max && "Expected valid DWARF language");
3642   Result.assign(Encoding);
3643   Lex.Lex();
3644   return false;
3645 }
3646 
3647 /// DIFlagField
3648 ///  ::= uint32
3649 ///  ::= DIFlagVector
3650 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3651 template <>
3652 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3653 
3654   // Parser for a single flag.
3655   auto parseFlag = [&](DINode::DIFlags &Val) {
3656     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3657       uint32_t TempVal = static_cast<uint32_t>(Val);
3658       bool Res = ParseUInt32(TempVal);
3659       Val = static_cast<DINode::DIFlags>(TempVal);
3660       return Res;
3661     }
3662 
3663     if (Lex.getKind() != lltok::DIFlag)
3664       return TokError("expected debug info flag");
3665 
3666     Val = DINode::getFlag(Lex.getStrVal());
3667     if (!Val)
3668       return TokError(Twine("invalid debug info flag flag '") +
3669                       Lex.getStrVal() + "'");
3670     Lex.Lex();
3671     return false;
3672   };
3673 
3674   // Parse the flags and combine them together.
3675   DINode::DIFlags Combined = DINode::FlagZero;
3676   do {
3677     DINode::DIFlags Val;
3678     if (parseFlag(Val))
3679       return true;
3680     Combined |= Val;
3681   } while (EatIfPresent(lltok::bar));
3682 
3683   Result.assign(Combined);
3684   return false;
3685 }
3686 
3687 template <>
3688 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3689                             MDSignedField &Result) {
3690   if (Lex.getKind() != lltok::APSInt)
3691     return TokError("expected signed integer");
3692 
3693   auto &S = Lex.getAPSIntVal();
3694   if (S < Result.Min)
3695     return TokError("value for '" + Name + "' too small, limit is " +
3696                     Twine(Result.Min));
3697   if (S > Result.Max)
3698     return TokError("value for '" + Name + "' too large, limit is " +
3699                     Twine(Result.Max));
3700   Result.assign(S.getExtValue());
3701   assert(Result.Val >= Result.Min && "Expected value in range");
3702   assert(Result.Val <= Result.Max && "Expected value in range");
3703   Lex.Lex();
3704   return false;
3705 }
3706 
3707 template <>
3708 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3709   switch (Lex.getKind()) {
3710   default:
3711     return TokError("expected 'true' or 'false'");
3712   case lltok::kw_true:
3713     Result.assign(true);
3714     break;
3715   case lltok::kw_false:
3716     Result.assign(false);
3717     break;
3718   }
3719   Lex.Lex();
3720   return false;
3721 }
3722 
3723 template <>
3724 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3725   if (Lex.getKind() == lltok::kw_null) {
3726     if (!Result.AllowNull)
3727       return TokError("'" + Name + "' cannot be null");
3728     Lex.Lex();
3729     Result.assign(nullptr);
3730     return false;
3731   }
3732 
3733   Metadata *MD;
3734   if (ParseMetadata(MD, nullptr))
3735     return true;
3736 
3737   Result.assign(MD);
3738   return false;
3739 }
3740 
3741 template <>
3742 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3743   LocTy ValueLoc = Lex.getLoc();
3744   std::string S;
3745   if (ParseStringConstant(S))
3746     return true;
3747 
3748   if (!Result.AllowEmpty && S.empty())
3749     return Error(ValueLoc, "'" + Name + "' cannot be empty");
3750 
3751   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3752   return false;
3753 }
3754 
3755 template <>
3756 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3757   SmallVector<Metadata *, 4> MDs;
3758   if (ParseMDNodeVector(MDs))
3759     return true;
3760 
3761   Result.assign(std::move(MDs));
3762   return false;
3763 }
3764 
3765 template <>
3766 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3767                             ChecksumKindField &Result) {
3768   if (Lex.getKind() != lltok::ChecksumKind)
3769     return TokError(
3770         "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3771 
3772   DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3773 
3774   Result.assign(CSKind);
3775   Lex.Lex();
3776   return false;
3777 }
3778 
3779 } // end namespace llvm
3780 
3781 template <class ParserTy>
3782 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3783   do {
3784     if (Lex.getKind() != lltok::LabelStr)
3785       return TokError("expected field label here");
3786 
3787     if (parseField())
3788       return true;
3789   } while (EatIfPresent(lltok::comma));
3790 
3791   return false;
3792 }
3793 
3794 template <class ParserTy>
3795 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3796   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3797   Lex.Lex();
3798 
3799   if (ParseToken(lltok::lparen, "expected '(' here"))
3800     return true;
3801   if (Lex.getKind() != lltok::rparen)
3802     if (ParseMDFieldsImplBody(parseField))
3803       return true;
3804 
3805   ClosingLoc = Lex.getLoc();
3806   return ParseToken(lltok::rparen, "expected ')' here");
3807 }
3808 
3809 template <class FieldTy>
3810 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3811   if (Result.Seen)
3812     return TokError("field '" + Name + "' cannot be specified more than once");
3813 
3814   LocTy Loc = Lex.getLoc();
3815   Lex.Lex();
3816   return ParseMDField(Loc, Name, Result);
3817 }
3818 
3819 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3820   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3821 
3822 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
3823   if (Lex.getStrVal() == #CLASS)                                               \
3824     return Parse##CLASS(N, IsDistinct);
3825 #include "llvm/IR/Metadata.def"
3826 
3827   return TokError("expected metadata type");
3828 }
3829 
3830 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3831 #define NOP_FIELD(NAME, TYPE, INIT)
3832 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
3833   if (!NAME.Seen)                                                              \
3834     return Error(ClosingLoc, "missing required field '" #NAME "'");
3835 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
3836   if (Lex.getStrVal() == #NAME)                                                \
3837     return ParseMDField(#NAME, NAME);
3838 #define PARSE_MD_FIELDS()                                                      \
3839   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
3840   do {                                                                         \
3841     LocTy ClosingLoc;                                                          \
3842     if (ParseMDFieldsImpl([&]() -> bool {                                      \
3843       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
3844       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
3845     }, ClosingLoc))                                                            \
3846       return true;                                                             \
3847     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
3848   } while (false)
3849 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
3850   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3851 
3852 /// ParseDILocationFields:
3853 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3854 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3855 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3856   OPTIONAL(line, LineField, );                                                 \
3857   OPTIONAL(column, ColumnField, );                                             \
3858   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3859   OPTIONAL(inlinedAt, MDField, );
3860   PARSE_MD_FIELDS();
3861 #undef VISIT_MD_FIELDS
3862 
3863   Result = GET_OR_DISTINCT(
3864       DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3865   return false;
3866 }
3867 
3868 /// ParseGenericDINode:
3869 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3870 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3871 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3872   REQUIRED(tag, DwarfTagField, );                                              \
3873   OPTIONAL(header, MDStringField, );                                           \
3874   OPTIONAL(operands, MDFieldList, );
3875   PARSE_MD_FIELDS();
3876 #undef VISIT_MD_FIELDS
3877 
3878   Result = GET_OR_DISTINCT(GenericDINode,
3879                            (Context, tag.Val, header.Val, operands.Val));
3880   return false;
3881 }
3882 
3883 /// ParseDISubrange:
3884 ///   ::= !DISubrange(count: 30, lowerBound: 2)
3885 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3886 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3887   REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX));                         \
3888   OPTIONAL(lowerBound, MDSignedField, );
3889   PARSE_MD_FIELDS();
3890 #undef VISIT_MD_FIELDS
3891 
3892   Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3893   return false;
3894 }
3895 
3896 /// ParseDIEnumerator:
3897 ///   ::= !DIEnumerator(value: 30, name: "SomeKind")
3898 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3899 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3900   REQUIRED(name, MDStringField, );                                             \
3901   REQUIRED(value, MDSignedField, );
3902   PARSE_MD_FIELDS();
3903 #undef VISIT_MD_FIELDS
3904 
3905   Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3906   return false;
3907 }
3908 
3909 /// ParseDIBasicType:
3910 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3911 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3912 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3913   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
3914   OPTIONAL(name, MDStringField, );                                             \
3915   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3916   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
3917   OPTIONAL(encoding, DwarfAttEncodingField, );
3918   PARSE_MD_FIELDS();
3919 #undef VISIT_MD_FIELDS
3920 
3921   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3922                                          align.Val, encoding.Val));
3923   return false;
3924 }
3925 
3926 /// ParseDIDerivedType:
3927 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3928 ///                      line: 7, scope: !1, baseType: !2, size: 32,
3929 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
3930 ///                      dwarfAddressSpace: 3)
3931 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3932 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3933   REQUIRED(tag, DwarfTagField, );                                              \
3934   OPTIONAL(name, MDStringField, );                                             \
3935   OPTIONAL(file, MDField, );                                                   \
3936   OPTIONAL(line, LineField, );                                                 \
3937   OPTIONAL(scope, MDField, );                                                  \
3938   REQUIRED(baseType, MDField, );                                               \
3939   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3940   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
3941   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3942   OPTIONAL(flags, DIFlagField, );                                              \
3943   OPTIONAL(extraData, MDField, );                                              \
3944   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
3945   PARSE_MD_FIELDS();
3946 #undef VISIT_MD_FIELDS
3947 
3948   Optional<unsigned> DWARFAddressSpace;
3949   if (dwarfAddressSpace.Val != UINT32_MAX)
3950     DWARFAddressSpace = dwarfAddressSpace.Val;
3951 
3952   Result = GET_OR_DISTINCT(DIDerivedType,
3953                            (Context, tag.Val, name.Val, file.Val, line.Val,
3954                             scope.Val, baseType.Val, size.Val, align.Val,
3955                             offset.Val, DWARFAddressSpace, flags.Val,
3956                             extraData.Val));
3957   return false;
3958 }
3959 
3960 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3961 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3962   REQUIRED(tag, DwarfTagField, );                                              \
3963   OPTIONAL(name, MDStringField, );                                             \
3964   OPTIONAL(file, MDField, );                                                   \
3965   OPTIONAL(line, LineField, );                                                 \
3966   OPTIONAL(scope, MDField, );                                                  \
3967   OPTIONAL(baseType, MDField, );                                               \
3968   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3969   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
3970   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3971   OPTIONAL(flags, DIFlagField, );                                              \
3972   OPTIONAL(elements, MDField, );                                               \
3973   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
3974   OPTIONAL(vtableHolder, MDField, );                                           \
3975   OPTIONAL(templateParams, MDField, );                                         \
3976   OPTIONAL(identifier, MDStringField, );
3977   PARSE_MD_FIELDS();
3978 #undef VISIT_MD_FIELDS
3979 
3980   // If this has an identifier try to build an ODR type.
3981   if (identifier.Val)
3982     if (auto *CT = DICompositeType::buildODRType(
3983             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3984             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3985             elements.Val, runtimeLang.Val, vtableHolder.Val,
3986             templateParams.Val)) {
3987       Result = CT;
3988       return false;
3989     }
3990 
3991   // Create a new node, and save it in the context if it belongs in the type
3992   // map.
3993   Result = GET_OR_DISTINCT(
3994       DICompositeType,
3995       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3996        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3997        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3998   return false;
3999 }
4000 
4001 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4002 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4003   OPTIONAL(flags, DIFlagField, );                                              \
4004   OPTIONAL(cc, DwarfCCField, );                                                \
4005   REQUIRED(types, MDField, );
4006   PARSE_MD_FIELDS();
4007 #undef VISIT_MD_FIELDS
4008 
4009   Result = GET_OR_DISTINCT(DISubroutineType,
4010                            (Context, flags.Val, cc.Val, types.Val));
4011   return false;
4012 }
4013 
4014 /// ParseDIFileType:
4015 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4016 ///                   checksumkind: CSK_MD5,
4017 ///                   checksum: "000102030405060708090a0b0c0d0e0f")
4018 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4019 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4020   REQUIRED(filename, MDStringField, );                                         \
4021   REQUIRED(directory, MDStringField, );                                        \
4022   OPTIONAL(checksumkind, ChecksumKindField, );                                 \
4023   OPTIONAL(checksum, MDStringField, );
4024   PARSE_MD_FIELDS();
4025 #undef VISIT_MD_FIELDS
4026 
4027   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4028                                     checksumkind.Val, checksum.Val));
4029   return false;
4030 }
4031 
4032 /// ParseDICompileUnit:
4033 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4034 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
4035 ///                      splitDebugFilename: "abc.debug",
4036 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4037 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4038 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4039   if (!IsDistinct)
4040     return Lex.Error("missing 'distinct', required for !DICompileUnit");
4041 
4042 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4043   REQUIRED(language, DwarfLangField, );                                        \
4044   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
4045   OPTIONAL(producer, MDStringField, );                                         \
4046   OPTIONAL(isOptimized, MDBoolField, );                                        \
4047   OPTIONAL(flags, MDStringField, );                                            \
4048   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
4049   OPTIONAL(splitDebugFilename, MDStringField, );                               \
4050   OPTIONAL(emissionKind, EmissionKindField, );                                 \
4051   OPTIONAL(enums, MDField, );                                                  \
4052   OPTIONAL(retainedTypes, MDField, );                                          \
4053   OPTIONAL(globals, MDField, );                                                \
4054   OPTIONAL(imports, MDField, );                                                \
4055   OPTIONAL(macros, MDField, );                                                 \
4056   OPTIONAL(dwoId, MDUnsignedField, );                                          \
4057   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
4058   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
4059   PARSE_MD_FIELDS();
4060 #undef VISIT_MD_FIELDS
4061 
4062   Result = DICompileUnit::getDistinct(
4063       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4064       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4065       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4066       splitDebugInlining.Val, debugInfoForProfiling.Val);
4067   return false;
4068 }
4069 
4070 /// ParseDISubprogram:
4071 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4072 ///                     file: !1, line: 7, type: !2, isLocal: false,
4073 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
4074 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
4075 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
4076 ///                     isOptimized: false, templateParams: !4, declaration: !5,
4077 ///                     variables: !6)
4078 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4079   auto Loc = Lex.getLoc();
4080 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4081   OPTIONAL(scope, MDField, );                                                  \
4082   OPTIONAL(name, MDStringField, );                                             \
4083   OPTIONAL(linkageName, MDStringField, );                                      \
4084   OPTIONAL(file, MDField, );                                                   \
4085   OPTIONAL(line, LineField, );                                                 \
4086   OPTIONAL(type, MDField, );                                                   \
4087   OPTIONAL(isLocal, MDBoolField, );                                            \
4088   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4089   OPTIONAL(scopeLine, LineField, );                                            \
4090   OPTIONAL(containingType, MDField, );                                         \
4091   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
4092   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
4093   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
4094   OPTIONAL(flags, DIFlagField, );                                              \
4095   OPTIONAL(isOptimized, MDBoolField, );                                        \
4096   OPTIONAL(unit, MDField, );                                                   \
4097   OPTIONAL(templateParams, MDField, );                                         \
4098   OPTIONAL(declaration, MDField, );                                            \
4099   OPTIONAL(variables, MDField, );
4100   PARSE_MD_FIELDS();
4101 #undef VISIT_MD_FIELDS
4102 
4103   if (isDefinition.Val && !IsDistinct)
4104     return Lex.Error(
4105         Loc,
4106         "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4107 
4108   Result = GET_OR_DISTINCT(
4109       DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4110                      line.Val, type.Val, isLocal.Val, isDefinition.Val,
4111                      scopeLine.Val, containingType.Val, virtuality.Val,
4112                      virtualIndex.Val, thisAdjustment.Val, flags.Val,
4113                      isOptimized.Val, unit.Val, templateParams.Val,
4114                      declaration.Val, variables.Val));
4115   return false;
4116 }
4117 
4118 /// ParseDILexicalBlock:
4119 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4120 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4121 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4122   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4123   OPTIONAL(file, MDField, );                                                   \
4124   OPTIONAL(line, LineField, );                                                 \
4125   OPTIONAL(column, ColumnField, );
4126   PARSE_MD_FIELDS();
4127 #undef VISIT_MD_FIELDS
4128 
4129   Result = GET_OR_DISTINCT(
4130       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4131   return false;
4132 }
4133 
4134 /// ParseDILexicalBlockFile:
4135 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4136 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4137 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4138   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4139   OPTIONAL(file, MDField, );                                                   \
4140   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4141   PARSE_MD_FIELDS();
4142 #undef VISIT_MD_FIELDS
4143 
4144   Result = GET_OR_DISTINCT(DILexicalBlockFile,
4145                            (Context, scope.Val, file.Val, discriminator.Val));
4146   return false;
4147 }
4148 
4149 /// ParseDINamespace:
4150 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4151 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4152 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4153   REQUIRED(scope, MDField, );                                                  \
4154   OPTIONAL(file, MDField, );                                                   \
4155   OPTIONAL(name, MDStringField, );                                             \
4156   OPTIONAL(line, LineField, );                                                 \
4157   OPTIONAL(exportSymbols, MDBoolField, );
4158   PARSE_MD_FIELDS();
4159 #undef VISIT_MD_FIELDS
4160 
4161   Result = GET_OR_DISTINCT(DINamespace,
4162   (Context, scope.Val, file.Val, name.Val, line.Val, exportSymbols.Val));
4163   return false;
4164 }
4165 
4166 /// ParseDIMacro:
4167 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4168 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4169 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4170   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
4171   OPTIONAL(line, LineField, );                                                 \
4172   REQUIRED(name, MDStringField, );                                             \
4173   OPTIONAL(value, MDStringField, );
4174   PARSE_MD_FIELDS();
4175 #undef VISIT_MD_FIELDS
4176 
4177   Result = GET_OR_DISTINCT(DIMacro,
4178                            (Context, type.Val, line.Val, name.Val, value.Val));
4179   return false;
4180 }
4181 
4182 /// ParseDIMacroFile:
4183 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4184 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4185 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4186   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
4187   OPTIONAL(line, LineField, );                                                 \
4188   REQUIRED(file, MDField, );                                                   \
4189   OPTIONAL(nodes, MDField, );
4190   PARSE_MD_FIELDS();
4191 #undef VISIT_MD_FIELDS
4192 
4193   Result = GET_OR_DISTINCT(DIMacroFile,
4194                            (Context, type.Val, line.Val, file.Val, nodes.Val));
4195   return false;
4196 }
4197 
4198 /// ParseDIModule:
4199 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4200 ///                 includePath: "/usr/include", isysroot: "/")
4201 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4202 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4203   REQUIRED(scope, MDField, );                                                  \
4204   REQUIRED(name, MDStringField, );                                             \
4205   OPTIONAL(configMacros, MDStringField, );                                     \
4206   OPTIONAL(includePath, MDStringField, );                                      \
4207   OPTIONAL(isysroot, MDStringField, );
4208   PARSE_MD_FIELDS();
4209 #undef VISIT_MD_FIELDS
4210 
4211   Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4212                            configMacros.Val, includePath.Val, isysroot.Val));
4213   return false;
4214 }
4215 
4216 /// ParseDITemplateTypeParameter:
4217 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4218 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4219 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4220   OPTIONAL(name, MDStringField, );                                             \
4221   REQUIRED(type, MDField, );
4222   PARSE_MD_FIELDS();
4223 #undef VISIT_MD_FIELDS
4224 
4225   Result =
4226       GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4227   return false;
4228 }
4229 
4230 /// ParseDITemplateValueParameter:
4231 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4232 ///                                 name: "V", type: !1, value: i32 7)
4233 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4234 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4235   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
4236   OPTIONAL(name, MDStringField, );                                             \
4237   OPTIONAL(type, MDField, );                                                   \
4238   REQUIRED(value, MDField, );
4239   PARSE_MD_FIELDS();
4240 #undef VISIT_MD_FIELDS
4241 
4242   Result = GET_OR_DISTINCT(DITemplateValueParameter,
4243                            (Context, tag.Val, name.Val, type.Val, value.Val));
4244   return false;
4245 }
4246 
4247 /// ParseDIGlobalVariable:
4248 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4249 ///                         file: !1, line: 7, type: !2, isLocal: false,
4250 ///                         isDefinition: true, declaration: !3, align: 8)
4251 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4252 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4253   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
4254   OPTIONAL(scope, MDField, );                                                  \
4255   OPTIONAL(linkageName, MDStringField, );                                      \
4256   OPTIONAL(file, MDField, );                                                   \
4257   OPTIONAL(line, LineField, );                                                 \
4258   OPTIONAL(type, MDField, );                                                   \
4259   OPTIONAL(isLocal, MDBoolField, );                                            \
4260   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4261   OPTIONAL(declaration, MDField, );                                            \
4262   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4263   PARSE_MD_FIELDS();
4264 #undef VISIT_MD_FIELDS
4265 
4266   Result = GET_OR_DISTINCT(DIGlobalVariable,
4267                            (Context, scope.Val, name.Val, linkageName.Val,
4268                             file.Val, line.Val, type.Val, isLocal.Val,
4269                             isDefinition.Val, declaration.Val, align.Val));
4270   return false;
4271 }
4272 
4273 /// ParseDILocalVariable:
4274 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4275 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
4276 ///                        align: 8)
4277 ///   ::= !DILocalVariable(scope: !0, name: "foo",
4278 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
4279 ///                        align: 8)
4280 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4281 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4282   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4283   OPTIONAL(name, MDStringField, );                                             \
4284   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
4285   OPTIONAL(file, MDField, );                                                   \
4286   OPTIONAL(line, LineField, );                                                 \
4287   OPTIONAL(type, MDField, );                                                   \
4288   OPTIONAL(flags, DIFlagField, );                                              \
4289   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4290   PARSE_MD_FIELDS();
4291 #undef VISIT_MD_FIELDS
4292 
4293   Result = GET_OR_DISTINCT(DILocalVariable,
4294                            (Context, scope.Val, name.Val, file.Val, line.Val,
4295                             type.Val, arg.Val, flags.Val, align.Val));
4296   return false;
4297 }
4298 
4299 /// ParseDIExpression:
4300 ///   ::= !DIExpression(0, 7, -1)
4301 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4302   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4303   Lex.Lex();
4304 
4305   if (ParseToken(lltok::lparen, "expected '(' here"))
4306     return true;
4307 
4308   SmallVector<uint64_t, 8> Elements;
4309   if (Lex.getKind() != lltok::rparen)
4310     do {
4311       if (Lex.getKind() == lltok::DwarfOp) {
4312         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4313           Lex.Lex();
4314           Elements.push_back(Op);
4315           continue;
4316         }
4317         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4318       }
4319 
4320       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4321         return TokError("expected unsigned integer");
4322 
4323       auto &U = Lex.getAPSIntVal();
4324       if (U.ugt(UINT64_MAX))
4325         return TokError("element too large, limit is " + Twine(UINT64_MAX));
4326       Elements.push_back(U.getZExtValue());
4327       Lex.Lex();
4328     } while (EatIfPresent(lltok::comma));
4329 
4330   if (ParseToken(lltok::rparen, "expected ')' here"))
4331     return true;
4332 
4333   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4334   return false;
4335 }
4336 
4337 /// ParseDIGlobalVariableExpression:
4338 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4339 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4340                                                bool IsDistinct) {
4341 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4342   REQUIRED(var, MDField, );                                                    \
4343   OPTIONAL(expr, MDField, );
4344   PARSE_MD_FIELDS();
4345 #undef VISIT_MD_FIELDS
4346 
4347   Result =
4348       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4349   return false;
4350 }
4351 
4352 /// ParseDIObjCProperty:
4353 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4354 ///                       getter: "getFoo", attributes: 7, type: !2)
4355 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4356 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4357   OPTIONAL(name, MDStringField, );                                             \
4358   OPTIONAL(file, MDField, );                                                   \
4359   OPTIONAL(line, LineField, );                                                 \
4360   OPTIONAL(setter, MDStringField, );                                           \
4361   OPTIONAL(getter, MDStringField, );                                           \
4362   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
4363   OPTIONAL(type, MDField, );
4364   PARSE_MD_FIELDS();
4365 #undef VISIT_MD_FIELDS
4366 
4367   Result = GET_OR_DISTINCT(DIObjCProperty,
4368                            (Context, name.Val, file.Val, line.Val, setter.Val,
4369                             getter.Val, attributes.Val, type.Val));
4370   return false;
4371 }
4372 
4373 /// ParseDIImportedEntity:
4374 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4375 ///                         line: 7, name: "foo")
4376 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4377 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4378   REQUIRED(tag, DwarfTagField, );                                              \
4379   REQUIRED(scope, MDField, );                                                  \
4380   OPTIONAL(entity, MDField, );                                                 \
4381   OPTIONAL(line, LineField, );                                                 \
4382   OPTIONAL(name, MDStringField, );
4383   PARSE_MD_FIELDS();
4384 #undef VISIT_MD_FIELDS
4385 
4386   Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4387                                               entity.Val, line.Val, name.Val));
4388   return false;
4389 }
4390 
4391 #undef PARSE_MD_FIELD
4392 #undef NOP_FIELD
4393 #undef REQUIRE_FIELD
4394 #undef DECLARE_FIELD
4395 
4396 /// ParseMetadataAsValue
4397 ///  ::= metadata i32 %local
4398 ///  ::= metadata i32 @global
4399 ///  ::= metadata i32 7
4400 ///  ::= metadata !0
4401 ///  ::= metadata !{...}
4402 ///  ::= metadata !"string"
4403 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4404   // Note: the type 'metadata' has already been parsed.
4405   Metadata *MD;
4406   if (ParseMetadata(MD, &PFS))
4407     return true;
4408 
4409   V = MetadataAsValue::get(Context, MD);
4410   return false;
4411 }
4412 
4413 /// ParseValueAsMetadata
4414 ///  ::= i32 %local
4415 ///  ::= i32 @global
4416 ///  ::= i32 7
4417 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4418                                     PerFunctionState *PFS) {
4419   Type *Ty;
4420   LocTy Loc;
4421   if (ParseType(Ty, TypeMsg, Loc))
4422     return true;
4423   if (Ty->isMetadataTy())
4424     return Error(Loc, "invalid metadata-value-metadata roundtrip");
4425 
4426   Value *V;
4427   if (ParseValue(Ty, V, PFS))
4428     return true;
4429 
4430   MD = ValueAsMetadata::get(V);
4431   return false;
4432 }
4433 
4434 /// ParseMetadata
4435 ///  ::= i32 %local
4436 ///  ::= i32 @global
4437 ///  ::= i32 7
4438 ///  ::= !42
4439 ///  ::= !{...}
4440 ///  ::= !"string"
4441 ///  ::= !DILocation(...)
4442 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4443   if (Lex.getKind() == lltok::MetadataVar) {
4444     MDNode *N;
4445     if (ParseSpecializedMDNode(N))
4446       return true;
4447     MD = N;
4448     return false;
4449   }
4450 
4451   // ValueAsMetadata:
4452   // <type> <value>
4453   if (Lex.getKind() != lltok::exclaim)
4454     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4455 
4456   // '!'.
4457   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4458   Lex.Lex();
4459 
4460   // MDString:
4461   //   ::= '!' STRINGCONSTANT
4462   if (Lex.getKind() == lltok::StringConstant) {
4463     MDString *S;
4464     if (ParseMDString(S))
4465       return true;
4466     MD = S;
4467     return false;
4468   }
4469 
4470   // MDNode:
4471   // !{ ... }
4472   // !7
4473   MDNode *N;
4474   if (ParseMDNodeTail(N))
4475     return true;
4476   MD = N;
4477   return false;
4478 }
4479 
4480 //===----------------------------------------------------------------------===//
4481 // Function Parsing.
4482 //===----------------------------------------------------------------------===//
4483 
4484 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4485                                    PerFunctionState *PFS) {
4486   if (Ty->isFunctionTy())
4487     return Error(ID.Loc, "functions are not values, refer to them as pointers");
4488 
4489   switch (ID.Kind) {
4490   case ValID::t_LocalID:
4491     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4492     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4493     return V == nullptr;
4494   case ValID::t_LocalName:
4495     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4496     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4497     return V == nullptr;
4498   case ValID::t_InlineAsm: {
4499     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4500       return Error(ID.Loc, "invalid type for inline asm constraint string");
4501     V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4502                        (ID.UIntVal >> 1) & 1,
4503                        (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4504     return false;
4505   }
4506   case ValID::t_GlobalName:
4507     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4508     return V == nullptr;
4509   case ValID::t_GlobalID:
4510     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4511     return V == nullptr;
4512   case ValID::t_APSInt:
4513     if (!Ty->isIntegerTy())
4514       return Error(ID.Loc, "integer constant must have integer type");
4515     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4516     V = ConstantInt::get(Context, ID.APSIntVal);
4517     return false;
4518   case ValID::t_APFloat:
4519     if (!Ty->isFloatingPointTy() ||
4520         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4521       return Error(ID.Loc, "floating point constant invalid for type");
4522 
4523     // The lexer has no type info, so builds all half, float, and double FP
4524     // constants as double.  Fix this here.  Long double does not need this.
4525     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
4526       bool Ignored;
4527       if (Ty->isHalfTy())
4528         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
4529                               &Ignored);
4530       else if (Ty->isFloatTy())
4531         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
4532                               &Ignored);
4533     }
4534     V = ConstantFP::get(Context, ID.APFloatVal);
4535 
4536     if (V->getType() != Ty)
4537       return Error(ID.Loc, "floating point constant does not have type '" +
4538                    getTypeString(Ty) + "'");
4539 
4540     return false;
4541   case ValID::t_Null:
4542     if (!Ty->isPointerTy())
4543       return Error(ID.Loc, "null must be a pointer type");
4544     V = ConstantPointerNull::get(cast<PointerType>(Ty));
4545     return false;
4546   case ValID::t_Undef:
4547     // FIXME: LabelTy should not be a first-class type.
4548     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4549       return Error(ID.Loc, "invalid type for undef constant");
4550     V = UndefValue::get(Ty);
4551     return false;
4552   case ValID::t_EmptyArray:
4553     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4554       return Error(ID.Loc, "invalid empty array initializer");
4555     V = UndefValue::get(Ty);
4556     return false;
4557   case ValID::t_Zero:
4558     // FIXME: LabelTy should not be a first-class type.
4559     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4560       return Error(ID.Loc, "invalid type for null constant");
4561     V = Constant::getNullValue(Ty);
4562     return false;
4563   case ValID::t_None:
4564     if (!Ty->isTokenTy())
4565       return Error(ID.Loc, "invalid type for none constant");
4566     V = Constant::getNullValue(Ty);
4567     return false;
4568   case ValID::t_Constant:
4569     if (ID.ConstantVal->getType() != Ty)
4570       return Error(ID.Loc, "constant expression type mismatch");
4571 
4572     V = ID.ConstantVal;
4573     return false;
4574   case ValID::t_ConstantStruct:
4575   case ValID::t_PackedConstantStruct:
4576     if (StructType *ST = dyn_cast<StructType>(Ty)) {
4577       if (ST->getNumElements() != ID.UIntVal)
4578         return Error(ID.Loc,
4579                      "initializer with struct type has wrong # elements");
4580       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4581         return Error(ID.Loc, "packed'ness of initializer and type don't match");
4582 
4583       // Verify that the elements are compatible with the structtype.
4584       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4585         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4586           return Error(ID.Loc, "element " + Twine(i) +
4587                     " of struct initializer doesn't match struct element type");
4588 
4589       V = ConstantStruct::get(
4590           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4591     } else
4592       return Error(ID.Loc, "constant expression type mismatch");
4593     return false;
4594   }
4595   llvm_unreachable("Invalid ValID");
4596 }
4597 
4598 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4599   C = nullptr;
4600   ValID ID;
4601   auto Loc = Lex.getLoc();
4602   if (ParseValID(ID, /*PFS=*/nullptr))
4603     return true;
4604   switch (ID.Kind) {
4605   case ValID::t_APSInt:
4606   case ValID::t_APFloat:
4607   case ValID::t_Undef:
4608   case ValID::t_Constant:
4609   case ValID::t_ConstantStruct:
4610   case ValID::t_PackedConstantStruct: {
4611     Value *V;
4612     if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4613       return true;
4614     assert(isa<Constant>(V) && "Expected a constant value");
4615     C = cast<Constant>(V);
4616     return false;
4617   }
4618   case ValID::t_Null:
4619     C = Constant::getNullValue(Ty);
4620     return false;
4621   default:
4622     return Error(Loc, "expected a constant value");
4623   }
4624 }
4625 
4626 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4627   V = nullptr;
4628   ValID ID;
4629   return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4630 }
4631 
4632 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4633   Type *Ty = nullptr;
4634   return ParseType(Ty) ||
4635          ParseValue(Ty, V, PFS);
4636 }
4637 
4638 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4639                                       PerFunctionState &PFS) {
4640   Value *V;
4641   Loc = Lex.getLoc();
4642   if (ParseTypeAndValue(V, PFS)) return true;
4643   if (!isa<BasicBlock>(V))
4644     return Error(Loc, "expected a basic block");
4645   BB = cast<BasicBlock>(V);
4646   return false;
4647 }
4648 
4649 /// FunctionHeader
4650 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4651 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4652 ///       OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4653 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4654   // Parse the linkage.
4655   LocTy LinkageLoc = Lex.getLoc();
4656   unsigned Linkage;
4657 
4658   unsigned Visibility;
4659   unsigned DLLStorageClass;
4660   AttrBuilder RetAttrs;
4661   unsigned CC;
4662   bool HasLinkage;
4663   Type *RetType = nullptr;
4664   LocTy RetTypeLoc = Lex.getLoc();
4665   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4666       ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4667       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4668     return true;
4669 
4670   // Verify that the linkage is ok.
4671   switch ((GlobalValue::LinkageTypes)Linkage) {
4672   case GlobalValue::ExternalLinkage:
4673     break; // always ok.
4674   case GlobalValue::ExternalWeakLinkage:
4675     if (isDefine)
4676       return Error(LinkageLoc, "invalid linkage for function definition");
4677     break;
4678   case GlobalValue::PrivateLinkage:
4679   case GlobalValue::InternalLinkage:
4680   case GlobalValue::AvailableExternallyLinkage:
4681   case GlobalValue::LinkOnceAnyLinkage:
4682   case GlobalValue::LinkOnceODRLinkage:
4683   case GlobalValue::WeakAnyLinkage:
4684   case GlobalValue::WeakODRLinkage:
4685     if (!isDefine)
4686       return Error(LinkageLoc, "invalid linkage for function declaration");
4687     break;
4688   case GlobalValue::AppendingLinkage:
4689   case GlobalValue::CommonLinkage:
4690     return Error(LinkageLoc, "invalid function linkage type");
4691   }
4692 
4693   if (!isValidVisibilityForLinkage(Visibility, Linkage))
4694     return Error(LinkageLoc,
4695                  "symbol with local linkage must have default visibility");
4696 
4697   if (!FunctionType::isValidReturnType(RetType))
4698     return Error(RetTypeLoc, "invalid function return type");
4699 
4700   LocTy NameLoc = Lex.getLoc();
4701 
4702   std::string FunctionName;
4703   if (Lex.getKind() == lltok::GlobalVar) {
4704     FunctionName = Lex.getStrVal();
4705   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
4706     unsigned NameID = Lex.getUIntVal();
4707 
4708     if (NameID != NumberedVals.size())
4709       return TokError("function expected to be numbered '%" +
4710                       Twine(NumberedVals.size()) + "'");
4711   } else {
4712     return TokError("expected function name");
4713   }
4714 
4715   Lex.Lex();
4716 
4717   if (Lex.getKind() != lltok::lparen)
4718     return TokError("expected '(' in function argument list");
4719 
4720   SmallVector<ArgInfo, 8> ArgList;
4721   bool isVarArg;
4722   AttrBuilder FuncAttrs;
4723   std::vector<unsigned> FwdRefAttrGrps;
4724   LocTy BuiltinLoc;
4725   std::string Section;
4726   unsigned Alignment;
4727   std::string GC;
4728   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4729   LocTy UnnamedAddrLoc;
4730   Constant *Prefix = nullptr;
4731   Constant *Prologue = nullptr;
4732   Constant *PersonalityFn = nullptr;
4733   Comdat *C;
4734 
4735   if (ParseArgumentList(ArgList, isVarArg) ||
4736       ParseOptionalUnnamedAddr(UnnamedAddr) ||
4737       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4738                                  BuiltinLoc) ||
4739       (EatIfPresent(lltok::kw_section) &&
4740        ParseStringConstant(Section)) ||
4741       parseOptionalComdat(FunctionName, C) ||
4742       ParseOptionalAlignment(Alignment) ||
4743       (EatIfPresent(lltok::kw_gc) &&
4744        ParseStringConstant(GC)) ||
4745       (EatIfPresent(lltok::kw_prefix) &&
4746        ParseGlobalTypeAndValue(Prefix)) ||
4747       (EatIfPresent(lltok::kw_prologue) &&
4748        ParseGlobalTypeAndValue(Prologue)) ||
4749       (EatIfPresent(lltok::kw_personality) &&
4750        ParseGlobalTypeAndValue(PersonalityFn)))
4751     return true;
4752 
4753   if (FuncAttrs.contains(Attribute::Builtin))
4754     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4755 
4756   // If the alignment was parsed as an attribute, move to the alignment field.
4757   if (FuncAttrs.hasAlignmentAttr()) {
4758     Alignment = FuncAttrs.getAlignment();
4759     FuncAttrs.removeAttribute(Attribute::Alignment);
4760   }
4761 
4762   // Okay, if we got here, the function is syntactically valid.  Convert types
4763   // and do semantic checks.
4764   std::vector<Type*> ParamTypeList;
4765   SmallVector<AttributeSet, 8> Attrs;
4766 
4767   Attrs.push_back(AttributeSet::get(Context, RetAttrs));
4768 
4769   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4770     ParamTypeList.push_back(ArgList[i].Ty);
4771     Attrs.push_back(ArgList[i].Attrs);
4772   }
4773 
4774   Attrs.push_back(AttributeSet::get(Context, FuncAttrs));
4775 
4776   AttributeList PAL = AttributeList::get(Context, Attrs);
4777 
4778   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4779     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4780 
4781   FunctionType *FT =
4782     FunctionType::get(RetType, ParamTypeList, isVarArg);
4783   PointerType *PFT = PointerType::getUnqual(FT);
4784 
4785   Fn = nullptr;
4786   if (!FunctionName.empty()) {
4787     // If this was a definition of a forward reference, remove the definition
4788     // from the forward reference table and fill in the forward ref.
4789     auto FRVI = ForwardRefVals.find(FunctionName);
4790     if (FRVI != ForwardRefVals.end()) {
4791       Fn = M->getFunction(FunctionName);
4792       if (!Fn)
4793         return Error(FRVI->second.second, "invalid forward reference to "
4794                      "function as global value!");
4795       if (Fn->getType() != PFT)
4796         return Error(FRVI->second.second, "invalid forward reference to "
4797                      "function '" + FunctionName + "' with wrong type!");
4798 
4799       ForwardRefVals.erase(FRVI);
4800     } else if ((Fn = M->getFunction(FunctionName))) {
4801       // Reject redefinitions.
4802       return Error(NameLoc, "invalid redefinition of function '" +
4803                    FunctionName + "'");
4804     } else if (M->getNamedValue(FunctionName)) {
4805       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4806     }
4807 
4808   } else {
4809     // If this is a definition of a forward referenced function, make sure the
4810     // types agree.
4811     auto I = ForwardRefValIDs.find(NumberedVals.size());
4812     if (I != ForwardRefValIDs.end()) {
4813       Fn = cast<Function>(I->second.first);
4814       if (Fn->getType() != PFT)
4815         return Error(NameLoc, "type of definition and forward reference of '@" +
4816                      Twine(NumberedVals.size()) + "' disagree");
4817       ForwardRefValIDs.erase(I);
4818     }
4819   }
4820 
4821   if (!Fn)
4822     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4823   else // Move the forward-reference to the correct spot in the module.
4824     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4825 
4826   if (FunctionName.empty())
4827     NumberedVals.push_back(Fn);
4828 
4829   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4830   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4831   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4832   Fn->setCallingConv(CC);
4833   Fn->setAttributes(PAL);
4834   Fn->setUnnamedAddr(UnnamedAddr);
4835   Fn->setAlignment(Alignment);
4836   Fn->setSection(Section);
4837   Fn->setComdat(C);
4838   Fn->setPersonalityFn(PersonalityFn);
4839   if (!GC.empty()) Fn->setGC(GC);
4840   Fn->setPrefixData(Prefix);
4841   Fn->setPrologueData(Prologue);
4842   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4843 
4844   // Add all of the arguments we parsed to the function.
4845   Function::arg_iterator ArgIt = Fn->arg_begin();
4846   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4847     // If the argument has a name, insert it into the argument symbol table.
4848     if (ArgList[i].Name.empty()) continue;
4849 
4850     // Set the name, if it conflicted, it will be auto-renamed.
4851     ArgIt->setName(ArgList[i].Name);
4852 
4853     if (ArgIt->getName() != ArgList[i].Name)
4854       return Error(ArgList[i].Loc, "redefinition of argument '%" +
4855                    ArgList[i].Name + "'");
4856   }
4857 
4858   if (isDefine)
4859     return false;
4860 
4861   // Check the declaration has no block address forward references.
4862   ValID ID;
4863   if (FunctionName.empty()) {
4864     ID.Kind = ValID::t_GlobalID;
4865     ID.UIntVal = NumberedVals.size() - 1;
4866   } else {
4867     ID.Kind = ValID::t_GlobalName;
4868     ID.StrVal = FunctionName;
4869   }
4870   auto Blocks = ForwardRefBlockAddresses.find(ID);
4871   if (Blocks != ForwardRefBlockAddresses.end())
4872     return Error(Blocks->first.Loc,
4873                  "cannot take blockaddress inside a declaration");
4874   return false;
4875 }
4876 
4877 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4878   ValID ID;
4879   if (FunctionNumber == -1) {
4880     ID.Kind = ValID::t_GlobalName;
4881     ID.StrVal = F.getName();
4882   } else {
4883     ID.Kind = ValID::t_GlobalID;
4884     ID.UIntVal = FunctionNumber;
4885   }
4886 
4887   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4888   if (Blocks == P.ForwardRefBlockAddresses.end())
4889     return false;
4890 
4891   for (const auto &I : Blocks->second) {
4892     const ValID &BBID = I.first;
4893     GlobalValue *GV = I.second;
4894 
4895     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4896            "Expected local id or name");
4897     BasicBlock *BB;
4898     if (BBID.Kind == ValID::t_LocalName)
4899       BB = GetBB(BBID.StrVal, BBID.Loc);
4900     else
4901       BB = GetBB(BBID.UIntVal, BBID.Loc);
4902     if (!BB)
4903       return P.Error(BBID.Loc, "referenced value is not a basic block");
4904 
4905     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4906     GV->eraseFromParent();
4907   }
4908 
4909   P.ForwardRefBlockAddresses.erase(Blocks);
4910   return false;
4911 }
4912 
4913 /// ParseFunctionBody
4914 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
4915 bool LLParser::ParseFunctionBody(Function &Fn) {
4916   if (Lex.getKind() != lltok::lbrace)
4917     return TokError("expected '{' in function body");
4918   Lex.Lex();  // eat the {.
4919 
4920   int FunctionNumber = -1;
4921   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4922 
4923   PerFunctionState PFS(*this, Fn, FunctionNumber);
4924 
4925   // Resolve block addresses and allow basic blocks to be forward-declared
4926   // within this function.
4927   if (PFS.resolveForwardRefBlockAddresses())
4928     return true;
4929   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4930 
4931   // We need at least one basic block.
4932   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4933     return TokError("function body requires at least one basic block");
4934 
4935   while (Lex.getKind() != lltok::rbrace &&
4936          Lex.getKind() != lltok::kw_uselistorder)
4937     if (ParseBasicBlock(PFS)) return true;
4938 
4939   while (Lex.getKind() != lltok::rbrace)
4940     if (ParseUseListOrder(&PFS))
4941       return true;
4942 
4943   // Eat the }.
4944   Lex.Lex();
4945 
4946   // Verify function is ok.
4947   return PFS.FinishFunction();
4948 }
4949 
4950 /// ParseBasicBlock
4951 ///   ::= LabelStr? Instruction*
4952 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4953   // If this basic block starts out with a name, remember it.
4954   std::string Name;
4955   LocTy NameLoc = Lex.getLoc();
4956   if (Lex.getKind() == lltok::LabelStr) {
4957     Name = Lex.getStrVal();
4958     Lex.Lex();
4959   }
4960 
4961   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4962   if (!BB)
4963     return Error(NameLoc,
4964                  "unable to create block named '" + Name + "'");
4965 
4966   std::string NameStr;
4967 
4968   // Parse the instructions in this block until we get a terminator.
4969   Instruction *Inst;
4970   do {
4971     // This instruction may have three possibilities for a name: a) none
4972     // specified, b) name specified "%foo =", c) number specified: "%4 =".
4973     LocTy NameLoc = Lex.getLoc();
4974     int NameID = -1;
4975     NameStr = "";
4976 
4977     if (Lex.getKind() == lltok::LocalVarID) {
4978       NameID = Lex.getUIntVal();
4979       Lex.Lex();
4980       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4981         return true;
4982     } else if (Lex.getKind() == lltok::LocalVar) {
4983       NameStr = Lex.getStrVal();
4984       Lex.Lex();
4985       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4986         return true;
4987     }
4988 
4989     switch (ParseInstruction(Inst, BB, PFS)) {
4990     default: llvm_unreachable("Unknown ParseInstruction result!");
4991     case InstError: return true;
4992     case InstNormal:
4993       BB->getInstList().push_back(Inst);
4994 
4995       // With a normal result, we check to see if the instruction is followed by
4996       // a comma and metadata.
4997       if (EatIfPresent(lltok::comma))
4998         if (ParseInstructionMetadata(*Inst))
4999           return true;
5000       break;
5001     case InstExtraComma:
5002       BB->getInstList().push_back(Inst);
5003 
5004       // If the instruction parser ate an extra comma at the end of it, it
5005       // *must* be followed by metadata.
5006       if (ParseInstructionMetadata(*Inst))
5007         return true;
5008       break;
5009     }
5010 
5011     // Set the name on the instruction.
5012     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5013   } while (!isa<TerminatorInst>(Inst));
5014 
5015   return false;
5016 }
5017 
5018 //===----------------------------------------------------------------------===//
5019 // Instruction Parsing.
5020 //===----------------------------------------------------------------------===//
5021 
5022 /// ParseInstruction - Parse one of the many different instructions.
5023 ///
5024 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5025                                PerFunctionState &PFS) {
5026   lltok::Kind Token = Lex.getKind();
5027   if (Token == lltok::Eof)
5028     return TokError("found end of file when expecting more instructions");
5029   LocTy Loc = Lex.getLoc();
5030   unsigned KeywordVal = Lex.getUIntVal();
5031   Lex.Lex();  // Eat the keyword.
5032 
5033   switch (Token) {
5034   default:                    return Error(Loc, "expected instruction opcode");
5035   // Terminator Instructions.
5036   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5037   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
5038   case lltok::kw_br:          return ParseBr(Inst, PFS);
5039   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
5040   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
5041   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
5042   case lltok::kw_resume:      return ParseResume(Inst, PFS);
5043   case lltok::kw_cleanupret:  return ParseCleanupRet(Inst, PFS);
5044   case lltok::kw_catchret:    return ParseCatchRet(Inst, PFS);
5045   case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5046   case lltok::kw_catchpad:    return ParseCatchPad(Inst, PFS);
5047   case lltok::kw_cleanuppad:  return ParseCleanupPad(Inst, PFS);
5048   // Binary Operators.
5049   case lltok::kw_add:
5050   case lltok::kw_sub:
5051   case lltok::kw_mul:
5052   case lltok::kw_shl: {
5053     bool NUW = EatIfPresent(lltok::kw_nuw);
5054     bool NSW = EatIfPresent(lltok::kw_nsw);
5055     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5056 
5057     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5058 
5059     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5060     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5061     return false;
5062   }
5063   case lltok::kw_fadd:
5064   case lltok::kw_fsub:
5065   case lltok::kw_fmul:
5066   case lltok::kw_fdiv:
5067   case lltok::kw_frem: {
5068     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5069     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5070     if (Res != 0)
5071       return Res;
5072     if (FMF.any())
5073       Inst->setFastMathFlags(FMF);
5074     return 0;
5075   }
5076 
5077   case lltok::kw_sdiv:
5078   case lltok::kw_udiv:
5079   case lltok::kw_lshr:
5080   case lltok::kw_ashr: {
5081     bool Exact = EatIfPresent(lltok::kw_exact);
5082 
5083     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5084     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5085     return false;
5086   }
5087 
5088   case lltok::kw_urem:
5089   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5090   case lltok::kw_and:
5091   case lltok::kw_or:
5092   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
5093   case lltok::kw_icmp:   return ParseCompare(Inst, PFS, KeywordVal);
5094   case lltok::kw_fcmp: {
5095     FastMathFlags FMF = EatFastMathFlagsIfPresent();
5096     int Res = ParseCompare(Inst, PFS, KeywordVal);
5097     if (Res != 0)
5098       return Res;
5099     if (FMF.any())
5100       Inst->setFastMathFlags(FMF);
5101     return 0;
5102   }
5103 
5104   // Casts.
5105   case lltok::kw_trunc:
5106   case lltok::kw_zext:
5107   case lltok::kw_sext:
5108   case lltok::kw_fptrunc:
5109   case lltok::kw_fpext:
5110   case lltok::kw_bitcast:
5111   case lltok::kw_addrspacecast:
5112   case lltok::kw_uitofp:
5113   case lltok::kw_sitofp:
5114   case lltok::kw_fptoui:
5115   case lltok::kw_fptosi:
5116   case lltok::kw_inttoptr:
5117   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
5118   // Other.
5119   case lltok::kw_select:         return ParseSelect(Inst, PFS);
5120   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
5121   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5122   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
5123   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
5124   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
5125   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
5126   // Call.
5127   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
5128   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5129   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5130   case lltok::kw_notail:   return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5131   // Memory.
5132   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
5133   case lltok::kw_load:           return ParseLoad(Inst, PFS);
5134   case lltok::kw_store:          return ParseStore(Inst, PFS);
5135   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
5136   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
5137   case lltok::kw_fence:          return ParseFence(Inst, PFS);
5138   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5139   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
5140   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
5141   }
5142 }
5143 
5144 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5145 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5146   if (Opc == Instruction::FCmp) {
5147     switch (Lex.getKind()) {
5148     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5149     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5150     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5151     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5152     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5153     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5154     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5155     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5156     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5157     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5158     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5159     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5160     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5161     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5162     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5163     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5164     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5165     }
5166   } else {
5167     switch (Lex.getKind()) {
5168     default: return TokError("expected icmp predicate (e.g. 'eq')");
5169     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
5170     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
5171     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5172     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5173     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5174     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5175     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5176     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5177     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5178     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5179     }
5180   }
5181   Lex.Lex();
5182   return false;
5183 }
5184 
5185 //===----------------------------------------------------------------------===//
5186 // Terminator Instructions.
5187 //===----------------------------------------------------------------------===//
5188 
5189 /// ParseRet - Parse a return instruction.
5190 ///   ::= 'ret' void (',' !dbg, !1)*
5191 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
5192 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5193                         PerFunctionState &PFS) {
5194   SMLoc TypeLoc = Lex.getLoc();
5195   Type *Ty = nullptr;
5196   if (ParseType(Ty, true /*void allowed*/)) return true;
5197 
5198   Type *ResType = PFS.getFunction().getReturnType();
5199 
5200   if (Ty->isVoidTy()) {
5201     if (!ResType->isVoidTy())
5202       return Error(TypeLoc, "value doesn't match function result type '" +
5203                    getTypeString(ResType) + "'");
5204 
5205     Inst = ReturnInst::Create(Context);
5206     return false;
5207   }
5208 
5209   Value *RV;
5210   if (ParseValue(Ty, RV, PFS)) return true;
5211 
5212   if (ResType != RV->getType())
5213     return Error(TypeLoc, "value doesn't match function result type '" +
5214                  getTypeString(ResType) + "'");
5215 
5216   Inst = ReturnInst::Create(Context, RV);
5217   return false;
5218 }
5219 
5220 /// ParseBr
5221 ///   ::= 'br' TypeAndValue
5222 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5223 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5224   LocTy Loc, Loc2;
5225   Value *Op0;
5226   BasicBlock *Op1, *Op2;
5227   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5228 
5229   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5230     Inst = BranchInst::Create(BB);
5231     return false;
5232   }
5233 
5234   if (Op0->getType() != Type::getInt1Ty(Context))
5235     return Error(Loc, "branch condition must have 'i1' type");
5236 
5237   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5238       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5239       ParseToken(lltok::comma, "expected ',' after true destination") ||
5240       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5241     return true;
5242 
5243   Inst = BranchInst::Create(Op1, Op2, Op0);
5244   return false;
5245 }
5246 
5247 /// ParseSwitch
5248 ///  Instruction
5249 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5250 ///  JumpTable
5251 ///    ::= (TypeAndValue ',' TypeAndValue)*
5252 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5253   LocTy CondLoc, BBLoc;
5254   Value *Cond;
5255   BasicBlock *DefaultBB;
5256   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5257       ParseToken(lltok::comma, "expected ',' after switch condition") ||
5258       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5259       ParseToken(lltok::lsquare, "expected '[' with switch table"))
5260     return true;
5261 
5262   if (!Cond->getType()->isIntegerTy())
5263     return Error(CondLoc, "switch condition must have integer type");
5264 
5265   // Parse the jump table pairs.
5266   SmallPtrSet<Value*, 32> SeenCases;
5267   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5268   while (Lex.getKind() != lltok::rsquare) {
5269     Value *Constant;
5270     BasicBlock *DestBB;
5271 
5272     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5273         ParseToken(lltok::comma, "expected ',' after case value") ||
5274         ParseTypeAndBasicBlock(DestBB, PFS))
5275       return true;
5276 
5277     if (!SeenCases.insert(Constant).second)
5278       return Error(CondLoc, "duplicate case value in switch");
5279     if (!isa<ConstantInt>(Constant))
5280       return Error(CondLoc, "case value is not a constant integer");
5281 
5282     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5283   }
5284 
5285   Lex.Lex();  // Eat the ']'.
5286 
5287   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5288   for (unsigned i = 0, e = Table.size(); i != e; ++i)
5289     SI->addCase(Table[i].first, Table[i].second);
5290   Inst = SI;
5291   return false;
5292 }
5293 
5294 /// ParseIndirectBr
5295 ///  Instruction
5296 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5297 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5298   LocTy AddrLoc;
5299   Value *Address;
5300   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5301       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5302       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5303     return true;
5304 
5305   if (!Address->getType()->isPointerTy())
5306     return Error(AddrLoc, "indirectbr address must have pointer type");
5307 
5308   // Parse the destination list.
5309   SmallVector<BasicBlock*, 16> DestList;
5310 
5311   if (Lex.getKind() != lltok::rsquare) {
5312     BasicBlock *DestBB;
5313     if (ParseTypeAndBasicBlock(DestBB, PFS))
5314       return true;
5315     DestList.push_back(DestBB);
5316 
5317     while (EatIfPresent(lltok::comma)) {
5318       if (ParseTypeAndBasicBlock(DestBB, PFS))
5319         return true;
5320       DestList.push_back(DestBB);
5321     }
5322   }
5323 
5324   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5325     return true;
5326 
5327   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5328   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5329     IBI->addDestination(DestList[i]);
5330   Inst = IBI;
5331   return false;
5332 }
5333 
5334 /// ParseInvoke
5335 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5336 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5337 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5338   LocTy CallLoc = Lex.getLoc();
5339   AttrBuilder RetAttrs, FnAttrs;
5340   std::vector<unsigned> FwdRefAttrGrps;
5341   LocTy NoBuiltinLoc;
5342   unsigned CC;
5343   Type *RetType = nullptr;
5344   LocTy RetTypeLoc;
5345   ValID CalleeID;
5346   SmallVector<ParamInfo, 16> ArgList;
5347   SmallVector<OperandBundleDef, 2> BundleList;
5348 
5349   BasicBlock *NormalBB, *UnwindBB;
5350   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5351       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5352       ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5353       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5354                                  NoBuiltinLoc) ||
5355       ParseOptionalOperandBundles(BundleList, PFS) ||
5356       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5357       ParseTypeAndBasicBlock(NormalBB, PFS) ||
5358       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5359       ParseTypeAndBasicBlock(UnwindBB, PFS))
5360     return true;
5361 
5362   // If RetType is a non-function pointer type, then this is the short syntax
5363   // for the call, which means that RetType is just the return type.  Infer the
5364   // rest of the function argument types from the arguments that are present.
5365   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5366   if (!Ty) {
5367     // Pull out the types of all of the arguments...
5368     std::vector<Type*> ParamTypes;
5369     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5370       ParamTypes.push_back(ArgList[i].V->getType());
5371 
5372     if (!FunctionType::isValidReturnType(RetType))
5373       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5374 
5375     Ty = FunctionType::get(RetType, ParamTypes, false);
5376   }
5377 
5378   CalleeID.FTy = Ty;
5379 
5380   // Look up the callee.
5381   Value *Callee;
5382   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5383     return true;
5384 
5385   // Set up the Attribute for the function.
5386   SmallVector<AttributeSet, 8> Attrs;
5387   Attrs.push_back(AttributeSet::get(Context, RetAttrs));
5388 
5389   SmallVector<Value*, 8> Args;
5390 
5391   // Loop through FunctionType's arguments and ensure they are specified
5392   // correctly.  Also, gather any parameter attributes.
5393   FunctionType::param_iterator I = Ty->param_begin();
5394   FunctionType::param_iterator E = Ty->param_end();
5395   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5396     Type *ExpectedTy = nullptr;
5397     if (I != E) {
5398       ExpectedTy = *I++;
5399     } else if (!Ty->isVarArg()) {
5400       return Error(ArgList[i].Loc, "too many arguments specified");
5401     }
5402 
5403     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5404       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5405                    getTypeString(ExpectedTy) + "'");
5406     Args.push_back(ArgList[i].V);
5407     Attrs.push_back(ArgList[i].Attrs);
5408   }
5409 
5410   if (I != E)
5411     return Error(CallLoc, "not enough parameters specified for call");
5412 
5413   if (FnAttrs.hasAlignmentAttr())
5414     return Error(CallLoc, "invoke instructions may not have an alignment");
5415 
5416   Attrs.push_back(AttributeSet::get(Context, FnAttrs));
5417 
5418   // Finish off the Attribute and check them
5419   AttributeList PAL = AttributeList::get(Context, Attrs);
5420 
5421   InvokeInst *II =
5422       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5423   II->setCallingConv(CC);
5424   II->setAttributes(PAL);
5425   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5426   Inst = II;
5427   return false;
5428 }
5429 
5430 /// ParseResume
5431 ///   ::= 'resume' TypeAndValue
5432 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5433   Value *Exn; LocTy ExnLoc;
5434   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5435     return true;
5436 
5437   ResumeInst *RI = ResumeInst::Create(Exn);
5438   Inst = RI;
5439   return false;
5440 }
5441 
5442 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5443                                   PerFunctionState &PFS) {
5444   if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5445     return true;
5446 
5447   while (Lex.getKind() != lltok::rsquare) {
5448     // If this isn't the first argument, we need a comma.
5449     if (!Args.empty() &&
5450         ParseToken(lltok::comma, "expected ',' in argument list"))
5451       return true;
5452 
5453     // Parse the argument.
5454     LocTy ArgLoc;
5455     Type *ArgTy = nullptr;
5456     if (ParseType(ArgTy, ArgLoc))
5457       return true;
5458 
5459     Value *V;
5460     if (ArgTy->isMetadataTy()) {
5461       if (ParseMetadataAsValue(V, PFS))
5462         return true;
5463     } else {
5464       if (ParseValue(ArgTy, V, PFS))
5465         return true;
5466     }
5467     Args.push_back(V);
5468   }
5469 
5470   Lex.Lex();  // Lex the ']'.
5471   return false;
5472 }
5473 
5474 /// ParseCleanupRet
5475 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5476 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5477   Value *CleanupPad = nullptr;
5478 
5479   if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5480     return true;
5481 
5482   if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5483     return true;
5484 
5485   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5486     return true;
5487 
5488   BasicBlock *UnwindBB = nullptr;
5489   if (Lex.getKind() == lltok::kw_to) {
5490     Lex.Lex();
5491     if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5492       return true;
5493   } else {
5494     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5495       return true;
5496     }
5497   }
5498 
5499   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5500   return false;
5501 }
5502 
5503 /// ParseCatchRet
5504 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
5505 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5506   Value *CatchPad = nullptr;
5507 
5508   if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5509     return true;
5510 
5511   if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5512     return true;
5513 
5514   BasicBlock *BB;
5515   if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5516       ParseTypeAndBasicBlock(BB, PFS))
5517       return true;
5518 
5519   Inst = CatchReturnInst::Create(CatchPad, BB);
5520   return false;
5521 }
5522 
5523 /// ParseCatchSwitch
5524 ///   ::= 'catchswitch' within Parent
5525 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5526   Value *ParentPad;
5527   LocTy BBLoc;
5528 
5529   if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5530     return true;
5531 
5532   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5533       Lex.getKind() != lltok::LocalVarID)
5534     return TokError("expected scope value for catchswitch");
5535 
5536   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5537     return true;
5538 
5539   if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5540     return true;
5541 
5542   SmallVector<BasicBlock *, 32> Table;
5543   do {
5544     BasicBlock *DestBB;
5545     if (ParseTypeAndBasicBlock(DestBB, PFS))
5546       return true;
5547     Table.push_back(DestBB);
5548   } while (EatIfPresent(lltok::comma));
5549 
5550   if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5551     return true;
5552 
5553   if (ParseToken(lltok::kw_unwind,
5554                  "expected 'unwind' after catchswitch scope"))
5555     return true;
5556 
5557   BasicBlock *UnwindBB = nullptr;
5558   if (EatIfPresent(lltok::kw_to)) {
5559     if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5560       return true;
5561   } else {
5562     if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5563       return true;
5564   }
5565 
5566   auto *CatchSwitch =
5567       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5568   for (BasicBlock *DestBB : Table)
5569     CatchSwitch->addHandler(DestBB);
5570   Inst = CatchSwitch;
5571   return false;
5572 }
5573 
5574 /// ParseCatchPad
5575 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5576 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5577   Value *CatchSwitch = nullptr;
5578 
5579   if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5580     return true;
5581 
5582   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5583     return TokError("expected scope value for catchpad");
5584 
5585   if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5586     return true;
5587 
5588   SmallVector<Value *, 8> Args;
5589   if (ParseExceptionArgs(Args, PFS))
5590     return true;
5591 
5592   Inst = CatchPadInst::Create(CatchSwitch, Args);
5593   return false;
5594 }
5595 
5596 /// ParseCleanupPad
5597 ///   ::= 'cleanuppad' within Parent ParamList
5598 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5599   Value *ParentPad = nullptr;
5600 
5601   if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5602     return true;
5603 
5604   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5605       Lex.getKind() != lltok::LocalVarID)
5606     return TokError("expected scope value for cleanuppad");
5607 
5608   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5609     return true;
5610 
5611   SmallVector<Value *, 8> Args;
5612   if (ParseExceptionArgs(Args, PFS))
5613     return true;
5614 
5615   Inst = CleanupPadInst::Create(ParentPad, Args);
5616   return false;
5617 }
5618 
5619 //===----------------------------------------------------------------------===//
5620 // Binary Operators.
5621 //===----------------------------------------------------------------------===//
5622 
5623 /// ParseArithmetic
5624 ///  ::= ArithmeticOps TypeAndValue ',' Value
5625 ///
5626 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
5627 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5628 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5629                                unsigned Opc, unsigned OperandType) {
5630   LocTy Loc; Value *LHS, *RHS;
5631   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5632       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5633       ParseValue(LHS->getType(), RHS, PFS))
5634     return true;
5635 
5636   bool Valid;
5637   switch (OperandType) {
5638   default: llvm_unreachable("Unknown operand type!");
5639   case 0: // int or FP.
5640     Valid = LHS->getType()->isIntOrIntVectorTy() ||
5641             LHS->getType()->isFPOrFPVectorTy();
5642     break;
5643   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5644   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5645   }
5646 
5647   if (!Valid)
5648     return Error(Loc, "invalid operand type for instruction");
5649 
5650   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5651   return false;
5652 }
5653 
5654 /// ParseLogical
5655 ///  ::= ArithmeticOps TypeAndValue ',' Value {
5656 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5657                             unsigned Opc) {
5658   LocTy Loc; Value *LHS, *RHS;
5659   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5660       ParseToken(lltok::comma, "expected ',' in logical operation") ||
5661       ParseValue(LHS->getType(), RHS, PFS))
5662     return true;
5663 
5664   if (!LHS->getType()->isIntOrIntVectorTy())
5665     return Error(Loc,"instruction requires integer or integer vector operands");
5666 
5667   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5668   return false;
5669 }
5670 
5671 /// ParseCompare
5672 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
5673 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
5674 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5675                             unsigned Opc) {
5676   // Parse the integer/fp comparison predicate.
5677   LocTy Loc;
5678   unsigned Pred;
5679   Value *LHS, *RHS;
5680   if (ParseCmpPredicate(Pred, Opc) ||
5681       ParseTypeAndValue(LHS, Loc, PFS) ||
5682       ParseToken(lltok::comma, "expected ',' after compare value") ||
5683       ParseValue(LHS->getType(), RHS, PFS))
5684     return true;
5685 
5686   if (Opc == Instruction::FCmp) {
5687     if (!LHS->getType()->isFPOrFPVectorTy())
5688       return Error(Loc, "fcmp requires floating point operands");
5689     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5690   } else {
5691     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5692     if (!LHS->getType()->isIntOrIntVectorTy() &&
5693         !LHS->getType()->getScalarType()->isPointerTy())
5694       return Error(Loc, "icmp requires integer operands");
5695     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5696   }
5697   return false;
5698 }
5699 
5700 //===----------------------------------------------------------------------===//
5701 // Other Instructions.
5702 //===----------------------------------------------------------------------===//
5703 
5704 
5705 /// ParseCast
5706 ///   ::= CastOpc TypeAndValue 'to' Type
5707 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5708                          unsigned Opc) {
5709   LocTy Loc;
5710   Value *Op;
5711   Type *DestTy = nullptr;
5712   if (ParseTypeAndValue(Op, Loc, PFS) ||
5713       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5714       ParseType(DestTy))
5715     return true;
5716 
5717   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5718     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5719     return Error(Loc, "invalid cast opcode for cast from '" +
5720                  getTypeString(Op->getType()) + "' to '" +
5721                  getTypeString(DestTy) + "'");
5722   }
5723   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5724   return false;
5725 }
5726 
5727 /// ParseSelect
5728 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5729 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5730   LocTy Loc;
5731   Value *Op0, *Op1, *Op2;
5732   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5733       ParseToken(lltok::comma, "expected ',' after select condition") ||
5734       ParseTypeAndValue(Op1, PFS) ||
5735       ParseToken(lltok::comma, "expected ',' after select value") ||
5736       ParseTypeAndValue(Op2, PFS))
5737     return true;
5738 
5739   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5740     return Error(Loc, Reason);
5741 
5742   Inst = SelectInst::Create(Op0, Op1, Op2);
5743   return false;
5744 }
5745 
5746 /// ParseVA_Arg
5747 ///   ::= 'va_arg' TypeAndValue ',' Type
5748 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5749   Value *Op;
5750   Type *EltTy = nullptr;
5751   LocTy TypeLoc;
5752   if (ParseTypeAndValue(Op, PFS) ||
5753       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5754       ParseType(EltTy, TypeLoc))
5755     return true;
5756 
5757   if (!EltTy->isFirstClassType())
5758     return Error(TypeLoc, "va_arg requires operand with first class type");
5759 
5760   Inst = new VAArgInst(Op, EltTy);
5761   return false;
5762 }
5763 
5764 /// ParseExtractElement
5765 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
5766 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5767   LocTy Loc;
5768   Value *Op0, *Op1;
5769   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5770       ParseToken(lltok::comma, "expected ',' after extract value") ||
5771       ParseTypeAndValue(Op1, PFS))
5772     return true;
5773 
5774   if (!ExtractElementInst::isValidOperands(Op0, Op1))
5775     return Error(Loc, "invalid extractelement operands");
5776 
5777   Inst = ExtractElementInst::Create(Op0, Op1);
5778   return false;
5779 }
5780 
5781 /// ParseInsertElement
5782 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5783 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5784   LocTy Loc;
5785   Value *Op0, *Op1, *Op2;
5786   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5787       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5788       ParseTypeAndValue(Op1, PFS) ||
5789       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5790       ParseTypeAndValue(Op2, PFS))
5791     return true;
5792 
5793   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5794     return Error(Loc, "invalid insertelement operands");
5795 
5796   Inst = InsertElementInst::Create(Op0, Op1, Op2);
5797   return false;
5798 }
5799 
5800 /// ParseShuffleVector
5801 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5802 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5803   LocTy Loc;
5804   Value *Op0, *Op1, *Op2;
5805   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5806       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5807       ParseTypeAndValue(Op1, PFS) ||
5808       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5809       ParseTypeAndValue(Op2, PFS))
5810     return true;
5811 
5812   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5813     return Error(Loc, "invalid shufflevector operands");
5814 
5815   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5816   return false;
5817 }
5818 
5819 /// ParsePHI
5820 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5821 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5822   Type *Ty = nullptr;  LocTy TypeLoc;
5823   Value *Op0, *Op1;
5824 
5825   if (ParseType(Ty, TypeLoc) ||
5826       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5827       ParseValue(Ty, Op0, PFS) ||
5828       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5829       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5830       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5831     return true;
5832 
5833   bool AteExtraComma = false;
5834   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5835 
5836   while (true) {
5837     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5838 
5839     if (!EatIfPresent(lltok::comma))
5840       break;
5841 
5842     if (Lex.getKind() == lltok::MetadataVar) {
5843       AteExtraComma = true;
5844       break;
5845     }
5846 
5847     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5848         ParseValue(Ty, Op0, PFS) ||
5849         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5850         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5851         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5852       return true;
5853   }
5854 
5855   if (!Ty->isFirstClassType())
5856     return Error(TypeLoc, "phi node must have first class type");
5857 
5858   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5859   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5860     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5861   Inst = PN;
5862   return AteExtraComma ? InstExtraComma : InstNormal;
5863 }
5864 
5865 /// ParseLandingPad
5866 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5867 /// Clause
5868 ///   ::= 'catch' TypeAndValue
5869 ///   ::= 'filter'
5870 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5871 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5872   Type *Ty = nullptr; LocTy TyLoc;
5873 
5874   if (ParseType(Ty, TyLoc))
5875     return true;
5876 
5877   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5878   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5879 
5880   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5881     LandingPadInst::ClauseType CT;
5882     if (EatIfPresent(lltok::kw_catch))
5883       CT = LandingPadInst::Catch;
5884     else if (EatIfPresent(lltok::kw_filter))
5885       CT = LandingPadInst::Filter;
5886     else
5887       return TokError("expected 'catch' or 'filter' clause type");
5888 
5889     Value *V;
5890     LocTy VLoc;
5891     if (ParseTypeAndValue(V, VLoc, PFS))
5892       return true;
5893 
5894     // A 'catch' type expects a non-array constant. A filter clause expects an
5895     // array constant.
5896     if (CT == LandingPadInst::Catch) {
5897       if (isa<ArrayType>(V->getType()))
5898         Error(VLoc, "'catch' clause has an invalid type");
5899     } else {
5900       if (!isa<ArrayType>(V->getType()))
5901         Error(VLoc, "'filter' clause has an invalid type");
5902     }
5903 
5904     Constant *CV = dyn_cast<Constant>(V);
5905     if (!CV)
5906       return Error(VLoc, "clause argument must be a constant");
5907     LP->addClause(CV);
5908   }
5909 
5910   Inst = LP.release();
5911   return false;
5912 }
5913 
5914 /// ParseCall
5915 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
5916 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5917 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5918 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5919 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5920 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5921 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
5922 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5923 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5924                          CallInst::TailCallKind TCK) {
5925   AttrBuilder RetAttrs, FnAttrs;
5926   std::vector<unsigned> FwdRefAttrGrps;
5927   LocTy BuiltinLoc;
5928   unsigned CC;
5929   Type *RetType = nullptr;
5930   LocTy RetTypeLoc;
5931   ValID CalleeID;
5932   SmallVector<ParamInfo, 16> ArgList;
5933   SmallVector<OperandBundleDef, 2> BundleList;
5934   LocTy CallLoc = Lex.getLoc();
5935 
5936   if (TCK != CallInst::TCK_None &&
5937       ParseToken(lltok::kw_call,
5938                  "expected 'tail call', 'musttail call', or 'notail call'"))
5939     return true;
5940 
5941   FastMathFlags FMF = EatFastMathFlagsIfPresent();
5942 
5943   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5944       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5945       ParseValID(CalleeID) ||
5946       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5947                          PFS.getFunction().isVarArg()) ||
5948       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5949       ParseOptionalOperandBundles(BundleList, PFS))
5950     return true;
5951 
5952   if (FMF.any() && !RetType->isFPOrFPVectorTy())
5953     return Error(CallLoc, "fast-math-flags specified for call without "
5954                           "floating-point scalar or vector return type");
5955 
5956   // If RetType is a non-function pointer type, then this is the short syntax
5957   // for the call, which means that RetType is just the return type.  Infer the
5958   // rest of the function argument types from the arguments that are present.
5959   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5960   if (!Ty) {
5961     // Pull out the types of all of the arguments...
5962     std::vector<Type*> ParamTypes;
5963     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5964       ParamTypes.push_back(ArgList[i].V->getType());
5965 
5966     if (!FunctionType::isValidReturnType(RetType))
5967       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5968 
5969     Ty = FunctionType::get(RetType, ParamTypes, false);
5970   }
5971 
5972   CalleeID.FTy = Ty;
5973 
5974   // Look up the callee.
5975   Value *Callee;
5976   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5977     return true;
5978 
5979   // Set up the Attribute for the function.
5980   SmallVector<AttributeSet, 8> Attrs;
5981   Attrs.push_back(AttributeSet::get(Context, RetAttrs));
5982 
5983   SmallVector<Value*, 8> Args;
5984 
5985   // Loop through FunctionType's arguments and ensure they are specified
5986   // correctly.  Also, gather any parameter attributes.
5987   FunctionType::param_iterator I = Ty->param_begin();
5988   FunctionType::param_iterator E = Ty->param_end();
5989   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5990     Type *ExpectedTy = nullptr;
5991     if (I != E) {
5992       ExpectedTy = *I++;
5993     } else if (!Ty->isVarArg()) {
5994       return Error(ArgList[i].Loc, "too many arguments specified");
5995     }
5996 
5997     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5998       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5999                    getTypeString(ExpectedTy) + "'");
6000     Args.push_back(ArgList[i].V);
6001     Attrs.push_back(ArgList[i].Attrs);
6002   }
6003 
6004   if (I != E)
6005     return Error(CallLoc, "not enough parameters specified for call");
6006 
6007   if (FnAttrs.hasAlignmentAttr())
6008     return Error(CallLoc, "call instructions may not have an alignment");
6009 
6010   Attrs.push_back(AttributeSet::get(Context, FnAttrs));
6011 
6012   // Finish off the Attribute and check them
6013   AttributeList PAL = AttributeList::get(Context, Attrs);
6014 
6015   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6016   CI->setTailCallKind(TCK);
6017   CI->setCallingConv(CC);
6018   if (FMF.any())
6019     CI->setFastMathFlags(FMF);
6020   CI->setAttributes(PAL);
6021   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6022   Inst = CI;
6023   return false;
6024 }
6025 
6026 //===----------------------------------------------------------------------===//
6027 // Memory Instructions.
6028 //===----------------------------------------------------------------------===//
6029 
6030 /// ParseAlloc
6031 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6032 ///       (',' 'align' i32)?
6033 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6034   Value *Size = nullptr;
6035   LocTy SizeLoc, TyLoc, ASLoc;
6036   unsigned Alignment = 0;
6037   unsigned AddrSpace = 0;
6038   Type *Ty = nullptr;
6039 
6040   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6041   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6042 
6043   if (ParseType(Ty, TyLoc)) return true;
6044 
6045   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6046     return Error(TyLoc, "invalid type for alloca");
6047 
6048   bool AteExtraComma = false;
6049   if (EatIfPresent(lltok::comma)) {
6050     if (Lex.getKind() == lltok::kw_align) {
6051       if (ParseOptionalAlignment(Alignment))
6052         return true;
6053       if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6054         return true;
6055     } else if (Lex.getKind() == lltok::kw_addrspace) {
6056       ASLoc = Lex.getLoc();
6057       if (ParseOptionalAddrSpace(AddrSpace))
6058         return true;
6059     } else if (Lex.getKind() == lltok::MetadataVar) {
6060       AteExtraComma = true;
6061     } else {
6062       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6063           ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6064           (!AteExtraComma &&
6065            ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
6066         return true;
6067     }
6068   }
6069 
6070   if (Size && !Size->getType()->isIntegerTy())
6071     return Error(SizeLoc, "element count must have integer type");
6072 
6073   const DataLayout &DL = M->getDataLayout();
6074   unsigned AS = DL.getAllocaAddrSpace();
6075   if (AS != AddrSpace) {
6076     // TODO: In the future it should be possible to specify addrspace per-alloca.
6077     return Error(ASLoc, "address space must match datalayout");
6078   }
6079 
6080   AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
6081   AI->setUsedWithInAlloca(IsInAlloca);
6082   AI->setSwiftError(IsSwiftError);
6083   Inst = AI;
6084   return AteExtraComma ? InstExtraComma : InstNormal;
6085 }
6086 
6087 /// ParseLoad
6088 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6089 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
6090 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
6091 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6092   Value *Val; LocTy Loc;
6093   unsigned Alignment = 0;
6094   bool AteExtraComma = false;
6095   bool isAtomic = false;
6096   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6097   SynchronizationScope Scope = CrossThread;
6098 
6099   if (Lex.getKind() == lltok::kw_atomic) {
6100     isAtomic = true;
6101     Lex.Lex();
6102   }
6103 
6104   bool isVolatile = false;
6105   if (Lex.getKind() == lltok::kw_volatile) {
6106     isVolatile = true;
6107     Lex.Lex();
6108   }
6109 
6110   Type *Ty;
6111   LocTy ExplicitTypeLoc = Lex.getLoc();
6112   if (ParseType(Ty) ||
6113       ParseToken(lltok::comma, "expected comma after load's type") ||
6114       ParseTypeAndValue(Val, Loc, PFS) ||
6115       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6116       ParseOptionalCommaAlign(Alignment, AteExtraComma))
6117     return true;
6118 
6119   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6120     return Error(Loc, "load operand must be a pointer to a first class type");
6121   if (isAtomic && !Alignment)
6122     return Error(Loc, "atomic load must have explicit non-zero alignment");
6123   if (Ordering == AtomicOrdering::Release ||
6124       Ordering == AtomicOrdering::AcquireRelease)
6125     return Error(Loc, "atomic load cannot use Release ordering");
6126 
6127   if (Ty != cast<PointerType>(Val->getType())->getElementType())
6128     return Error(ExplicitTypeLoc,
6129                  "explicit pointee type doesn't match operand's pointee type");
6130 
6131   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
6132   return AteExtraComma ? InstExtraComma : InstNormal;
6133 }
6134 
6135 /// ParseStore
6136 
6137 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6138 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6139 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
6140 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6141   Value *Val, *Ptr; LocTy Loc, PtrLoc;
6142   unsigned Alignment = 0;
6143   bool AteExtraComma = false;
6144   bool isAtomic = false;
6145   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6146   SynchronizationScope Scope = CrossThread;
6147 
6148   if (Lex.getKind() == lltok::kw_atomic) {
6149     isAtomic = true;
6150     Lex.Lex();
6151   }
6152 
6153   bool isVolatile = false;
6154   if (Lex.getKind() == lltok::kw_volatile) {
6155     isVolatile = true;
6156     Lex.Lex();
6157   }
6158 
6159   if (ParseTypeAndValue(Val, Loc, PFS) ||
6160       ParseToken(lltok::comma, "expected ',' after store operand") ||
6161       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6162       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6163       ParseOptionalCommaAlign(Alignment, AteExtraComma))
6164     return true;
6165 
6166   if (!Ptr->getType()->isPointerTy())
6167     return Error(PtrLoc, "store operand must be a pointer");
6168   if (!Val->getType()->isFirstClassType())
6169     return Error(Loc, "store operand must be a first class value");
6170   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6171     return Error(Loc, "stored value and pointer type do not match");
6172   if (isAtomic && !Alignment)
6173     return Error(Loc, "atomic store must have explicit non-zero alignment");
6174   if (Ordering == AtomicOrdering::Acquire ||
6175       Ordering == AtomicOrdering::AcquireRelease)
6176     return Error(Loc, "atomic store cannot use Acquire ordering");
6177 
6178   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
6179   return AteExtraComma ? InstExtraComma : InstNormal;
6180 }
6181 
6182 /// ParseCmpXchg
6183 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6184 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6185 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6186   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6187   bool AteExtraComma = false;
6188   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6189   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6190   SynchronizationScope Scope = CrossThread;
6191   bool isVolatile = false;
6192   bool isWeak = false;
6193 
6194   if (EatIfPresent(lltok::kw_weak))
6195     isWeak = true;
6196 
6197   if (EatIfPresent(lltok::kw_volatile))
6198     isVolatile = true;
6199 
6200   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6201       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6202       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6203       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6204       ParseTypeAndValue(New, NewLoc, PFS) ||
6205       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6206       ParseOrdering(FailureOrdering))
6207     return true;
6208 
6209   if (SuccessOrdering == AtomicOrdering::Unordered ||
6210       FailureOrdering == AtomicOrdering::Unordered)
6211     return TokError("cmpxchg cannot be unordered");
6212   if (isStrongerThan(FailureOrdering, SuccessOrdering))
6213     return TokError("cmpxchg failure argument shall be no stronger than the "
6214                     "success argument");
6215   if (FailureOrdering == AtomicOrdering::Release ||
6216       FailureOrdering == AtomicOrdering::AcquireRelease)
6217     return TokError(
6218         "cmpxchg failure ordering cannot include release semantics");
6219   if (!Ptr->getType()->isPointerTy())
6220     return Error(PtrLoc, "cmpxchg operand must be a pointer");
6221   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6222     return Error(CmpLoc, "compare value and pointer type do not match");
6223   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6224     return Error(NewLoc, "new value and pointer type do not match");
6225   if (!New->getType()->isFirstClassType())
6226     return Error(NewLoc, "cmpxchg operand must be a first class value");
6227   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6228       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
6229   CXI->setVolatile(isVolatile);
6230   CXI->setWeak(isWeak);
6231   Inst = CXI;
6232   return AteExtraComma ? InstExtraComma : InstNormal;
6233 }
6234 
6235 /// ParseAtomicRMW
6236 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6237 ///       'singlethread'? AtomicOrdering
6238 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6239   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6240   bool AteExtraComma = false;
6241   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6242   SynchronizationScope Scope = CrossThread;
6243   bool isVolatile = false;
6244   AtomicRMWInst::BinOp Operation;
6245 
6246   if (EatIfPresent(lltok::kw_volatile))
6247     isVolatile = true;
6248 
6249   switch (Lex.getKind()) {
6250   default: return TokError("expected binary operation in atomicrmw");
6251   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6252   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6253   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6254   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6255   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6256   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6257   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6258   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6259   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6260   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6261   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6262   }
6263   Lex.Lex();  // Eat the operation.
6264 
6265   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6266       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6267       ParseTypeAndValue(Val, ValLoc, PFS) ||
6268       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6269     return true;
6270 
6271   if (Ordering == AtomicOrdering::Unordered)
6272     return TokError("atomicrmw cannot be unordered");
6273   if (!Ptr->getType()->isPointerTy())
6274     return Error(PtrLoc, "atomicrmw operand must be a pointer");
6275   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6276     return Error(ValLoc, "atomicrmw value and pointer type do not match");
6277   if (!Val->getType()->isIntegerTy())
6278     return Error(ValLoc, "atomicrmw operand must be an integer");
6279   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6280   if (Size < 8 || (Size & (Size - 1)))
6281     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6282                          " integer");
6283 
6284   AtomicRMWInst *RMWI =
6285     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6286   RMWI->setVolatile(isVolatile);
6287   Inst = RMWI;
6288   return AteExtraComma ? InstExtraComma : InstNormal;
6289 }
6290 
6291 /// ParseFence
6292 ///   ::= 'fence' 'singlethread'? AtomicOrdering
6293 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6294   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6295   SynchronizationScope Scope = CrossThread;
6296   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6297     return true;
6298 
6299   if (Ordering == AtomicOrdering::Unordered)
6300     return TokError("fence cannot be unordered");
6301   if (Ordering == AtomicOrdering::Monotonic)
6302     return TokError("fence cannot be monotonic");
6303 
6304   Inst = new FenceInst(Context, Ordering, Scope);
6305   return InstNormal;
6306 }
6307 
6308 /// ParseGetElementPtr
6309 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6310 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6311   Value *Ptr = nullptr;
6312   Value *Val = nullptr;
6313   LocTy Loc, EltLoc;
6314 
6315   bool InBounds = EatIfPresent(lltok::kw_inbounds);
6316 
6317   Type *Ty = nullptr;
6318   LocTy ExplicitTypeLoc = Lex.getLoc();
6319   if (ParseType(Ty) ||
6320       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6321       ParseTypeAndValue(Ptr, Loc, PFS))
6322     return true;
6323 
6324   Type *BaseType = Ptr->getType();
6325   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6326   if (!BasePointerType)
6327     return Error(Loc, "base of getelementptr must be a pointer");
6328 
6329   if (Ty != BasePointerType->getElementType())
6330     return Error(ExplicitTypeLoc,
6331                  "explicit pointee type doesn't match operand's pointee type");
6332 
6333   SmallVector<Value*, 16> Indices;
6334   bool AteExtraComma = false;
6335   // GEP returns a vector of pointers if at least one of parameters is a vector.
6336   // All vector parameters should have the same vector width.
6337   unsigned GEPWidth = BaseType->isVectorTy() ?
6338     BaseType->getVectorNumElements() : 0;
6339 
6340   while (EatIfPresent(lltok::comma)) {
6341     if (Lex.getKind() == lltok::MetadataVar) {
6342       AteExtraComma = true;
6343       break;
6344     }
6345     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6346     if (!Val->getType()->getScalarType()->isIntegerTy())
6347       return Error(EltLoc, "getelementptr index must be an integer");
6348 
6349     if (Val->getType()->isVectorTy()) {
6350       unsigned ValNumEl = Val->getType()->getVectorNumElements();
6351       if (GEPWidth && GEPWidth != ValNumEl)
6352         return Error(EltLoc,
6353           "getelementptr vector index has a wrong number of elements");
6354       GEPWidth = ValNumEl;
6355     }
6356     Indices.push_back(Val);
6357   }
6358 
6359   SmallPtrSet<Type*, 4> Visited;
6360   if (!Indices.empty() && !Ty->isSized(&Visited))
6361     return Error(Loc, "base element of getelementptr must be sized");
6362 
6363   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6364     return Error(Loc, "invalid getelementptr indices");
6365   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6366   if (InBounds)
6367     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6368   return AteExtraComma ? InstExtraComma : InstNormal;
6369 }
6370 
6371 /// ParseExtractValue
6372 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
6373 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6374   Value *Val; LocTy Loc;
6375   SmallVector<unsigned, 4> Indices;
6376   bool AteExtraComma;
6377   if (ParseTypeAndValue(Val, Loc, PFS) ||
6378       ParseIndexList(Indices, AteExtraComma))
6379     return true;
6380 
6381   if (!Val->getType()->isAggregateType())
6382     return Error(Loc, "extractvalue operand must be aggregate type");
6383 
6384   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6385     return Error(Loc, "invalid indices for extractvalue");
6386   Inst = ExtractValueInst::Create(Val, Indices);
6387   return AteExtraComma ? InstExtraComma : InstNormal;
6388 }
6389 
6390 /// ParseInsertValue
6391 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6392 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6393   Value *Val0, *Val1; LocTy Loc0, Loc1;
6394   SmallVector<unsigned, 4> Indices;
6395   bool AteExtraComma;
6396   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6397       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6398       ParseTypeAndValue(Val1, Loc1, PFS) ||
6399       ParseIndexList(Indices, AteExtraComma))
6400     return true;
6401 
6402   if (!Val0->getType()->isAggregateType())
6403     return Error(Loc0, "insertvalue operand must be aggregate type");
6404 
6405   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6406   if (!IndexedType)
6407     return Error(Loc0, "invalid indices for insertvalue");
6408   if (IndexedType != Val1->getType())
6409     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6410                            getTypeString(Val1->getType()) + "' instead of '" +
6411                            getTypeString(IndexedType) + "'");
6412   Inst = InsertValueInst::Create(Val0, Val1, Indices);
6413   return AteExtraComma ? InstExtraComma : InstNormal;
6414 }
6415 
6416 //===----------------------------------------------------------------------===//
6417 // Embedded metadata.
6418 //===----------------------------------------------------------------------===//
6419 
6420 /// ParseMDNodeVector
6421 ///   ::= { Element (',' Element)* }
6422 /// Element
6423 ///   ::= 'null' | TypeAndValue
6424 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6425   if (ParseToken(lltok::lbrace, "expected '{' here"))
6426     return true;
6427 
6428   // Check for an empty list.
6429   if (EatIfPresent(lltok::rbrace))
6430     return false;
6431 
6432   do {
6433     // Null is a special case since it is typeless.
6434     if (EatIfPresent(lltok::kw_null)) {
6435       Elts.push_back(nullptr);
6436       continue;
6437     }
6438 
6439     Metadata *MD;
6440     if (ParseMetadata(MD, nullptr))
6441       return true;
6442     Elts.push_back(MD);
6443   } while (EatIfPresent(lltok::comma));
6444 
6445   return ParseToken(lltok::rbrace, "expected end of metadata node");
6446 }
6447 
6448 //===----------------------------------------------------------------------===//
6449 // Use-list order directives.
6450 //===----------------------------------------------------------------------===//
6451 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6452                                 SMLoc Loc) {
6453   if (V->use_empty())
6454     return Error(Loc, "value has no uses");
6455 
6456   unsigned NumUses = 0;
6457   SmallDenseMap<const Use *, unsigned, 16> Order;
6458   for (const Use &U : V->uses()) {
6459     if (++NumUses > Indexes.size())
6460       break;
6461     Order[&U] = Indexes[NumUses - 1];
6462   }
6463   if (NumUses < 2)
6464     return Error(Loc, "value only has one use");
6465   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6466     return Error(Loc, "wrong number of indexes, expected " +
6467                           Twine(std::distance(V->use_begin(), V->use_end())));
6468 
6469   V->sortUseList([&](const Use &L, const Use &R) {
6470     return Order.lookup(&L) < Order.lookup(&R);
6471   });
6472   return false;
6473 }
6474 
6475 /// ParseUseListOrderIndexes
6476 ///   ::= '{' uint32 (',' uint32)+ '}'
6477 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6478   SMLoc Loc = Lex.getLoc();
6479   if (ParseToken(lltok::lbrace, "expected '{' here"))
6480     return true;
6481   if (Lex.getKind() == lltok::rbrace)
6482     return Lex.Error("expected non-empty list of uselistorder indexes");
6483 
6484   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
6485   // indexes should be distinct numbers in the range [0, size-1], and should
6486   // not be in order.
6487   unsigned Offset = 0;
6488   unsigned Max = 0;
6489   bool IsOrdered = true;
6490   assert(Indexes.empty() && "Expected empty order vector");
6491   do {
6492     unsigned Index;
6493     if (ParseUInt32(Index))
6494       return true;
6495 
6496     // Update consistency checks.
6497     Offset += Index - Indexes.size();
6498     Max = std::max(Max, Index);
6499     IsOrdered &= Index == Indexes.size();
6500 
6501     Indexes.push_back(Index);
6502   } while (EatIfPresent(lltok::comma));
6503 
6504   if (ParseToken(lltok::rbrace, "expected '}' here"))
6505     return true;
6506 
6507   if (Indexes.size() < 2)
6508     return Error(Loc, "expected >= 2 uselistorder indexes");
6509   if (Offset != 0 || Max >= Indexes.size())
6510     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6511   if (IsOrdered)
6512     return Error(Loc, "expected uselistorder indexes to change the order");
6513 
6514   return false;
6515 }
6516 
6517 /// ParseUseListOrder
6518 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6519 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6520   SMLoc Loc = Lex.getLoc();
6521   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6522     return true;
6523 
6524   Value *V;
6525   SmallVector<unsigned, 16> Indexes;
6526   if (ParseTypeAndValue(V, PFS) ||
6527       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6528       ParseUseListOrderIndexes(Indexes))
6529     return true;
6530 
6531   return sortUseListOrder(V, Indexes, Loc);
6532 }
6533 
6534 /// ParseUseListOrderBB
6535 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6536 bool LLParser::ParseUseListOrderBB() {
6537   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6538   SMLoc Loc = Lex.getLoc();
6539   Lex.Lex();
6540 
6541   ValID Fn, Label;
6542   SmallVector<unsigned, 16> Indexes;
6543   if (ParseValID(Fn) ||
6544       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6545       ParseValID(Label) ||
6546       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6547       ParseUseListOrderIndexes(Indexes))
6548     return true;
6549 
6550   // Check the function.
6551   GlobalValue *GV;
6552   if (Fn.Kind == ValID::t_GlobalName)
6553     GV = M->getNamedValue(Fn.StrVal);
6554   else if (Fn.Kind == ValID::t_GlobalID)
6555     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6556   else
6557     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6558   if (!GV)
6559     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6560   auto *F = dyn_cast<Function>(GV);
6561   if (!F)
6562     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6563   if (F->isDeclaration())
6564     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6565 
6566   // Check the basic block.
6567   if (Label.Kind == ValID::t_LocalID)
6568     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6569   if (Label.Kind != ValID::t_LocalName)
6570     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6571   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
6572   if (!V)
6573     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6574   if (!isa<BasicBlock>(V))
6575     return Error(Label.Loc, "expected basic block in uselistorder_bb");
6576 
6577   return sortUseListOrder(V, Indexes, Loc);
6578 }
6579