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