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