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