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