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