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