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