1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the parser class for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/AsmParser/LLParser.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueSymbolTable.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/SaveAndRestore.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <cstring>
49 #include <iterator>
50 #include <vector>
51 
52 using namespace llvm;
53 
54 static std::string getTypeString(Type *T) {
55   std::string Result;
56   raw_string_ostream Tmp(Result);
57   Tmp << *T;
58   return Tmp.str();
59 }
60 
61 /// Run: module ::= toplevelentity*
62 bool LLParser::Run(bool UpgradeDebugInfo,
63                    DataLayoutCallbackTy DataLayoutCallback) {
64   // Prime the lexer.
65   Lex.Lex();
66 
67   if (Context.shouldDiscardValueNames())
68     return error(
69         Lex.getLoc(),
70         "Can't read textual IR with a Context that discards named Values");
71 
72   if (M) {
73     if (parseTargetDefinitions())
74       return true;
75 
76     if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
77       M->setDataLayout(*LayoutOverride);
78   }
79 
80   return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
81          validateEndOfIndex();
82 }
83 
84 bool LLParser::parseStandaloneConstantValue(Constant *&C,
85                                             const SlotMapping *Slots) {
86   restoreParsingState(Slots);
87   Lex.Lex();
88 
89   Type *Ty = nullptr;
90   if (parseType(Ty) || parseConstantValue(Ty, C))
91     return true;
92   if (Lex.getKind() != lltok::Eof)
93     return error(Lex.getLoc(), "expected end of string");
94   return false;
95 }
96 
97 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
98                                     const SlotMapping *Slots) {
99   restoreParsingState(Slots);
100   Lex.Lex();
101 
102   Read = 0;
103   SMLoc Start = Lex.getLoc();
104   Ty = nullptr;
105   if (parseType(Ty))
106     return true;
107   SMLoc End = Lex.getLoc();
108   Read = End.getPointer() - Start.getPointer();
109 
110   return false;
111 }
112 
113 void LLParser::restoreParsingState(const SlotMapping *Slots) {
114   if (!Slots)
115     return;
116   NumberedVals = Slots->GlobalValues;
117   NumberedMetadata = Slots->MetadataNodes;
118   for (const auto &I : Slots->NamedTypes)
119     NamedTypes.insert(
120         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
121   for (const auto &I : Slots->Types)
122     NumberedTypes.insert(
123         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
124 }
125 
126 /// validateEndOfModule - Do final validity and sanity checks at the end of the
127 /// module.
128 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
129   if (!M)
130     return false;
131   // Handle any function attribute group forward references.
132   for (const auto &RAG : ForwardRefAttrGroups) {
133     Value *V = RAG.first;
134     const std::vector<unsigned> &Attrs = RAG.second;
135     AttrBuilder B;
136 
137     for (const auto &Attr : Attrs)
138       B.merge(NumberedAttrBuilders[Attr]);
139 
140     if (Function *Fn = dyn_cast<Function>(V)) {
141       AttributeList AS = Fn->getAttributes();
142       AttrBuilder FnAttrs(AS.getFnAttributes());
143       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
144 
145       FnAttrs.merge(B);
146 
147       // If the alignment was parsed as an attribute, move to the alignment
148       // field.
149       if (FnAttrs.hasAlignmentAttr()) {
150         Fn->setAlignment(FnAttrs.getAlignment());
151         FnAttrs.removeAttribute(Attribute::Alignment);
152       }
153 
154       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155                             AttributeSet::get(Context, FnAttrs));
156       Fn->setAttributes(AS);
157     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
158       AttributeList AS = CI->getAttributes();
159       AttrBuilder FnAttrs(AS.getFnAttributes());
160       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
161       FnAttrs.merge(B);
162       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163                             AttributeSet::get(Context, FnAttrs));
164       CI->setAttributes(AS);
165     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
166       AttributeList AS = II->getAttributes();
167       AttrBuilder FnAttrs(AS.getFnAttributes());
168       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
169       FnAttrs.merge(B);
170       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
171                             AttributeSet::get(Context, FnAttrs));
172       II->setAttributes(AS);
173     } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
174       AttributeList AS = CBI->getAttributes();
175       AttrBuilder FnAttrs(AS.getFnAttributes());
176       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
177       FnAttrs.merge(B);
178       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
179                             AttributeSet::get(Context, FnAttrs));
180       CBI->setAttributes(AS);
181     } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
182       AttrBuilder Attrs(GV->getAttributes());
183       Attrs.merge(B);
184       GV->setAttributes(AttributeSet::get(Context,Attrs));
185     } else {
186       llvm_unreachable("invalid object with forward attribute group reference");
187     }
188   }
189 
190   // If there are entries in ForwardRefBlockAddresses at this point, the
191   // function was never defined.
192   if (!ForwardRefBlockAddresses.empty())
193     return error(ForwardRefBlockAddresses.begin()->first.Loc,
194                  "expected function name in blockaddress");
195 
196   for (const auto &NT : NumberedTypes)
197     if (NT.second.second.isValid())
198       return error(NT.second.second,
199                    "use of undefined type '%" + Twine(NT.first) + "'");
200 
201   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
202        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
203     if (I->second.second.isValid())
204       return error(I->second.second,
205                    "use of undefined type named '" + I->getKey() + "'");
206 
207   if (!ForwardRefComdats.empty())
208     return error(ForwardRefComdats.begin()->second,
209                  "use of undefined comdat '$" +
210                      ForwardRefComdats.begin()->first + "'");
211 
212   if (!ForwardRefVals.empty())
213     return error(ForwardRefVals.begin()->second.second,
214                  "use of undefined value '@" + ForwardRefVals.begin()->first +
215                      "'");
216 
217   if (!ForwardRefValIDs.empty())
218     return error(ForwardRefValIDs.begin()->second.second,
219                  "use of undefined value '@" +
220                      Twine(ForwardRefValIDs.begin()->first) + "'");
221 
222   if (!ForwardRefMDNodes.empty())
223     return error(ForwardRefMDNodes.begin()->second.second,
224                  "use of undefined metadata '!" +
225                      Twine(ForwardRefMDNodes.begin()->first) + "'");
226 
227   // Resolve metadata cycles.
228   for (auto &N : NumberedMetadata) {
229     if (N.second && !N.second->isResolved())
230       N.second->resolveCycles();
231   }
232 
233   for (auto *Inst : InstsWithTBAATag) {
234     MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
235     assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
236     auto *UpgradedMD = UpgradeTBAANode(*MD);
237     if (MD != UpgradedMD)
238       Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
239   }
240 
241   // Look for intrinsic functions and CallInst that need to be upgraded
242   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
243     UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
244 
245   // Some types could be renamed during loading if several modules are
246   // loaded in the same LLVMContext (LTO scenario). In this case we should
247   // remangle intrinsics names as well.
248   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
249     Function *F = &*FI++;
250     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
251       F->replaceAllUsesWith(Remangled.getValue());
252       F->eraseFromParent();
253     }
254   }
255 
256   if (UpgradeDebugInfo)
257     llvm::UpgradeDebugInfo(*M);
258 
259   UpgradeModuleFlags(*M);
260   UpgradeSectionAttributes(*M);
261 
262   if (!Slots)
263     return false;
264   // Initialize the slot mapping.
265   // Because by this point we've parsed and validated everything, we can "steal"
266   // the mapping from LLParser as it doesn't need it anymore.
267   Slots->GlobalValues = std::move(NumberedVals);
268   Slots->MetadataNodes = std::move(NumberedMetadata);
269   for (const auto &I : NamedTypes)
270     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
271   for (const auto &I : NumberedTypes)
272     Slots->Types.insert(std::make_pair(I.first, I.second.first));
273 
274   return false;
275 }
276 
277 /// Do final validity and sanity checks at the end of the index.
278 bool LLParser::validateEndOfIndex() {
279   if (!Index)
280     return false;
281 
282   if (!ForwardRefValueInfos.empty())
283     return error(ForwardRefValueInfos.begin()->second.front().second,
284                  "use of undefined summary '^" +
285                      Twine(ForwardRefValueInfos.begin()->first) + "'");
286 
287   if (!ForwardRefAliasees.empty())
288     return error(ForwardRefAliasees.begin()->second.front().second,
289                  "use of undefined summary '^" +
290                      Twine(ForwardRefAliasees.begin()->first) + "'");
291 
292   if (!ForwardRefTypeIds.empty())
293     return error(ForwardRefTypeIds.begin()->second.front().second,
294                  "use of undefined type id summary '^" +
295                      Twine(ForwardRefTypeIds.begin()->first) + "'");
296 
297   return false;
298 }
299 
300 //===----------------------------------------------------------------------===//
301 // Top-Level Entities
302 //===----------------------------------------------------------------------===//
303 
304 bool LLParser::parseTargetDefinitions() {
305   while (true) {
306     switch (Lex.getKind()) {
307     case lltok::kw_target:
308       if (parseTargetDefinition())
309         return true;
310       break;
311     case lltok::kw_source_filename:
312       if (parseSourceFileName())
313         return true;
314       break;
315     default:
316       return false;
317     }
318   }
319 }
320 
321 bool LLParser::parseTopLevelEntities() {
322   // If there is no Module, then parse just the summary index entries.
323   if (!M) {
324     while (true) {
325       switch (Lex.getKind()) {
326       case lltok::Eof:
327         return false;
328       case lltok::SummaryID:
329         if (parseSummaryEntry())
330           return true;
331         break;
332       case lltok::kw_source_filename:
333         if (parseSourceFileName())
334           return true;
335         break;
336       default:
337         // Skip everything else
338         Lex.Lex();
339       }
340     }
341   }
342   while (true) {
343     switch (Lex.getKind()) {
344     default:
345       return tokError("expected top-level entity");
346     case lltok::Eof: return false;
347     case lltok::kw_declare:
348       if (parseDeclare())
349         return true;
350       break;
351     case lltok::kw_define:
352       if (parseDefine())
353         return true;
354       break;
355     case lltok::kw_module:
356       if (parseModuleAsm())
357         return true;
358       break;
359     case lltok::kw_deplibs:
360       if (parseDepLibs())
361         return true;
362       break;
363     case lltok::LocalVarID:
364       if (parseUnnamedType())
365         return true;
366       break;
367     case lltok::LocalVar:
368       if (parseNamedType())
369         return true;
370       break;
371     case lltok::GlobalID:
372       if (parseUnnamedGlobal())
373         return true;
374       break;
375     case lltok::GlobalVar:
376       if (parseNamedGlobal())
377         return true;
378       break;
379     case lltok::ComdatVar:  if (parseComdat()) return true; break;
380     case lltok::exclaim:
381       if (parseStandaloneMetadata())
382         return true;
383       break;
384     case lltok::SummaryID:
385       if (parseSummaryEntry())
386         return true;
387       break;
388     case lltok::MetadataVar:
389       if (parseNamedMetadata())
390         return true;
391       break;
392     case lltok::kw_attributes:
393       if (parseUnnamedAttrGrp())
394         return true;
395       break;
396     case lltok::kw_uselistorder:
397       if (parseUseListOrder())
398         return true;
399       break;
400     case lltok::kw_uselistorder_bb:
401       if (parseUseListOrderBB())
402         return true;
403       break;
404     }
405   }
406 }
407 
408 /// toplevelentity
409 ///   ::= 'module' 'asm' STRINGCONSTANT
410 bool LLParser::parseModuleAsm() {
411   assert(Lex.getKind() == lltok::kw_module);
412   Lex.Lex();
413 
414   std::string AsmStr;
415   if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
416       parseStringConstant(AsmStr))
417     return true;
418 
419   M->appendModuleInlineAsm(AsmStr);
420   return false;
421 }
422 
423 /// toplevelentity
424 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
425 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
426 bool LLParser::parseTargetDefinition() {
427   assert(Lex.getKind() == lltok::kw_target);
428   std::string Str;
429   switch (Lex.Lex()) {
430   default:
431     return tokError("unknown target property");
432   case lltok::kw_triple:
433     Lex.Lex();
434     if (parseToken(lltok::equal, "expected '=' after target triple") ||
435         parseStringConstant(Str))
436       return true;
437     M->setTargetTriple(Str);
438     return false;
439   case lltok::kw_datalayout:
440     Lex.Lex();
441     if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
442         parseStringConstant(Str))
443       return true;
444     M->setDataLayout(Str);
445     return false;
446   }
447 }
448 
449 /// toplevelentity
450 ///   ::= 'source_filename' '=' STRINGCONSTANT
451 bool LLParser::parseSourceFileName() {
452   assert(Lex.getKind() == lltok::kw_source_filename);
453   Lex.Lex();
454   if (parseToken(lltok::equal, "expected '=' after source_filename") ||
455       parseStringConstant(SourceFileName))
456     return true;
457   if (M)
458     M->setSourceFileName(SourceFileName);
459   return false;
460 }
461 
462 /// toplevelentity
463 ///   ::= 'deplibs' '=' '[' ']'
464 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
465 /// FIXME: Remove in 4.0. Currently parse, but ignore.
466 bool LLParser::parseDepLibs() {
467   assert(Lex.getKind() == lltok::kw_deplibs);
468   Lex.Lex();
469   if (parseToken(lltok::equal, "expected '=' after deplibs") ||
470       parseToken(lltok::lsquare, "expected '=' after deplibs"))
471     return true;
472 
473   if (EatIfPresent(lltok::rsquare))
474     return false;
475 
476   do {
477     std::string Str;
478     if (parseStringConstant(Str))
479       return true;
480   } while (EatIfPresent(lltok::comma));
481 
482   return parseToken(lltok::rsquare, "expected ']' at end of list");
483 }
484 
485 /// parseUnnamedType:
486 ///   ::= LocalVarID '=' 'type' type
487 bool LLParser::parseUnnamedType() {
488   LocTy TypeLoc = Lex.getLoc();
489   unsigned TypeID = Lex.getUIntVal();
490   Lex.Lex(); // eat LocalVarID;
491 
492   if (parseToken(lltok::equal, "expected '=' after name") ||
493       parseToken(lltok::kw_type, "expected 'type' after '='"))
494     return true;
495 
496   Type *Result = nullptr;
497   if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
498     return true;
499 
500   if (!isa<StructType>(Result)) {
501     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
502     if (Entry.first)
503       return error(TypeLoc, "non-struct types may not be recursive");
504     Entry.first = Result;
505     Entry.second = SMLoc();
506   }
507 
508   return false;
509 }
510 
511 /// toplevelentity
512 ///   ::= LocalVar '=' 'type' type
513 bool LLParser::parseNamedType() {
514   std::string Name = Lex.getStrVal();
515   LocTy NameLoc = Lex.getLoc();
516   Lex.Lex();  // eat LocalVar.
517 
518   if (parseToken(lltok::equal, "expected '=' after name") ||
519       parseToken(lltok::kw_type, "expected 'type' after name"))
520     return true;
521 
522   Type *Result = nullptr;
523   if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
524     return true;
525 
526   if (!isa<StructType>(Result)) {
527     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
528     if (Entry.first)
529       return error(NameLoc, "non-struct types may not be recursive");
530     Entry.first = Result;
531     Entry.second = SMLoc();
532   }
533 
534   return false;
535 }
536 
537 /// toplevelentity
538 ///   ::= 'declare' FunctionHeader
539 bool LLParser::parseDeclare() {
540   assert(Lex.getKind() == lltok::kw_declare);
541   Lex.Lex();
542 
543   std::vector<std::pair<unsigned, MDNode *>> MDs;
544   while (Lex.getKind() == lltok::MetadataVar) {
545     unsigned MDK;
546     MDNode *N;
547     if (parseMetadataAttachment(MDK, N))
548       return true;
549     MDs.push_back({MDK, N});
550   }
551 
552   Function *F;
553   if (parseFunctionHeader(F, false))
554     return true;
555   for (auto &MD : MDs)
556     F->addMetadata(MD.first, *MD.second);
557   return false;
558 }
559 
560 /// toplevelentity
561 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
562 bool LLParser::parseDefine() {
563   assert(Lex.getKind() == lltok::kw_define);
564   Lex.Lex();
565 
566   Function *F;
567   return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
568          parseFunctionBody(*F);
569 }
570 
571 /// parseGlobalType
572 ///   ::= 'constant'
573 ///   ::= 'global'
574 bool LLParser::parseGlobalType(bool &IsConstant) {
575   if (Lex.getKind() == lltok::kw_constant)
576     IsConstant = true;
577   else if (Lex.getKind() == lltok::kw_global)
578     IsConstant = false;
579   else {
580     IsConstant = false;
581     return tokError("expected 'global' or 'constant'");
582   }
583   Lex.Lex();
584   return false;
585 }
586 
587 bool LLParser::parseOptionalUnnamedAddr(
588     GlobalVariable::UnnamedAddr &UnnamedAddr) {
589   if (EatIfPresent(lltok::kw_unnamed_addr))
590     UnnamedAddr = GlobalValue::UnnamedAddr::Global;
591   else if (EatIfPresent(lltok::kw_local_unnamed_addr))
592     UnnamedAddr = GlobalValue::UnnamedAddr::Local;
593   else
594     UnnamedAddr = GlobalValue::UnnamedAddr::None;
595   return false;
596 }
597 
598 /// parseUnnamedGlobal:
599 ///   OptionalVisibility (ALIAS | IFUNC) ...
600 ///   OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
601 ///   OptionalDLLStorageClass
602 ///                                                     ...   -> global variable
603 ///   GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
604 ///   GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
605 ///   OptionalVisibility
606 ///                OptionalDLLStorageClass
607 ///                                                     ...   -> global variable
608 bool LLParser::parseUnnamedGlobal() {
609   unsigned VarID = NumberedVals.size();
610   std::string Name;
611   LocTy NameLoc = Lex.getLoc();
612 
613   // Handle the GlobalID form.
614   if (Lex.getKind() == lltok::GlobalID) {
615     if (Lex.getUIntVal() != VarID)
616       return error(Lex.getLoc(),
617                    "variable expected to be numbered '%" + Twine(VarID) + "'");
618     Lex.Lex(); // eat GlobalID;
619 
620     if (parseToken(lltok::equal, "expected '=' after name"))
621       return true;
622   }
623 
624   bool HasLinkage;
625   unsigned Linkage, Visibility, DLLStorageClass;
626   bool DSOLocal;
627   GlobalVariable::ThreadLocalMode TLM;
628   GlobalVariable::UnnamedAddr UnnamedAddr;
629   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
630                            DSOLocal) ||
631       parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
632     return true;
633 
634   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
635     return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
636                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
637 
638   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
639                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
640 }
641 
642 /// parseNamedGlobal:
643 ///   GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
644 ///   GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
645 ///                 OptionalVisibility OptionalDLLStorageClass
646 ///                                                     ...   -> global variable
647 bool LLParser::parseNamedGlobal() {
648   assert(Lex.getKind() == lltok::GlobalVar);
649   LocTy NameLoc = Lex.getLoc();
650   std::string Name = Lex.getStrVal();
651   Lex.Lex();
652 
653   bool HasLinkage;
654   unsigned Linkage, Visibility, DLLStorageClass;
655   bool DSOLocal;
656   GlobalVariable::ThreadLocalMode TLM;
657   GlobalVariable::UnnamedAddr UnnamedAddr;
658   if (parseToken(lltok::equal, "expected '=' in global variable") ||
659       parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
660                            DSOLocal) ||
661       parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
662     return true;
663 
664   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
665     return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
666                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
667 
668   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
669                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
670 }
671 
672 bool LLParser::parseComdat() {
673   assert(Lex.getKind() == lltok::ComdatVar);
674   std::string Name = Lex.getStrVal();
675   LocTy NameLoc = Lex.getLoc();
676   Lex.Lex();
677 
678   if (parseToken(lltok::equal, "expected '=' here"))
679     return true;
680 
681   if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
682     return tokError("expected comdat type");
683 
684   Comdat::SelectionKind SK;
685   switch (Lex.getKind()) {
686   default:
687     return tokError("unknown selection kind");
688   case lltok::kw_any:
689     SK = Comdat::Any;
690     break;
691   case lltok::kw_exactmatch:
692     SK = Comdat::ExactMatch;
693     break;
694   case lltok::kw_largest:
695     SK = Comdat::Largest;
696     break;
697   case lltok::kw_noduplicates:
698     SK = Comdat::NoDuplicates;
699     break;
700   case lltok::kw_samesize:
701     SK = Comdat::SameSize;
702     break;
703   }
704   Lex.Lex();
705 
706   // See if the comdat was forward referenced, if so, use the comdat.
707   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
708   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
709   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
710     return error(NameLoc, "redefinition of comdat '$" + Name + "'");
711 
712   Comdat *C;
713   if (I != ComdatSymTab.end())
714     C = &I->second;
715   else
716     C = M->getOrInsertComdat(Name);
717   C->setSelectionKind(SK);
718 
719   return false;
720 }
721 
722 // MDString:
723 //   ::= '!' STRINGCONSTANT
724 bool LLParser::parseMDString(MDString *&Result) {
725   std::string Str;
726   if (parseStringConstant(Str))
727     return true;
728   Result = MDString::get(Context, Str);
729   return false;
730 }
731 
732 // MDNode:
733 //   ::= '!' MDNodeNumber
734 bool LLParser::parseMDNodeID(MDNode *&Result) {
735   // !{ ..., !42, ... }
736   LocTy IDLoc = Lex.getLoc();
737   unsigned MID = 0;
738   if (parseUInt32(MID))
739     return true;
740 
741   // If not a forward reference, just return it now.
742   if (NumberedMetadata.count(MID)) {
743     Result = NumberedMetadata[MID];
744     return false;
745   }
746 
747   // Otherwise, create MDNode forward reference.
748   auto &FwdRef = ForwardRefMDNodes[MID];
749   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
750 
751   Result = FwdRef.first.get();
752   NumberedMetadata[MID].reset(Result);
753   return false;
754 }
755 
756 /// parseNamedMetadata:
757 ///   !foo = !{ !1, !2 }
758 bool LLParser::parseNamedMetadata() {
759   assert(Lex.getKind() == lltok::MetadataVar);
760   std::string Name = Lex.getStrVal();
761   Lex.Lex();
762 
763   if (parseToken(lltok::equal, "expected '=' here") ||
764       parseToken(lltok::exclaim, "Expected '!' here") ||
765       parseToken(lltok::lbrace, "Expected '{' here"))
766     return true;
767 
768   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
769   if (Lex.getKind() != lltok::rbrace)
770     do {
771       MDNode *N = nullptr;
772       // parse DIExpressions inline as a special case. They are still MDNodes,
773       // so they can still appear in named metadata. Remove this logic if they
774       // become plain Metadata.
775       if (Lex.getKind() == lltok::MetadataVar &&
776           Lex.getStrVal() == "DIExpression") {
777         if (parseDIExpression(N, /*IsDistinct=*/false))
778           return true;
779         // DIArgLists should only appear inline in a function, as they may
780         // contain LocalAsMetadata arguments which require a function context.
781       } else if (Lex.getKind() == lltok::MetadataVar &&
782                  Lex.getStrVal() == "DIArgList") {
783         return tokError("found DIArgList outside of function");
784       } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
785                  parseMDNodeID(N)) {
786         return true;
787       }
788       NMD->addOperand(N);
789     } while (EatIfPresent(lltok::comma));
790 
791   return parseToken(lltok::rbrace, "expected end of metadata node");
792 }
793 
794 /// parseStandaloneMetadata:
795 ///   !42 = !{...}
796 bool LLParser::parseStandaloneMetadata() {
797   assert(Lex.getKind() == lltok::exclaim);
798   Lex.Lex();
799   unsigned MetadataID = 0;
800 
801   MDNode *Init;
802   if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
803     return true;
804 
805   // Detect common error, from old metadata syntax.
806   if (Lex.getKind() == lltok::Type)
807     return tokError("unexpected type in metadata definition");
808 
809   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
810   if (Lex.getKind() == lltok::MetadataVar) {
811     if (parseSpecializedMDNode(Init, IsDistinct))
812       return true;
813   } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
814              parseMDTuple(Init, IsDistinct))
815     return true;
816 
817   // See if this was forward referenced, if so, handle it.
818   auto FI = ForwardRefMDNodes.find(MetadataID);
819   if (FI != ForwardRefMDNodes.end()) {
820     FI->second.first->replaceAllUsesWith(Init);
821     ForwardRefMDNodes.erase(FI);
822 
823     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
824   } else {
825     if (NumberedMetadata.count(MetadataID))
826       return tokError("Metadata id is already used");
827     NumberedMetadata[MetadataID].reset(Init);
828   }
829 
830   return false;
831 }
832 
833 // Skips a single module summary entry.
834 bool LLParser::skipModuleSummaryEntry() {
835   // Each module summary entry consists of a tag for the entry
836   // type, followed by a colon, then the fields which may be surrounded by
837   // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
838   // support is in place we will look for the tokens corresponding to the
839   // expected tags.
840   if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
841       Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
842       Lex.getKind() != lltok::kw_blockcount)
843     return tokError(
844         "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
845         "start of summary entry");
846   if (Lex.getKind() == lltok::kw_flags)
847     return parseSummaryIndexFlags();
848   if (Lex.getKind() == lltok::kw_blockcount)
849     return parseBlockCount();
850   Lex.Lex();
851   if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
852       parseToken(lltok::lparen, "expected '(' at start of summary entry"))
853     return true;
854   // Now walk through the parenthesized entry, until the number of open
855   // parentheses goes back down to 0 (the first '(' was parsed above).
856   unsigned NumOpenParen = 1;
857   do {
858     switch (Lex.getKind()) {
859     case lltok::lparen:
860       NumOpenParen++;
861       break;
862     case lltok::rparen:
863       NumOpenParen--;
864       break;
865     case lltok::Eof:
866       return tokError("found end of file while parsing summary entry");
867     default:
868       // Skip everything in between parentheses.
869       break;
870     }
871     Lex.Lex();
872   } while (NumOpenParen > 0);
873   return false;
874 }
875 
876 /// SummaryEntry
877 ///   ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
878 bool LLParser::parseSummaryEntry() {
879   assert(Lex.getKind() == lltok::SummaryID);
880   unsigned SummaryID = Lex.getUIntVal();
881 
882   // For summary entries, colons should be treated as distinct tokens,
883   // not an indication of the end of a label token.
884   Lex.setIgnoreColonInIdentifiers(true);
885 
886   Lex.Lex();
887   if (parseToken(lltok::equal, "expected '=' here"))
888     return true;
889 
890   // If we don't have an index object, skip the summary entry.
891   if (!Index)
892     return skipModuleSummaryEntry();
893 
894   bool result = false;
895   switch (Lex.getKind()) {
896   case lltok::kw_gv:
897     result = parseGVEntry(SummaryID);
898     break;
899   case lltok::kw_module:
900     result = parseModuleEntry(SummaryID);
901     break;
902   case lltok::kw_typeid:
903     result = parseTypeIdEntry(SummaryID);
904     break;
905   case lltok::kw_typeidCompatibleVTable:
906     result = parseTypeIdCompatibleVtableEntry(SummaryID);
907     break;
908   case lltok::kw_flags:
909     result = parseSummaryIndexFlags();
910     break;
911   case lltok::kw_blockcount:
912     result = parseBlockCount();
913     break;
914   default:
915     result = error(Lex.getLoc(), "unexpected summary kind");
916     break;
917   }
918   Lex.setIgnoreColonInIdentifiers(false);
919   return result;
920 }
921 
922 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
923   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
924          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
925 }
926 
927 // If there was an explicit dso_local, update GV. In the absence of an explicit
928 // dso_local we keep the default value.
929 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
930   if (DSOLocal)
931     GV.setDSOLocal(true);
932 }
933 
934 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
935                                               Type *Ty2) {
936   std::string ErrString;
937   raw_string_ostream ErrOS(ErrString);
938   ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
939   return ErrOS.str();
940 }
941 
942 /// parseIndirectSymbol:
943 ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
944 ///                     OptionalVisibility OptionalDLLStorageClass
945 ///                     OptionalThreadLocal OptionalUnnamedAddr
946 ///                     'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
947 ///
948 /// IndirectSymbol
949 ///   ::= TypeAndValue
950 ///
951 /// IndirectSymbolAttr
952 ///   ::= ',' 'partition' StringConstant
953 ///
954 /// Everything through OptionalUnnamedAddr has already been parsed.
955 ///
956 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
957                                    unsigned L, unsigned Visibility,
958                                    unsigned DLLStorageClass, bool DSOLocal,
959                                    GlobalVariable::ThreadLocalMode TLM,
960                                    GlobalVariable::UnnamedAddr UnnamedAddr) {
961   bool IsAlias;
962   if (Lex.getKind() == lltok::kw_alias)
963     IsAlias = true;
964   else if (Lex.getKind() == lltok::kw_ifunc)
965     IsAlias = false;
966   else
967     llvm_unreachable("Not an alias or ifunc!");
968   Lex.Lex();
969 
970   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
971 
972   if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
973     return error(NameLoc, "invalid linkage type for alias");
974 
975   if (!isValidVisibilityForLinkage(Visibility, L))
976     return error(NameLoc,
977                  "symbol with local linkage must have default visibility");
978 
979   Type *Ty;
980   LocTy ExplicitTypeLoc = Lex.getLoc();
981   if (parseType(Ty) ||
982       parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
983     return true;
984 
985   Constant *Aliasee;
986   LocTy AliaseeLoc = Lex.getLoc();
987   if (Lex.getKind() != lltok::kw_bitcast &&
988       Lex.getKind() != lltok::kw_getelementptr &&
989       Lex.getKind() != lltok::kw_addrspacecast &&
990       Lex.getKind() != lltok::kw_inttoptr) {
991     if (parseGlobalTypeAndValue(Aliasee))
992       return true;
993   } else {
994     // The bitcast dest type is not present, it is implied by the dest type.
995     ValID ID;
996     if (parseValID(ID))
997       return true;
998     if (ID.Kind != ValID::t_Constant)
999       return error(AliaseeLoc, "invalid aliasee");
1000     Aliasee = ID.ConstantVal;
1001   }
1002 
1003   Type *AliaseeType = Aliasee->getType();
1004   auto *PTy = dyn_cast<PointerType>(AliaseeType);
1005   if (!PTy)
1006     return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1007   unsigned AddrSpace = PTy->getAddressSpace();
1008 
1009   if (IsAlias && Ty != PTy->getElementType()) {
1010     return error(
1011         ExplicitTypeLoc,
1012         typeComparisonErrorMessage(
1013             "explicit pointee type doesn't match operand's pointee type", Ty,
1014             PTy->getElementType()));
1015   }
1016 
1017   if (!IsAlias && !PTy->getElementType()->isFunctionTy()) {
1018     return error(ExplicitTypeLoc,
1019                  "explicit pointee type should be a function type");
1020   }
1021 
1022   GlobalValue *GVal = nullptr;
1023 
1024   // See if the alias was forward referenced, if so, prepare to replace the
1025   // forward reference.
1026   if (!Name.empty()) {
1027     GVal = M->getNamedValue(Name);
1028     if (GVal) {
1029       if (!ForwardRefVals.erase(Name))
1030         return error(NameLoc, "redefinition of global '@" + Name + "'");
1031     }
1032   } else {
1033     auto I = ForwardRefValIDs.find(NumberedVals.size());
1034     if (I != ForwardRefValIDs.end()) {
1035       GVal = I->second.first;
1036       ForwardRefValIDs.erase(I);
1037     }
1038   }
1039 
1040   // Okay, create the alias but do not insert it into the module yet.
1041   std::unique_ptr<GlobalIndirectSymbol> GA;
1042   if (IsAlias)
1043     GA.reset(GlobalAlias::create(Ty, AddrSpace,
1044                                  (GlobalValue::LinkageTypes)Linkage, Name,
1045                                  Aliasee, /*Parent*/ nullptr));
1046   else
1047     GA.reset(GlobalIFunc::create(Ty, AddrSpace,
1048                                  (GlobalValue::LinkageTypes)Linkage, Name,
1049                                  Aliasee, /*Parent*/ nullptr));
1050   GA->setThreadLocalMode(TLM);
1051   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1052   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1053   GA->setUnnamedAddr(UnnamedAddr);
1054   maybeSetDSOLocal(DSOLocal, *GA);
1055 
1056   // At this point we've parsed everything except for the IndirectSymbolAttrs.
1057   // Now parse them if there are any.
1058   while (Lex.getKind() == lltok::comma) {
1059     Lex.Lex();
1060 
1061     if (Lex.getKind() == lltok::kw_partition) {
1062       Lex.Lex();
1063       GA->setPartition(Lex.getStrVal());
1064       if (parseToken(lltok::StringConstant, "expected partition string"))
1065         return true;
1066     } else {
1067       return tokError("unknown alias or ifunc property!");
1068     }
1069   }
1070 
1071   if (Name.empty())
1072     NumberedVals.push_back(GA.get());
1073 
1074   if (GVal) {
1075     // Verify that types agree.
1076     if (GVal->getType() != GA->getType())
1077       return error(
1078           ExplicitTypeLoc,
1079           "forward reference and definition of alias have different types");
1080 
1081     // If they agree, just RAUW the old value with the alias and remove the
1082     // forward ref info.
1083     GVal->replaceAllUsesWith(GA.get());
1084     GVal->eraseFromParent();
1085   }
1086 
1087   // Insert into the module, we know its name won't collide now.
1088   if (IsAlias)
1089     M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1090   else
1091     M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1092   assert(GA->getName() == Name && "Should not be a name conflict!");
1093 
1094   // The module owns this now
1095   GA.release();
1096 
1097   return false;
1098 }
1099 
1100 /// parseGlobal
1101 ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1102 ///       OptionalVisibility OptionalDLLStorageClass
1103 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1104 ///       OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1105 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1106 ///       OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1107 ///       OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1108 ///       Const OptionalAttrs
1109 ///
1110 /// Everything up to and including OptionalUnnamedAddr has been parsed
1111 /// already.
1112 ///
1113 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1114                            unsigned Linkage, bool HasLinkage,
1115                            unsigned Visibility, unsigned DLLStorageClass,
1116                            bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1117                            GlobalVariable::UnnamedAddr UnnamedAddr) {
1118   if (!isValidVisibilityForLinkage(Visibility, Linkage))
1119     return error(NameLoc,
1120                  "symbol with local linkage must have default visibility");
1121 
1122   unsigned AddrSpace;
1123   bool IsConstant, IsExternallyInitialized;
1124   LocTy IsExternallyInitializedLoc;
1125   LocTy TyLoc;
1126 
1127   Type *Ty = nullptr;
1128   if (parseOptionalAddrSpace(AddrSpace) ||
1129       parseOptionalToken(lltok::kw_externally_initialized,
1130                          IsExternallyInitialized,
1131                          &IsExternallyInitializedLoc) ||
1132       parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1133     return true;
1134 
1135   // If the linkage is specified and is external, then no initializer is
1136   // present.
1137   Constant *Init = nullptr;
1138   if (!HasLinkage ||
1139       !GlobalValue::isValidDeclarationLinkage(
1140           (GlobalValue::LinkageTypes)Linkage)) {
1141     if (parseGlobalValue(Ty, Init))
1142       return true;
1143   }
1144 
1145   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1146     return error(TyLoc, "invalid type for global variable");
1147 
1148   GlobalValue *GVal = nullptr;
1149 
1150   // See if the global was forward referenced, if so, use the global.
1151   if (!Name.empty()) {
1152     GVal = M->getNamedValue(Name);
1153     if (GVal) {
1154       if (!ForwardRefVals.erase(Name))
1155         return error(NameLoc, "redefinition of global '@" + Name + "'");
1156     }
1157   } else {
1158     auto I = ForwardRefValIDs.find(NumberedVals.size());
1159     if (I != ForwardRefValIDs.end()) {
1160       GVal = I->second.first;
1161       ForwardRefValIDs.erase(I);
1162     }
1163   }
1164 
1165   GlobalVariable *GV;
1166   if (!GVal) {
1167     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1168                             Name, nullptr, GlobalVariable::NotThreadLocal,
1169                             AddrSpace);
1170   } else {
1171     if (GVal->getValueType() != Ty)
1172       return error(
1173           TyLoc,
1174           "forward reference and definition of global have different types");
1175 
1176     GV = cast<GlobalVariable>(GVal);
1177 
1178     // Move the forward-reference to the correct spot in the module.
1179     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1180   }
1181 
1182   if (Name.empty())
1183     NumberedVals.push_back(GV);
1184 
1185   // Set the parsed properties on the global.
1186   if (Init)
1187     GV->setInitializer(Init);
1188   GV->setConstant(IsConstant);
1189   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1190   maybeSetDSOLocal(DSOLocal, *GV);
1191   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1192   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1193   GV->setExternallyInitialized(IsExternallyInitialized);
1194   GV->setThreadLocalMode(TLM);
1195   GV->setUnnamedAddr(UnnamedAddr);
1196 
1197   // parse attributes on the global.
1198   while (Lex.getKind() == lltok::comma) {
1199     Lex.Lex();
1200 
1201     if (Lex.getKind() == lltok::kw_section) {
1202       Lex.Lex();
1203       GV->setSection(Lex.getStrVal());
1204       if (parseToken(lltok::StringConstant, "expected global section string"))
1205         return true;
1206     } else if (Lex.getKind() == lltok::kw_partition) {
1207       Lex.Lex();
1208       GV->setPartition(Lex.getStrVal());
1209       if (parseToken(lltok::StringConstant, "expected partition string"))
1210         return true;
1211     } else if (Lex.getKind() == lltok::kw_align) {
1212       MaybeAlign Alignment;
1213       if (parseOptionalAlignment(Alignment))
1214         return true;
1215       GV->setAlignment(Alignment);
1216     } else if (Lex.getKind() == lltok::MetadataVar) {
1217       if (parseGlobalObjectMetadataAttachment(*GV))
1218         return true;
1219     } else {
1220       Comdat *C;
1221       if (parseOptionalComdat(Name, C))
1222         return true;
1223       if (C)
1224         GV->setComdat(C);
1225       else
1226         return tokError("unknown global variable property!");
1227     }
1228   }
1229 
1230   AttrBuilder Attrs;
1231   LocTy BuiltinLoc;
1232   std::vector<unsigned> FwdRefAttrGrps;
1233   if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1234     return true;
1235   if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1236     GV->setAttributes(AttributeSet::get(Context, Attrs));
1237     ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1238   }
1239 
1240   return false;
1241 }
1242 
1243 /// parseUnnamedAttrGrp
1244 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1245 bool LLParser::parseUnnamedAttrGrp() {
1246   assert(Lex.getKind() == lltok::kw_attributes);
1247   LocTy AttrGrpLoc = Lex.getLoc();
1248   Lex.Lex();
1249 
1250   if (Lex.getKind() != lltok::AttrGrpID)
1251     return tokError("expected attribute group id");
1252 
1253   unsigned VarID = Lex.getUIntVal();
1254   std::vector<unsigned> unused;
1255   LocTy BuiltinLoc;
1256   Lex.Lex();
1257 
1258   if (parseToken(lltok::equal, "expected '=' here") ||
1259       parseToken(lltok::lbrace, "expected '{' here") ||
1260       parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1261                                  BuiltinLoc) ||
1262       parseToken(lltok::rbrace, "expected end of attribute group"))
1263     return true;
1264 
1265   if (!NumberedAttrBuilders[VarID].hasAttributes())
1266     return error(AttrGrpLoc, "attribute group has no attributes");
1267 
1268   return false;
1269 }
1270 
1271 /// parseFnAttributeValuePairs
1272 ///   ::= <attr> | <attr> '=' <value>
1273 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1274                                           std::vector<unsigned> &FwdRefAttrGrps,
1275                                           bool inAttrGrp, LocTy &BuiltinLoc) {
1276   bool HaveError = false;
1277 
1278   B.clear();
1279 
1280   while (true) {
1281     lltok::Kind Token = Lex.getKind();
1282     if (Token == lltok::kw_builtin)
1283       BuiltinLoc = Lex.getLoc();
1284     switch (Token) {
1285     default:
1286       if (!inAttrGrp) return HaveError;
1287       return error(Lex.getLoc(), "unterminated attribute group");
1288     case lltok::rbrace:
1289       // Finished.
1290       return false;
1291 
1292     case lltok::AttrGrpID: {
1293       // Allow a function to reference an attribute group:
1294       //
1295       //   define void @foo() #1 { ... }
1296       if (inAttrGrp)
1297         HaveError |= error(
1298             Lex.getLoc(),
1299             "cannot have an attribute group reference in an attribute group");
1300 
1301       unsigned AttrGrpNum = Lex.getUIntVal();
1302       if (inAttrGrp) break;
1303 
1304       // Save the reference to the attribute group. We'll fill it in later.
1305       FwdRefAttrGrps.push_back(AttrGrpNum);
1306       break;
1307     }
1308     // Target-dependent attributes:
1309     case lltok::StringConstant: {
1310       if (parseStringAttribute(B))
1311         return true;
1312       continue;
1313     }
1314 
1315     // Target-independent attributes:
1316     case lltok::kw_align: {
1317       // As a hack, we allow function alignment to be initially parsed as an
1318       // attribute on a function declaration/definition or added to an attribute
1319       // group and later moved to the alignment field.
1320       MaybeAlign Alignment;
1321       if (inAttrGrp) {
1322         Lex.Lex();
1323         uint32_t Value = 0;
1324         if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1325           return true;
1326         Alignment = Align(Value);
1327       } else {
1328         if (parseOptionalAlignment(Alignment))
1329           return true;
1330       }
1331       B.addAlignmentAttr(Alignment);
1332       continue;
1333     }
1334     case lltok::kw_alignstack: {
1335       unsigned Alignment;
1336       if (inAttrGrp) {
1337         Lex.Lex();
1338         if (parseToken(lltok::equal, "expected '=' here") ||
1339             parseUInt32(Alignment))
1340           return true;
1341       } else {
1342         if (parseOptionalStackAlignment(Alignment))
1343           return true;
1344       }
1345       B.addStackAlignmentAttr(Alignment);
1346       continue;
1347     }
1348     case lltok::kw_allocsize: {
1349       unsigned ElemSizeArg;
1350       Optional<unsigned> NumElemsArg;
1351       // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1352       if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1353         return true;
1354       B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1355       continue;
1356     }
1357     case lltok::kw_vscale_range: {
1358       unsigned MinValue, MaxValue;
1359       // inAttrGrp doesn't matter; we only support vscale_range(a[, b])
1360       if (parseVScaleRangeArguments(MinValue, MaxValue))
1361         return true;
1362       B.addVScaleRangeAttr(MinValue, MaxValue);
1363       continue;
1364     }
1365     case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1366     case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1367     case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1368     case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1369     case lltok::kw_hot: B.addAttribute(Attribute::Hot); break;
1370     case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1371     case lltok::kw_inaccessiblememonly:
1372       B.addAttribute(Attribute::InaccessibleMemOnly); break;
1373     case lltok::kw_inaccessiblemem_or_argmemonly:
1374       B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1375     case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1376     case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1377     case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1378     case lltok::kw_mustprogress:
1379       B.addAttribute(Attribute::MustProgress);
1380       break;
1381     case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1382     case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1383     case lltok::kw_nocallback:
1384       B.addAttribute(Attribute::NoCallback);
1385       break;
1386     case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1387     case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1388     case lltok::kw_noimplicitfloat:
1389       B.addAttribute(Attribute::NoImplicitFloat); break;
1390     case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1391     case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1392     case lltok::kw_nomerge: B.addAttribute(Attribute::NoMerge); break;
1393     case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1394     case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1395     case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1396     case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1397     case lltok::kw_noprofile: B.addAttribute(Attribute::NoProfile); break;
1398     case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1399     case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1400     case lltok::kw_null_pointer_is_valid:
1401       B.addAttribute(Attribute::NullPointerIsValid); break;
1402     case lltok::kw_optforfuzzing:
1403       B.addAttribute(Attribute::OptForFuzzing); break;
1404     case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1405     case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1406     case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1407     case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1408     case lltok::kw_returns_twice:
1409       B.addAttribute(Attribute::ReturnsTwice); break;
1410     case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1411     case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1412     case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1413     case lltok::kw_sspstrong:
1414       B.addAttribute(Attribute::StackProtectStrong); break;
1415     case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1416     case lltok::kw_shadowcallstack:
1417       B.addAttribute(Attribute::ShadowCallStack); break;
1418     case lltok::kw_sanitize_address:
1419       B.addAttribute(Attribute::SanitizeAddress); break;
1420     case lltok::kw_sanitize_hwaddress:
1421       B.addAttribute(Attribute::SanitizeHWAddress); break;
1422     case lltok::kw_sanitize_memtag:
1423       B.addAttribute(Attribute::SanitizeMemTag); break;
1424     case lltok::kw_sanitize_thread:
1425       B.addAttribute(Attribute::SanitizeThread); break;
1426     case lltok::kw_sanitize_memory:
1427       B.addAttribute(Attribute::SanitizeMemory); break;
1428     case lltok::kw_speculative_load_hardening:
1429       B.addAttribute(Attribute::SpeculativeLoadHardening);
1430       break;
1431     case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1432     case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1433     case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1434     case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1435     case lltok::kw_preallocated: {
1436       Type *Ty;
1437       if (parsePreallocated(Ty))
1438         return true;
1439       B.addPreallocatedAttr(Ty);
1440       break;
1441     }
1442 
1443     // error handling.
1444     case lltok::kw_inreg:
1445     case lltok::kw_signext:
1446     case lltok::kw_zeroext:
1447       HaveError |=
1448           error(Lex.getLoc(), "invalid use of attribute on a function");
1449       break;
1450     case lltok::kw_byval:
1451     case lltok::kw_dereferenceable:
1452     case lltok::kw_dereferenceable_or_null:
1453     case lltok::kw_inalloca:
1454     case lltok::kw_nest:
1455     case lltok::kw_noalias:
1456     case lltok::kw_noundef:
1457     case lltok::kw_nocapture:
1458     case lltok::kw_nonnull:
1459     case lltok::kw_returned:
1460     case lltok::kw_sret:
1461     case lltok::kw_swifterror:
1462     case lltok::kw_swiftself:
1463     case lltok::kw_swiftasync:
1464     case lltok::kw_immarg:
1465     case lltok::kw_byref:
1466       HaveError |=
1467           error(Lex.getLoc(),
1468                 "invalid use of parameter-only attribute on a function");
1469       break;
1470     }
1471 
1472     // parsePreallocated() consumes token
1473     if (Token != lltok::kw_preallocated)
1474       Lex.Lex();
1475   }
1476 }
1477 
1478 //===----------------------------------------------------------------------===//
1479 // GlobalValue Reference/Resolution Routines.
1480 //===----------------------------------------------------------------------===//
1481 
1482 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1483                                               const std::string &Name) {
1484   if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1485     return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1486                             PTy->getAddressSpace(), Name, M);
1487   else
1488     return new GlobalVariable(*M, PTy->getElementType(), false,
1489                               GlobalValue::ExternalWeakLinkage, nullptr, Name,
1490                               nullptr, GlobalVariable::NotThreadLocal,
1491                               PTy->getAddressSpace());
1492 }
1493 
1494 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1495                                         Value *Val, bool IsCall) {
1496   if (Val->getType() == Ty)
1497     return Val;
1498   // For calls we also accept variables in the program address space.
1499   Type *SuggestedTy = Ty;
1500   if (IsCall && isa<PointerType>(Ty)) {
1501     Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1502         M->getDataLayout().getProgramAddressSpace());
1503     SuggestedTy = TyInProgAS;
1504     if (Val->getType() == TyInProgAS)
1505       return Val;
1506   }
1507   if (Ty->isLabelTy())
1508     error(Loc, "'" + Name + "' is not a basic block");
1509   else
1510     error(Loc, "'" + Name + "' defined with type '" +
1511                    getTypeString(Val->getType()) + "' but expected '" +
1512                    getTypeString(SuggestedTy) + "'");
1513   return nullptr;
1514 }
1515 
1516 /// getGlobalVal - Get a value with the specified name or ID, creating a
1517 /// forward reference record if needed.  This can return null if the value
1518 /// exists but does not have the right type.
1519 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1520                                     LocTy Loc, bool IsCall) {
1521   PointerType *PTy = dyn_cast<PointerType>(Ty);
1522   if (!PTy) {
1523     error(Loc, "global variable reference must have pointer type");
1524     return nullptr;
1525   }
1526 
1527   // Look this name up in the normal function symbol table.
1528   GlobalValue *Val =
1529     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1530 
1531   // If this is a forward reference for the value, see if we already created a
1532   // forward ref record.
1533   if (!Val) {
1534     auto I = ForwardRefVals.find(Name);
1535     if (I != ForwardRefVals.end())
1536       Val = I->second.first;
1537   }
1538 
1539   // If we have the value in the symbol table or fwd-ref table, return it.
1540   if (Val)
1541     return cast_or_null<GlobalValue>(
1542         checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1543 
1544   // Otherwise, create a new forward reference for this value and remember it.
1545   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1546   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1547   return FwdVal;
1548 }
1549 
1550 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1551                                     bool IsCall) {
1552   PointerType *PTy = dyn_cast<PointerType>(Ty);
1553   if (!PTy) {
1554     error(Loc, "global variable reference must have pointer type");
1555     return nullptr;
1556   }
1557 
1558   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1559 
1560   // If this is a forward reference for the value, see if we already created a
1561   // forward ref record.
1562   if (!Val) {
1563     auto I = ForwardRefValIDs.find(ID);
1564     if (I != ForwardRefValIDs.end())
1565       Val = I->second.first;
1566   }
1567 
1568   // If we have the value in the symbol table or fwd-ref table, return it.
1569   if (Val)
1570     return cast_or_null<GlobalValue>(
1571         checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1572 
1573   // Otherwise, create a new forward reference for this value and remember it.
1574   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1575   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1576   return FwdVal;
1577 }
1578 
1579 //===----------------------------------------------------------------------===//
1580 // Comdat Reference/Resolution Routines.
1581 //===----------------------------------------------------------------------===//
1582 
1583 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1584   // Look this name up in the comdat symbol table.
1585   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1586   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1587   if (I != ComdatSymTab.end())
1588     return &I->second;
1589 
1590   // Otherwise, create a new forward reference for this value and remember it.
1591   Comdat *C = M->getOrInsertComdat(Name);
1592   ForwardRefComdats[Name] = Loc;
1593   return C;
1594 }
1595 
1596 //===----------------------------------------------------------------------===//
1597 // Helper Routines.
1598 //===----------------------------------------------------------------------===//
1599 
1600 /// parseToken - If the current token has the specified kind, eat it and return
1601 /// success.  Otherwise, emit the specified error and return failure.
1602 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1603   if (Lex.getKind() != T)
1604     return tokError(ErrMsg);
1605   Lex.Lex();
1606   return false;
1607 }
1608 
1609 /// parseStringConstant
1610 ///   ::= StringConstant
1611 bool LLParser::parseStringConstant(std::string &Result) {
1612   if (Lex.getKind() != lltok::StringConstant)
1613     return tokError("expected string constant");
1614   Result = Lex.getStrVal();
1615   Lex.Lex();
1616   return false;
1617 }
1618 
1619 /// parseUInt32
1620 ///   ::= uint32
1621 bool LLParser::parseUInt32(uint32_t &Val) {
1622   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1623     return tokError("expected integer");
1624   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1625   if (Val64 != unsigned(Val64))
1626     return tokError("expected 32-bit integer (too large)");
1627   Val = Val64;
1628   Lex.Lex();
1629   return false;
1630 }
1631 
1632 /// parseUInt64
1633 ///   ::= uint64
1634 bool LLParser::parseUInt64(uint64_t &Val) {
1635   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1636     return tokError("expected integer");
1637   Val = Lex.getAPSIntVal().getLimitedValue();
1638   Lex.Lex();
1639   return false;
1640 }
1641 
1642 /// parseTLSModel
1643 ///   := 'localdynamic'
1644 ///   := 'initialexec'
1645 ///   := 'localexec'
1646 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1647   switch (Lex.getKind()) {
1648     default:
1649       return tokError("expected localdynamic, initialexec or localexec");
1650     case lltok::kw_localdynamic:
1651       TLM = GlobalVariable::LocalDynamicTLSModel;
1652       break;
1653     case lltok::kw_initialexec:
1654       TLM = GlobalVariable::InitialExecTLSModel;
1655       break;
1656     case lltok::kw_localexec:
1657       TLM = GlobalVariable::LocalExecTLSModel;
1658       break;
1659   }
1660 
1661   Lex.Lex();
1662   return false;
1663 }
1664 
1665 /// parseOptionalThreadLocal
1666 ///   := /*empty*/
1667 ///   := 'thread_local'
1668 ///   := 'thread_local' '(' tlsmodel ')'
1669 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1670   TLM = GlobalVariable::NotThreadLocal;
1671   if (!EatIfPresent(lltok::kw_thread_local))
1672     return false;
1673 
1674   TLM = GlobalVariable::GeneralDynamicTLSModel;
1675   if (Lex.getKind() == lltok::lparen) {
1676     Lex.Lex();
1677     return parseTLSModel(TLM) ||
1678            parseToken(lltok::rparen, "expected ')' after thread local model");
1679   }
1680   return false;
1681 }
1682 
1683 /// parseOptionalAddrSpace
1684 ///   := /*empty*/
1685 ///   := 'addrspace' '(' uint32 ')'
1686 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1687   AddrSpace = DefaultAS;
1688   if (!EatIfPresent(lltok::kw_addrspace))
1689     return false;
1690   return parseToken(lltok::lparen, "expected '(' in address space") ||
1691          parseUInt32(AddrSpace) ||
1692          parseToken(lltok::rparen, "expected ')' in address space");
1693 }
1694 
1695 /// parseStringAttribute
1696 ///   := StringConstant
1697 ///   := StringConstant '=' StringConstant
1698 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1699   std::string Attr = Lex.getStrVal();
1700   Lex.Lex();
1701   std::string Val;
1702   if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1703     return true;
1704   B.addAttribute(Attr, Val);
1705   return false;
1706 }
1707 
1708 /// parseOptionalParamAttrs - parse a potentially empty list of parameter
1709 /// attributes.
1710 bool LLParser::parseOptionalParamAttrs(AttrBuilder &B) {
1711   bool HaveError = false;
1712 
1713   B.clear();
1714 
1715   while (true) {
1716     lltok::Kind Token = Lex.getKind();
1717     switch (Token) {
1718     default:  // End of attributes.
1719       return HaveError;
1720     case lltok::StringConstant: {
1721       if (parseStringAttribute(B))
1722         return true;
1723       continue;
1724     }
1725     case lltok::kw_align: {
1726       MaybeAlign Alignment;
1727       if (parseOptionalAlignment(Alignment, true))
1728         return true;
1729       B.addAlignmentAttr(Alignment);
1730       continue;
1731     }
1732     case lltok::kw_alignstack: {
1733       unsigned Alignment;
1734       if (parseOptionalStackAlignment(Alignment))
1735         return true;
1736       B.addStackAlignmentAttr(Alignment);
1737       continue;
1738     }
1739     case lltok::kw_byval: {
1740       Type *Ty;
1741       if (parseRequiredTypeAttr(Ty, lltok::kw_byval))
1742         return true;
1743       B.addByValAttr(Ty);
1744       continue;
1745     }
1746     case lltok::kw_sret: {
1747       Type *Ty;
1748       if (parseRequiredTypeAttr(Ty, lltok::kw_sret))
1749         return true;
1750       B.addStructRetAttr(Ty);
1751       continue;
1752     }
1753     case lltok::kw_preallocated: {
1754       Type *Ty;
1755       if (parsePreallocated(Ty))
1756         return true;
1757       B.addPreallocatedAttr(Ty);
1758       continue;
1759     }
1760     case lltok::kw_inalloca: {
1761       Type *Ty;
1762       if (parseInalloca(Ty))
1763         return true;
1764       B.addInAllocaAttr(Ty);
1765       continue;
1766     }
1767     case lltok::kw_dereferenceable: {
1768       uint64_t Bytes;
1769       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1770         return true;
1771       B.addDereferenceableAttr(Bytes);
1772       continue;
1773     }
1774     case lltok::kw_dereferenceable_or_null: {
1775       uint64_t Bytes;
1776       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1777         return true;
1778       B.addDereferenceableOrNullAttr(Bytes);
1779       continue;
1780     }
1781     case lltok::kw_byref: {
1782       Type *Ty;
1783       if (parseByRef(Ty))
1784         return true;
1785       B.addByRefAttr(Ty);
1786       continue;
1787     }
1788     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1789     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1790     case lltok::kw_noundef:
1791       B.addAttribute(Attribute::NoUndef);
1792       break;
1793     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1794     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1795     case lltok::kw_nofree:          B.addAttribute(Attribute::NoFree); break;
1796     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1797     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1798     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1799     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1800     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1801     case lltok::kw_swifterror:      B.addAttribute(Attribute::SwiftError); break;
1802     case lltok::kw_swiftself:       B.addAttribute(Attribute::SwiftSelf); break;
1803     case lltok::kw_swiftasync:      B.addAttribute(Attribute::SwiftAsync); break;
1804     case lltok::kw_writeonly:       B.addAttribute(Attribute::WriteOnly); break;
1805     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1806     case lltok::kw_immarg:          B.addAttribute(Attribute::ImmArg); break;
1807 
1808     case lltok::kw_alwaysinline:
1809     case lltok::kw_argmemonly:
1810     case lltok::kw_builtin:
1811     case lltok::kw_inlinehint:
1812     case lltok::kw_jumptable:
1813     case lltok::kw_minsize:
1814     case lltok::kw_mustprogress:
1815     case lltok::kw_naked:
1816     case lltok::kw_nobuiltin:
1817     case lltok::kw_noduplicate:
1818     case lltok::kw_noimplicitfloat:
1819     case lltok::kw_noinline:
1820     case lltok::kw_nonlazybind:
1821     case lltok::kw_nomerge:
1822     case lltok::kw_noprofile:
1823     case lltok::kw_noredzone:
1824     case lltok::kw_noreturn:
1825     case lltok::kw_nocf_check:
1826     case lltok::kw_nounwind:
1827     case lltok::kw_optforfuzzing:
1828     case lltok::kw_optnone:
1829     case lltok::kw_optsize:
1830     case lltok::kw_returns_twice:
1831     case lltok::kw_sanitize_address:
1832     case lltok::kw_sanitize_hwaddress:
1833     case lltok::kw_sanitize_memtag:
1834     case lltok::kw_sanitize_memory:
1835     case lltok::kw_sanitize_thread:
1836     case lltok::kw_speculative_load_hardening:
1837     case lltok::kw_ssp:
1838     case lltok::kw_sspreq:
1839     case lltok::kw_sspstrong:
1840     case lltok::kw_safestack:
1841     case lltok::kw_shadowcallstack:
1842     case lltok::kw_strictfp:
1843     case lltok::kw_uwtable:
1844     case lltok::kw_vscale_range:
1845       HaveError |=
1846           error(Lex.getLoc(), "invalid use of function-only attribute");
1847       break;
1848     }
1849 
1850     Lex.Lex();
1851   }
1852 }
1853 
1854 /// parseOptionalReturnAttrs - parse a potentially empty list of return
1855 /// attributes.
1856 bool LLParser::parseOptionalReturnAttrs(AttrBuilder &B) {
1857   bool HaveError = false;
1858 
1859   B.clear();
1860 
1861   while (true) {
1862     lltok::Kind Token = Lex.getKind();
1863     switch (Token) {
1864     default:  // End of attributes.
1865       return HaveError;
1866     case lltok::StringConstant: {
1867       if (parseStringAttribute(B))
1868         return true;
1869       continue;
1870     }
1871     case lltok::kw_dereferenceable: {
1872       uint64_t Bytes;
1873       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1874         return true;
1875       B.addDereferenceableAttr(Bytes);
1876       continue;
1877     }
1878     case lltok::kw_dereferenceable_or_null: {
1879       uint64_t Bytes;
1880       if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1881         return true;
1882       B.addDereferenceableOrNullAttr(Bytes);
1883       continue;
1884     }
1885     case lltok::kw_align: {
1886       MaybeAlign Alignment;
1887       if (parseOptionalAlignment(Alignment))
1888         return true;
1889       B.addAlignmentAttr(Alignment);
1890       continue;
1891     }
1892     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1893     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1894     case lltok::kw_noundef:
1895       B.addAttribute(Attribute::NoUndef);
1896       break;
1897     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1898     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1899     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1900 
1901     // error handling.
1902     case lltok::kw_byval:
1903     case lltok::kw_inalloca:
1904     case lltok::kw_nest:
1905     case lltok::kw_nocapture:
1906     case lltok::kw_returned:
1907     case lltok::kw_sret:
1908     case lltok::kw_swifterror:
1909     case lltok::kw_swiftself:
1910     case lltok::kw_swiftasync:
1911     case lltok::kw_immarg:
1912     case lltok::kw_byref:
1913       HaveError |=
1914           error(Lex.getLoc(), "invalid use of parameter-only attribute");
1915       break;
1916 
1917     case lltok::kw_alignstack:
1918     case lltok::kw_alwaysinline:
1919     case lltok::kw_argmemonly:
1920     case lltok::kw_builtin:
1921     case lltok::kw_cold:
1922     case lltok::kw_inlinehint:
1923     case lltok::kw_jumptable:
1924     case lltok::kw_minsize:
1925     case lltok::kw_mustprogress:
1926     case lltok::kw_naked:
1927     case lltok::kw_nobuiltin:
1928     case lltok::kw_noduplicate:
1929     case lltok::kw_noimplicitfloat:
1930     case lltok::kw_noinline:
1931     case lltok::kw_nonlazybind:
1932     case lltok::kw_nomerge:
1933     case lltok::kw_noprofile:
1934     case lltok::kw_noredzone:
1935     case lltok::kw_noreturn:
1936     case lltok::kw_nocf_check:
1937     case lltok::kw_nounwind:
1938     case lltok::kw_optforfuzzing:
1939     case lltok::kw_optnone:
1940     case lltok::kw_optsize:
1941     case lltok::kw_returns_twice:
1942     case lltok::kw_sanitize_address:
1943     case lltok::kw_sanitize_hwaddress:
1944     case lltok::kw_sanitize_memtag:
1945     case lltok::kw_sanitize_memory:
1946     case lltok::kw_sanitize_thread:
1947     case lltok::kw_speculative_load_hardening:
1948     case lltok::kw_ssp:
1949     case lltok::kw_sspreq:
1950     case lltok::kw_sspstrong:
1951     case lltok::kw_safestack:
1952     case lltok::kw_shadowcallstack:
1953     case lltok::kw_strictfp:
1954     case lltok::kw_uwtable:
1955     case lltok::kw_vscale_range:
1956       HaveError |=
1957           error(Lex.getLoc(), "invalid use of function-only attribute");
1958       break;
1959     case lltok::kw_readnone:
1960     case lltok::kw_readonly:
1961       HaveError |=
1962           error(Lex.getLoc(), "invalid use of attribute on return type");
1963       break;
1964     case lltok::kw_preallocated:
1965       HaveError |=
1966           error(Lex.getLoc(),
1967                 "invalid use of parameter-only/call site-only attribute");
1968       break;
1969     }
1970 
1971     Lex.Lex();
1972   }
1973 }
1974 
1975 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1976   HasLinkage = true;
1977   switch (Kind) {
1978   default:
1979     HasLinkage = false;
1980     return GlobalValue::ExternalLinkage;
1981   case lltok::kw_private:
1982     return GlobalValue::PrivateLinkage;
1983   case lltok::kw_internal:
1984     return GlobalValue::InternalLinkage;
1985   case lltok::kw_weak:
1986     return GlobalValue::WeakAnyLinkage;
1987   case lltok::kw_weak_odr:
1988     return GlobalValue::WeakODRLinkage;
1989   case lltok::kw_linkonce:
1990     return GlobalValue::LinkOnceAnyLinkage;
1991   case lltok::kw_linkonce_odr:
1992     return GlobalValue::LinkOnceODRLinkage;
1993   case lltok::kw_available_externally:
1994     return GlobalValue::AvailableExternallyLinkage;
1995   case lltok::kw_appending:
1996     return GlobalValue::AppendingLinkage;
1997   case lltok::kw_common:
1998     return GlobalValue::CommonLinkage;
1999   case lltok::kw_extern_weak:
2000     return GlobalValue::ExternalWeakLinkage;
2001   case lltok::kw_external:
2002     return GlobalValue::ExternalLinkage;
2003   }
2004 }
2005 
2006 /// parseOptionalLinkage
2007 ///   ::= /*empty*/
2008 ///   ::= 'private'
2009 ///   ::= 'internal'
2010 ///   ::= 'weak'
2011 ///   ::= 'weak_odr'
2012 ///   ::= 'linkonce'
2013 ///   ::= 'linkonce_odr'
2014 ///   ::= 'available_externally'
2015 ///   ::= 'appending'
2016 ///   ::= 'common'
2017 ///   ::= 'extern_weak'
2018 ///   ::= 'external'
2019 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2020                                     unsigned &Visibility,
2021                                     unsigned &DLLStorageClass, bool &DSOLocal) {
2022   Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2023   if (HasLinkage)
2024     Lex.Lex();
2025   parseOptionalDSOLocal(DSOLocal);
2026   parseOptionalVisibility(Visibility);
2027   parseOptionalDLLStorageClass(DLLStorageClass);
2028 
2029   if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2030     return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2031   }
2032 
2033   return false;
2034 }
2035 
2036 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2037   switch (Lex.getKind()) {
2038   default:
2039     DSOLocal = false;
2040     break;
2041   case lltok::kw_dso_local:
2042     DSOLocal = true;
2043     Lex.Lex();
2044     break;
2045   case lltok::kw_dso_preemptable:
2046     DSOLocal = false;
2047     Lex.Lex();
2048     break;
2049   }
2050 }
2051 
2052 /// parseOptionalVisibility
2053 ///   ::= /*empty*/
2054 ///   ::= 'default'
2055 ///   ::= 'hidden'
2056 ///   ::= 'protected'
2057 ///
2058 void LLParser::parseOptionalVisibility(unsigned &Res) {
2059   switch (Lex.getKind()) {
2060   default:
2061     Res = GlobalValue::DefaultVisibility;
2062     return;
2063   case lltok::kw_default:
2064     Res = GlobalValue::DefaultVisibility;
2065     break;
2066   case lltok::kw_hidden:
2067     Res = GlobalValue::HiddenVisibility;
2068     break;
2069   case lltok::kw_protected:
2070     Res = GlobalValue::ProtectedVisibility;
2071     break;
2072   }
2073   Lex.Lex();
2074 }
2075 
2076 /// parseOptionalDLLStorageClass
2077 ///   ::= /*empty*/
2078 ///   ::= 'dllimport'
2079 ///   ::= 'dllexport'
2080 ///
2081 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2082   switch (Lex.getKind()) {
2083   default:
2084     Res = GlobalValue::DefaultStorageClass;
2085     return;
2086   case lltok::kw_dllimport:
2087     Res = GlobalValue::DLLImportStorageClass;
2088     break;
2089   case lltok::kw_dllexport:
2090     Res = GlobalValue::DLLExportStorageClass;
2091     break;
2092   }
2093   Lex.Lex();
2094 }
2095 
2096 /// parseOptionalCallingConv
2097 ///   ::= /*empty*/
2098 ///   ::= 'ccc'
2099 ///   ::= 'fastcc'
2100 ///   ::= 'intel_ocl_bicc'
2101 ///   ::= 'coldcc'
2102 ///   ::= 'cfguard_checkcc'
2103 ///   ::= 'x86_stdcallcc'
2104 ///   ::= 'x86_fastcallcc'
2105 ///   ::= 'x86_thiscallcc'
2106 ///   ::= 'x86_vectorcallcc'
2107 ///   ::= 'arm_apcscc'
2108 ///   ::= 'arm_aapcscc'
2109 ///   ::= 'arm_aapcs_vfpcc'
2110 ///   ::= 'aarch64_vector_pcs'
2111 ///   ::= 'aarch64_sve_vector_pcs'
2112 ///   ::= 'msp430_intrcc'
2113 ///   ::= 'avr_intrcc'
2114 ///   ::= 'avr_signalcc'
2115 ///   ::= 'ptx_kernel'
2116 ///   ::= 'ptx_device'
2117 ///   ::= 'spir_func'
2118 ///   ::= 'spir_kernel'
2119 ///   ::= 'x86_64_sysvcc'
2120 ///   ::= 'win64cc'
2121 ///   ::= 'webkit_jscc'
2122 ///   ::= 'anyregcc'
2123 ///   ::= 'preserve_mostcc'
2124 ///   ::= 'preserve_allcc'
2125 ///   ::= 'ghccc'
2126 ///   ::= 'swiftcc'
2127 ///   ::= 'swifttailcc'
2128 ///   ::= 'x86_intrcc'
2129 ///   ::= 'hhvmcc'
2130 ///   ::= 'hhvm_ccc'
2131 ///   ::= 'cxx_fast_tlscc'
2132 ///   ::= 'amdgpu_vs'
2133 ///   ::= 'amdgpu_ls'
2134 ///   ::= 'amdgpu_hs'
2135 ///   ::= 'amdgpu_es'
2136 ///   ::= 'amdgpu_gs'
2137 ///   ::= 'amdgpu_ps'
2138 ///   ::= 'amdgpu_cs'
2139 ///   ::= 'amdgpu_kernel'
2140 ///   ::= 'tailcc'
2141 ///   ::= 'cc' UINT
2142 ///
2143 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2144   switch (Lex.getKind()) {
2145   default:                       CC = CallingConv::C; return false;
2146   case lltok::kw_ccc:            CC = CallingConv::C; break;
2147   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
2148   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
2149   case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
2150   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
2151   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
2152   case lltok::kw_x86_regcallcc:  CC = CallingConv::X86_RegCall; break;
2153   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
2154   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
2155   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
2156   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
2157   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
2158   case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
2159   case lltok::kw_aarch64_sve_vector_pcs:
2160     CC = CallingConv::AArch64_SVE_VectorCall;
2161     break;
2162   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
2163   case lltok::kw_avr_intrcc:     CC = CallingConv::AVR_INTR; break;
2164   case lltok::kw_avr_signalcc:   CC = CallingConv::AVR_SIGNAL; break;
2165   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
2166   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
2167   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
2168   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
2169   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
2170   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
2171   case lltok::kw_win64cc:        CC = CallingConv::Win64; break;
2172   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
2173   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
2174   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
2175   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
2176   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
2177   case lltok::kw_swiftcc:        CC = CallingConv::Swift; break;
2178   case lltok::kw_swifttailcc:    CC = CallingConv::SwiftTail; break;
2179   case lltok::kw_x86_intrcc:     CC = CallingConv::X86_INTR; break;
2180   case lltok::kw_hhvmcc:         CC = CallingConv::HHVM; break;
2181   case lltok::kw_hhvm_ccc:       CC = CallingConv::HHVM_C; break;
2182   case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
2183   case lltok::kw_amdgpu_vs:      CC = CallingConv::AMDGPU_VS; break;
2184   case lltok::kw_amdgpu_gfx:     CC = CallingConv::AMDGPU_Gfx; break;
2185   case lltok::kw_amdgpu_ls:      CC = CallingConv::AMDGPU_LS; break;
2186   case lltok::kw_amdgpu_hs:      CC = CallingConv::AMDGPU_HS; break;
2187   case lltok::kw_amdgpu_es:      CC = CallingConv::AMDGPU_ES; break;
2188   case lltok::kw_amdgpu_gs:      CC = CallingConv::AMDGPU_GS; break;
2189   case lltok::kw_amdgpu_ps:      CC = CallingConv::AMDGPU_PS; break;
2190   case lltok::kw_amdgpu_cs:      CC = CallingConv::AMDGPU_CS; break;
2191   case lltok::kw_amdgpu_kernel:  CC = CallingConv::AMDGPU_KERNEL; break;
2192   case lltok::kw_tailcc:         CC = CallingConv::Tail; break;
2193   case lltok::kw_cc: {
2194       Lex.Lex();
2195       return parseUInt32(CC);
2196     }
2197   }
2198 
2199   Lex.Lex();
2200   return false;
2201 }
2202 
2203 /// parseMetadataAttachment
2204 ///   ::= !dbg !42
2205 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2206   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2207 
2208   std::string Name = Lex.getStrVal();
2209   Kind = M->getMDKindID(Name);
2210   Lex.Lex();
2211 
2212   return parseMDNode(MD);
2213 }
2214 
2215 /// parseInstructionMetadata
2216 ///   ::= !dbg !42 (',' !dbg !57)*
2217 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2218   do {
2219     if (Lex.getKind() != lltok::MetadataVar)
2220       return tokError("expected metadata after comma");
2221 
2222     unsigned MDK;
2223     MDNode *N;
2224     if (parseMetadataAttachment(MDK, N))
2225       return true;
2226 
2227     Inst.setMetadata(MDK, N);
2228     if (MDK == LLVMContext::MD_tbaa)
2229       InstsWithTBAATag.push_back(&Inst);
2230 
2231     // If this is the end of the list, we're done.
2232   } while (EatIfPresent(lltok::comma));
2233   return false;
2234 }
2235 
2236 /// parseGlobalObjectMetadataAttachment
2237 ///   ::= !dbg !57
2238 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2239   unsigned MDK;
2240   MDNode *N;
2241   if (parseMetadataAttachment(MDK, N))
2242     return true;
2243 
2244   GO.addMetadata(MDK, *N);
2245   return false;
2246 }
2247 
2248 /// parseOptionalFunctionMetadata
2249 ///   ::= (!dbg !57)*
2250 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2251   while (Lex.getKind() == lltok::MetadataVar)
2252     if (parseGlobalObjectMetadataAttachment(F))
2253       return true;
2254   return false;
2255 }
2256 
2257 /// parseOptionalAlignment
2258 ///   ::= /* empty */
2259 ///   ::= 'align' 4
2260 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2261   Alignment = None;
2262   if (!EatIfPresent(lltok::kw_align))
2263     return false;
2264   LocTy AlignLoc = Lex.getLoc();
2265   uint32_t Value = 0;
2266 
2267   LocTy ParenLoc = Lex.getLoc();
2268   bool HaveParens = false;
2269   if (AllowParens) {
2270     if (EatIfPresent(lltok::lparen))
2271       HaveParens = true;
2272   }
2273 
2274   if (parseUInt32(Value))
2275     return true;
2276 
2277   if (HaveParens && !EatIfPresent(lltok::rparen))
2278     return error(ParenLoc, "expected ')'");
2279 
2280   if (!isPowerOf2_32(Value))
2281     return error(AlignLoc, "alignment is not a power of two");
2282   if (Value > Value::MaximumAlignment)
2283     return error(AlignLoc, "huge alignments are not supported yet");
2284   Alignment = Align(Value);
2285   return false;
2286 }
2287 
2288 /// parseOptionalDerefAttrBytes
2289 ///   ::= /* empty */
2290 ///   ::= AttrKind '(' 4 ')'
2291 ///
2292 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2293 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2294                                            uint64_t &Bytes) {
2295   assert((AttrKind == lltok::kw_dereferenceable ||
2296           AttrKind == lltok::kw_dereferenceable_or_null) &&
2297          "contract!");
2298 
2299   Bytes = 0;
2300   if (!EatIfPresent(AttrKind))
2301     return false;
2302   LocTy ParenLoc = Lex.getLoc();
2303   if (!EatIfPresent(lltok::lparen))
2304     return error(ParenLoc, "expected '('");
2305   LocTy DerefLoc = Lex.getLoc();
2306   if (parseUInt64(Bytes))
2307     return true;
2308   ParenLoc = Lex.getLoc();
2309   if (!EatIfPresent(lltok::rparen))
2310     return error(ParenLoc, "expected ')'");
2311   if (!Bytes)
2312     return error(DerefLoc, "dereferenceable bytes must be non-zero");
2313   return false;
2314 }
2315 
2316 /// parseOptionalCommaAlign
2317 ///   ::=
2318 ///   ::= ',' align 4
2319 ///
2320 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2321 /// end.
2322 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2323                                        bool &AteExtraComma) {
2324   AteExtraComma = false;
2325   while (EatIfPresent(lltok::comma)) {
2326     // Metadata at the end is an early exit.
2327     if (Lex.getKind() == lltok::MetadataVar) {
2328       AteExtraComma = true;
2329       return false;
2330     }
2331 
2332     if (Lex.getKind() != lltok::kw_align)
2333       return error(Lex.getLoc(), "expected metadata or 'align'");
2334 
2335     if (parseOptionalAlignment(Alignment))
2336       return true;
2337   }
2338 
2339   return false;
2340 }
2341 
2342 /// parseOptionalCommaAddrSpace
2343 ///   ::=
2344 ///   ::= ',' addrspace(1)
2345 ///
2346 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2347 /// end.
2348 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2349                                            bool &AteExtraComma) {
2350   AteExtraComma = false;
2351   while (EatIfPresent(lltok::comma)) {
2352     // Metadata at the end is an early exit.
2353     if (Lex.getKind() == lltok::MetadataVar) {
2354       AteExtraComma = true;
2355       return false;
2356     }
2357 
2358     Loc = Lex.getLoc();
2359     if (Lex.getKind() != lltok::kw_addrspace)
2360       return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2361 
2362     if (parseOptionalAddrSpace(AddrSpace))
2363       return true;
2364   }
2365 
2366   return false;
2367 }
2368 
2369 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2370                                        Optional<unsigned> &HowManyArg) {
2371   Lex.Lex();
2372 
2373   auto StartParen = Lex.getLoc();
2374   if (!EatIfPresent(lltok::lparen))
2375     return error(StartParen, "expected '('");
2376 
2377   if (parseUInt32(BaseSizeArg))
2378     return true;
2379 
2380   if (EatIfPresent(lltok::comma)) {
2381     auto HowManyAt = Lex.getLoc();
2382     unsigned HowMany;
2383     if (parseUInt32(HowMany))
2384       return true;
2385     if (HowMany == BaseSizeArg)
2386       return error(HowManyAt,
2387                    "'allocsize' indices can't refer to the same parameter");
2388     HowManyArg = HowMany;
2389   } else
2390     HowManyArg = None;
2391 
2392   auto EndParen = Lex.getLoc();
2393   if (!EatIfPresent(lltok::rparen))
2394     return error(EndParen, "expected ')'");
2395   return false;
2396 }
2397 
2398 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2399                                          unsigned &MaxValue) {
2400   Lex.Lex();
2401 
2402   auto StartParen = Lex.getLoc();
2403   if (!EatIfPresent(lltok::lparen))
2404     return error(StartParen, "expected '('");
2405 
2406   if (parseUInt32(MinValue))
2407     return true;
2408 
2409   if (EatIfPresent(lltok::comma)) {
2410     if (parseUInt32(MaxValue))
2411       return true;
2412   } else
2413     MaxValue = MinValue;
2414 
2415   auto EndParen = Lex.getLoc();
2416   if (!EatIfPresent(lltok::rparen))
2417     return error(EndParen, "expected ')'");
2418   return false;
2419 }
2420 
2421 /// parseScopeAndOrdering
2422 ///   if isAtomic: ::= SyncScope? AtomicOrdering
2423 ///   else: ::=
2424 ///
2425 /// This sets Scope and Ordering to the parsed values.
2426 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2427                                      AtomicOrdering &Ordering) {
2428   if (!IsAtomic)
2429     return false;
2430 
2431   return parseScope(SSID) || parseOrdering(Ordering);
2432 }
2433 
2434 /// parseScope
2435 ///   ::= syncscope("singlethread" | "<target scope>")?
2436 ///
2437 /// This sets synchronization scope ID to the ID of the parsed value.
2438 bool LLParser::parseScope(SyncScope::ID &SSID) {
2439   SSID = SyncScope::System;
2440   if (EatIfPresent(lltok::kw_syncscope)) {
2441     auto StartParenAt = Lex.getLoc();
2442     if (!EatIfPresent(lltok::lparen))
2443       return error(StartParenAt, "Expected '(' in syncscope");
2444 
2445     std::string SSN;
2446     auto SSNAt = Lex.getLoc();
2447     if (parseStringConstant(SSN))
2448       return error(SSNAt, "Expected synchronization scope name");
2449 
2450     auto EndParenAt = Lex.getLoc();
2451     if (!EatIfPresent(lltok::rparen))
2452       return error(EndParenAt, "Expected ')' in syncscope");
2453 
2454     SSID = Context.getOrInsertSyncScopeID(SSN);
2455   }
2456 
2457   return false;
2458 }
2459 
2460 /// parseOrdering
2461 ///   ::= AtomicOrdering
2462 ///
2463 /// This sets Ordering to the parsed value.
2464 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2465   switch (Lex.getKind()) {
2466   default:
2467     return tokError("Expected ordering on atomic instruction");
2468   case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2469   case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2470   // Not specified yet:
2471   // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2472   case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2473   case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2474   case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2475   case lltok::kw_seq_cst:
2476     Ordering = AtomicOrdering::SequentiallyConsistent;
2477     break;
2478   }
2479   Lex.Lex();
2480   return false;
2481 }
2482 
2483 /// parseOptionalStackAlignment
2484 ///   ::= /* empty */
2485 ///   ::= 'alignstack' '(' 4 ')'
2486 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2487   Alignment = 0;
2488   if (!EatIfPresent(lltok::kw_alignstack))
2489     return false;
2490   LocTy ParenLoc = Lex.getLoc();
2491   if (!EatIfPresent(lltok::lparen))
2492     return error(ParenLoc, "expected '('");
2493   LocTy AlignLoc = Lex.getLoc();
2494   if (parseUInt32(Alignment))
2495     return true;
2496   ParenLoc = Lex.getLoc();
2497   if (!EatIfPresent(lltok::rparen))
2498     return error(ParenLoc, "expected ')'");
2499   if (!isPowerOf2_32(Alignment))
2500     return error(AlignLoc, "stack alignment is not a power of two");
2501   return false;
2502 }
2503 
2504 /// parseIndexList - This parses the index list for an insert/extractvalue
2505 /// instruction.  This sets AteExtraComma in the case where we eat an extra
2506 /// comma at the end of the line and find that it is followed by metadata.
2507 /// Clients that don't allow metadata can call the version of this function that
2508 /// only takes one argument.
2509 ///
2510 /// parseIndexList
2511 ///    ::=  (',' uint32)+
2512 ///
2513 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2514                               bool &AteExtraComma) {
2515   AteExtraComma = false;
2516 
2517   if (Lex.getKind() != lltok::comma)
2518     return tokError("expected ',' as start of index list");
2519 
2520   while (EatIfPresent(lltok::comma)) {
2521     if (Lex.getKind() == lltok::MetadataVar) {
2522       if (Indices.empty())
2523         return tokError("expected index");
2524       AteExtraComma = true;
2525       return false;
2526     }
2527     unsigned Idx = 0;
2528     if (parseUInt32(Idx))
2529       return true;
2530     Indices.push_back(Idx);
2531   }
2532 
2533   return false;
2534 }
2535 
2536 //===----------------------------------------------------------------------===//
2537 // Type Parsing.
2538 //===----------------------------------------------------------------------===//
2539 
2540 /// parseType - parse a type.
2541 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2542   SMLoc TypeLoc = Lex.getLoc();
2543   switch (Lex.getKind()) {
2544   default:
2545     return tokError(Msg);
2546   case lltok::Type:
2547     // Type ::= 'float' | 'void' (etc)
2548     Result = Lex.getTyVal();
2549     Lex.Lex();
2550     break;
2551   case lltok::lbrace:
2552     // Type ::= StructType
2553     if (parseAnonStructType(Result, false))
2554       return true;
2555     break;
2556   case lltok::lsquare:
2557     // Type ::= '[' ... ']'
2558     Lex.Lex(); // eat the lsquare.
2559     if (parseArrayVectorType(Result, false))
2560       return true;
2561     break;
2562   case lltok::less: // Either vector or packed struct.
2563     // Type ::= '<' ... '>'
2564     Lex.Lex();
2565     if (Lex.getKind() == lltok::lbrace) {
2566       if (parseAnonStructType(Result, true) ||
2567           parseToken(lltok::greater, "expected '>' at end of packed struct"))
2568         return true;
2569     } else if (parseArrayVectorType(Result, true))
2570       return true;
2571     break;
2572   case lltok::LocalVar: {
2573     // Type ::= %foo
2574     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2575 
2576     // If the type hasn't been defined yet, create a forward definition and
2577     // remember where that forward def'n was seen (in case it never is defined).
2578     if (!Entry.first) {
2579       Entry.first = StructType::create(Context, Lex.getStrVal());
2580       Entry.second = Lex.getLoc();
2581     }
2582     Result = Entry.first;
2583     Lex.Lex();
2584     break;
2585   }
2586 
2587   case lltok::LocalVarID: {
2588     // Type ::= %4
2589     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2590 
2591     // If the type hasn't been defined yet, create a forward definition and
2592     // remember where that forward def'n was seen (in case it never is defined).
2593     if (!Entry.first) {
2594       Entry.first = StructType::create(Context);
2595       Entry.second = Lex.getLoc();
2596     }
2597     Result = Entry.first;
2598     Lex.Lex();
2599     break;
2600   }
2601   }
2602 
2603   if (Result->isPointerTy() && cast<PointerType>(Result)->isOpaque()) {
2604     unsigned AddrSpace;
2605     if (parseOptionalAddrSpace(AddrSpace))
2606       return true;
2607     Result = PointerType::get(getContext(), AddrSpace);
2608   }
2609 
2610   // parse the type suffixes.
2611   while (true) {
2612     switch (Lex.getKind()) {
2613     // End of type.
2614     default:
2615       if (!AllowVoid && Result->isVoidTy())
2616         return error(TypeLoc, "void type only allowed for function results");
2617       return false;
2618 
2619     // Type ::= Type '*'
2620     case lltok::star:
2621       if (Result->isLabelTy())
2622         return tokError("basic block pointers are invalid");
2623       if (Result->isVoidTy())
2624         return tokError("pointers to void are invalid - use i8* instead");
2625       if (!PointerType::isValidElementType(Result))
2626         return tokError("pointer to this type is invalid");
2627       Result = PointerType::getUnqual(Result);
2628       Lex.Lex();
2629       break;
2630 
2631     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2632     case lltok::kw_addrspace: {
2633       if (Result->isLabelTy())
2634         return tokError("basic block pointers are invalid");
2635       if (Result->isVoidTy())
2636         return tokError("pointers to void are invalid; use i8* instead");
2637       if (!PointerType::isValidElementType(Result))
2638         return tokError("pointer to this type is invalid");
2639       unsigned AddrSpace;
2640       if (parseOptionalAddrSpace(AddrSpace) ||
2641           parseToken(lltok::star, "expected '*' in address space"))
2642         return true;
2643 
2644       Result = PointerType::get(Result, AddrSpace);
2645       break;
2646     }
2647 
2648     /// Types '(' ArgTypeListI ')' OptFuncAttrs
2649     case lltok::lparen:
2650       if (parseFunctionType(Result))
2651         return true;
2652       break;
2653     }
2654   }
2655 }
2656 
2657 /// parseParameterList
2658 ///    ::= '(' ')'
2659 ///    ::= '(' Arg (',' Arg)* ')'
2660 ///  Arg
2661 ///    ::= Type OptionalAttributes Value OptionalAttributes
2662 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2663                                   PerFunctionState &PFS, bool IsMustTailCall,
2664                                   bool InVarArgsFunc) {
2665   if (parseToken(lltok::lparen, "expected '(' in call"))
2666     return true;
2667 
2668   while (Lex.getKind() != lltok::rparen) {
2669     // If this isn't the first argument, we need a comma.
2670     if (!ArgList.empty() &&
2671         parseToken(lltok::comma, "expected ',' in argument list"))
2672       return true;
2673 
2674     // parse an ellipsis if this is a musttail call in a variadic function.
2675     if (Lex.getKind() == lltok::dotdotdot) {
2676       const char *Msg = "unexpected ellipsis in argument list for ";
2677       if (!IsMustTailCall)
2678         return tokError(Twine(Msg) + "non-musttail call");
2679       if (!InVarArgsFunc)
2680         return tokError(Twine(Msg) + "musttail call in non-varargs function");
2681       Lex.Lex();  // Lex the '...', it is purely for readability.
2682       return parseToken(lltok::rparen, "expected ')' at end of argument list");
2683     }
2684 
2685     // parse the argument.
2686     LocTy ArgLoc;
2687     Type *ArgTy = nullptr;
2688     AttrBuilder ArgAttrs;
2689     Value *V;
2690     if (parseType(ArgTy, ArgLoc))
2691       return true;
2692 
2693     if (ArgTy->isMetadataTy()) {
2694       if (parseMetadataAsValue(V, PFS))
2695         return true;
2696     } else {
2697       // Otherwise, handle normal operands.
2698       if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2699         return true;
2700     }
2701     ArgList.push_back(ParamInfo(
2702         ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2703   }
2704 
2705   if (IsMustTailCall && InVarArgsFunc)
2706     return tokError("expected '...' at end of argument list for musttail call "
2707                     "in varargs function");
2708 
2709   Lex.Lex();  // Lex the ')'.
2710   return false;
2711 }
2712 
2713 /// parseRequiredTypeAttr
2714 ///   ::= attrname(<ty>)
2715 bool LLParser::parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName) {
2716   Result = nullptr;
2717   if (!EatIfPresent(AttrName))
2718     return true;
2719   if (!EatIfPresent(lltok::lparen))
2720     return error(Lex.getLoc(), "expected '('");
2721   if (parseType(Result))
2722     return true;
2723   if (!EatIfPresent(lltok::rparen))
2724     return error(Lex.getLoc(), "expected ')'");
2725   return false;
2726 }
2727 
2728 /// parsePreallocated
2729 ///   ::= preallocated(<ty>)
2730 bool LLParser::parsePreallocated(Type *&Result) {
2731   return parseRequiredTypeAttr(Result, lltok::kw_preallocated);
2732 }
2733 
2734 /// parseInalloca
2735 ///   ::= inalloca(<ty>)
2736 bool LLParser::parseInalloca(Type *&Result) {
2737   return parseRequiredTypeAttr(Result, lltok::kw_inalloca);
2738 }
2739 
2740 /// parseByRef
2741 ///   ::= byref(<type>)
2742 bool LLParser::parseByRef(Type *&Result) {
2743   return parseRequiredTypeAttr(Result, lltok::kw_byref);
2744 }
2745 
2746 /// parseOptionalOperandBundles
2747 ///    ::= /*empty*/
2748 ///    ::= '[' OperandBundle [, OperandBundle ]* ']'
2749 ///
2750 /// OperandBundle
2751 ///    ::= bundle-tag '(' ')'
2752 ///    ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2753 ///
2754 /// bundle-tag ::= String Constant
2755 bool LLParser::parseOptionalOperandBundles(
2756     SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2757   LocTy BeginLoc = Lex.getLoc();
2758   if (!EatIfPresent(lltok::lsquare))
2759     return false;
2760 
2761   while (Lex.getKind() != lltok::rsquare) {
2762     // If this isn't the first operand bundle, we need a comma.
2763     if (!BundleList.empty() &&
2764         parseToken(lltok::comma, "expected ',' in input list"))
2765       return true;
2766 
2767     std::string Tag;
2768     if (parseStringConstant(Tag))
2769       return true;
2770 
2771     if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2772       return true;
2773 
2774     std::vector<Value *> Inputs;
2775     while (Lex.getKind() != lltok::rparen) {
2776       // If this isn't the first input, we need a comma.
2777       if (!Inputs.empty() &&
2778           parseToken(lltok::comma, "expected ',' in input list"))
2779         return true;
2780 
2781       Type *Ty = nullptr;
2782       Value *Input = nullptr;
2783       if (parseType(Ty) || parseValue(Ty, Input, PFS))
2784         return true;
2785       Inputs.push_back(Input);
2786     }
2787 
2788     BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2789 
2790     Lex.Lex(); // Lex the ')'.
2791   }
2792 
2793   if (BundleList.empty())
2794     return error(BeginLoc, "operand bundle set must not be empty");
2795 
2796   Lex.Lex(); // Lex the ']'.
2797   return false;
2798 }
2799 
2800 /// parseArgumentList - parse the argument list for a function type or function
2801 /// prototype.
2802 ///   ::= '(' ArgTypeListI ')'
2803 /// ArgTypeListI
2804 ///   ::= /*empty*/
2805 ///   ::= '...'
2806 ///   ::= ArgTypeList ',' '...'
2807 ///   ::= ArgType (',' ArgType)*
2808 ///
2809 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2810                                  bool &IsVarArg) {
2811   unsigned CurValID = 0;
2812   IsVarArg = false;
2813   assert(Lex.getKind() == lltok::lparen);
2814   Lex.Lex(); // eat the (.
2815 
2816   if (Lex.getKind() == lltok::rparen) {
2817     // empty
2818   } else if (Lex.getKind() == lltok::dotdotdot) {
2819     IsVarArg = true;
2820     Lex.Lex();
2821   } else {
2822     LocTy TypeLoc = Lex.getLoc();
2823     Type *ArgTy = nullptr;
2824     AttrBuilder Attrs;
2825     std::string Name;
2826 
2827     if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2828       return true;
2829 
2830     if (ArgTy->isVoidTy())
2831       return error(TypeLoc, "argument can not have void type");
2832 
2833     if (Lex.getKind() == lltok::LocalVar) {
2834       Name = Lex.getStrVal();
2835       Lex.Lex();
2836     } else if (Lex.getKind() == lltok::LocalVarID) {
2837       if (Lex.getUIntVal() != CurValID)
2838         return error(TypeLoc, "argument expected to be numbered '%" +
2839                                   Twine(CurValID) + "'");
2840       ++CurValID;
2841       Lex.Lex();
2842     }
2843 
2844     if (!FunctionType::isValidArgumentType(ArgTy))
2845       return error(TypeLoc, "invalid type for function argument");
2846 
2847     ArgList.emplace_back(TypeLoc, ArgTy,
2848                          AttributeSet::get(ArgTy->getContext(), Attrs),
2849                          std::move(Name));
2850 
2851     while (EatIfPresent(lltok::comma)) {
2852       // Handle ... at end of arg list.
2853       if (EatIfPresent(lltok::dotdotdot)) {
2854         IsVarArg = true;
2855         break;
2856       }
2857 
2858       // Otherwise must be an argument type.
2859       TypeLoc = Lex.getLoc();
2860       if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2861         return true;
2862 
2863       if (ArgTy->isVoidTy())
2864         return error(TypeLoc, "argument can not have void type");
2865 
2866       if (Lex.getKind() == lltok::LocalVar) {
2867         Name = Lex.getStrVal();
2868         Lex.Lex();
2869       } else {
2870         if (Lex.getKind() == lltok::LocalVarID) {
2871           if (Lex.getUIntVal() != CurValID)
2872             return error(TypeLoc, "argument expected to be numbered '%" +
2873                                       Twine(CurValID) + "'");
2874           Lex.Lex();
2875         }
2876         ++CurValID;
2877         Name = "";
2878       }
2879 
2880       if (!ArgTy->isFirstClassType())
2881         return error(TypeLoc, "invalid type for function argument");
2882 
2883       ArgList.emplace_back(TypeLoc, ArgTy,
2884                            AttributeSet::get(ArgTy->getContext(), Attrs),
2885                            std::move(Name));
2886     }
2887   }
2888 
2889   return parseToken(lltok::rparen, "expected ')' at end of argument list");
2890 }
2891 
2892 /// parseFunctionType
2893 ///  ::= Type ArgumentList OptionalAttrs
2894 bool LLParser::parseFunctionType(Type *&Result) {
2895   assert(Lex.getKind() == lltok::lparen);
2896 
2897   if (!FunctionType::isValidReturnType(Result))
2898     return tokError("invalid function return type");
2899 
2900   SmallVector<ArgInfo, 8> ArgList;
2901   bool IsVarArg;
2902   if (parseArgumentList(ArgList, IsVarArg))
2903     return true;
2904 
2905   // Reject names on the arguments lists.
2906   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2907     if (!ArgList[i].Name.empty())
2908       return error(ArgList[i].Loc, "argument name invalid in function type");
2909     if (ArgList[i].Attrs.hasAttributes())
2910       return error(ArgList[i].Loc,
2911                    "argument attributes invalid in function type");
2912   }
2913 
2914   SmallVector<Type*, 16> ArgListTy;
2915   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2916     ArgListTy.push_back(ArgList[i].Ty);
2917 
2918   Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2919   return false;
2920 }
2921 
2922 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2923 /// other structs.
2924 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2925   SmallVector<Type*, 8> Elts;
2926   if (parseStructBody(Elts))
2927     return true;
2928 
2929   Result = StructType::get(Context, Elts, Packed);
2930   return false;
2931 }
2932 
2933 /// parseStructDefinition - parse a struct in a 'type' definition.
2934 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2935                                      std::pair<Type *, LocTy> &Entry,
2936                                      Type *&ResultTy) {
2937   // If the type was already defined, diagnose the redefinition.
2938   if (Entry.first && !Entry.second.isValid())
2939     return error(TypeLoc, "redefinition of type");
2940 
2941   // If we have opaque, just return without filling in the definition for the
2942   // struct.  This counts as a definition as far as the .ll file goes.
2943   if (EatIfPresent(lltok::kw_opaque)) {
2944     // This type is being defined, so clear the location to indicate this.
2945     Entry.second = SMLoc();
2946 
2947     // If this type number has never been uttered, create it.
2948     if (!Entry.first)
2949       Entry.first = StructType::create(Context, Name);
2950     ResultTy = Entry.first;
2951     return false;
2952   }
2953 
2954   // If the type starts with '<', then it is either a packed struct or a vector.
2955   bool isPacked = EatIfPresent(lltok::less);
2956 
2957   // If we don't have a struct, then we have a random type alias, which we
2958   // accept for compatibility with old files.  These types are not allowed to be
2959   // forward referenced and not allowed to be recursive.
2960   if (Lex.getKind() != lltok::lbrace) {
2961     if (Entry.first)
2962       return error(TypeLoc, "forward references to non-struct type");
2963 
2964     ResultTy = nullptr;
2965     if (isPacked)
2966       return parseArrayVectorType(ResultTy, true);
2967     return parseType(ResultTy);
2968   }
2969 
2970   // This type is being defined, so clear the location to indicate this.
2971   Entry.second = SMLoc();
2972 
2973   // If this type number has never been uttered, create it.
2974   if (!Entry.first)
2975     Entry.first = StructType::create(Context, Name);
2976 
2977   StructType *STy = cast<StructType>(Entry.first);
2978 
2979   SmallVector<Type*, 8> Body;
2980   if (parseStructBody(Body) ||
2981       (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2982     return true;
2983 
2984   STy->setBody(Body, isPacked);
2985   ResultTy = STy;
2986   return false;
2987 }
2988 
2989 /// parseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2990 ///   StructType
2991 ///     ::= '{' '}'
2992 ///     ::= '{' Type (',' Type)* '}'
2993 ///     ::= '<' '{' '}' '>'
2994 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2995 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2996   assert(Lex.getKind() == lltok::lbrace);
2997   Lex.Lex(); // Consume the '{'
2998 
2999   // Handle the empty struct.
3000   if (EatIfPresent(lltok::rbrace))
3001     return false;
3002 
3003   LocTy EltTyLoc = Lex.getLoc();
3004   Type *Ty = nullptr;
3005   if (parseType(Ty))
3006     return true;
3007   Body.push_back(Ty);
3008 
3009   if (!StructType::isValidElementType(Ty))
3010     return error(EltTyLoc, "invalid element type for struct");
3011 
3012   while (EatIfPresent(lltok::comma)) {
3013     EltTyLoc = Lex.getLoc();
3014     if (parseType(Ty))
3015       return true;
3016 
3017     if (!StructType::isValidElementType(Ty))
3018       return error(EltTyLoc, "invalid element type for struct");
3019 
3020     Body.push_back(Ty);
3021   }
3022 
3023   return parseToken(lltok::rbrace, "expected '}' at end of struct");
3024 }
3025 
3026 /// parseArrayVectorType - parse an array or vector type, assuming the first
3027 /// token has already been consumed.
3028 ///   Type
3029 ///     ::= '[' APSINTVAL 'x' Types ']'
3030 ///     ::= '<' APSINTVAL 'x' Types '>'
3031 ///     ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3032 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3033   bool Scalable = false;
3034 
3035   if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3036     Lex.Lex(); // consume the 'vscale'
3037     if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3038       return true;
3039 
3040     Scalable = true;
3041   }
3042 
3043   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3044       Lex.getAPSIntVal().getBitWidth() > 64)
3045     return tokError("expected number in address space");
3046 
3047   LocTy SizeLoc = Lex.getLoc();
3048   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3049   Lex.Lex();
3050 
3051   if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3052     return true;
3053 
3054   LocTy TypeLoc = Lex.getLoc();
3055   Type *EltTy = nullptr;
3056   if (parseType(EltTy))
3057     return true;
3058 
3059   if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3060                  "expected end of sequential type"))
3061     return true;
3062 
3063   if (IsVector) {
3064     if (Size == 0)
3065       return error(SizeLoc, "zero element vector is illegal");
3066     if ((unsigned)Size != Size)
3067       return error(SizeLoc, "size too large for vector");
3068     if (!VectorType::isValidElementType(EltTy))
3069       return error(TypeLoc, "invalid vector element type");
3070     Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3071   } else {
3072     if (!ArrayType::isValidElementType(EltTy))
3073       return error(TypeLoc, "invalid array element type");
3074     Result = ArrayType::get(EltTy, Size);
3075   }
3076   return false;
3077 }
3078 
3079 //===----------------------------------------------------------------------===//
3080 // Function Semantic Analysis.
3081 //===----------------------------------------------------------------------===//
3082 
3083 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3084                                              int functionNumber)
3085   : P(p), F(f), FunctionNumber(functionNumber) {
3086 
3087   // Insert unnamed arguments into the NumberedVals list.
3088   for (Argument &A : F.args())
3089     if (!A.hasName())
3090       NumberedVals.push_back(&A);
3091 }
3092 
3093 LLParser::PerFunctionState::~PerFunctionState() {
3094   // If there were any forward referenced non-basicblock values, delete them.
3095 
3096   for (const auto &P : ForwardRefVals) {
3097     if (isa<BasicBlock>(P.second.first))
3098       continue;
3099     P.second.first->replaceAllUsesWith(
3100         UndefValue::get(P.second.first->getType()));
3101     P.second.first->deleteValue();
3102   }
3103 
3104   for (const auto &P : ForwardRefValIDs) {
3105     if (isa<BasicBlock>(P.second.first))
3106       continue;
3107     P.second.first->replaceAllUsesWith(
3108         UndefValue::get(P.second.first->getType()));
3109     P.second.first->deleteValue();
3110   }
3111 }
3112 
3113 bool LLParser::PerFunctionState::finishFunction() {
3114   if (!ForwardRefVals.empty())
3115     return P.error(ForwardRefVals.begin()->second.second,
3116                    "use of undefined value '%" + ForwardRefVals.begin()->first +
3117                        "'");
3118   if (!ForwardRefValIDs.empty())
3119     return P.error(ForwardRefValIDs.begin()->second.second,
3120                    "use of undefined value '%" +
3121                        Twine(ForwardRefValIDs.begin()->first) + "'");
3122   return false;
3123 }
3124 
3125 /// getVal - Get a value with the specified name or ID, creating a
3126 /// forward reference record if needed.  This can return null if the value
3127 /// exists but does not have the right type.
3128 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3129                                           LocTy Loc, bool IsCall) {
3130   // Look this name up in the normal function symbol table.
3131   Value *Val = F.getValueSymbolTable()->lookup(Name);
3132 
3133   // If this is a forward reference for the value, see if we already created a
3134   // forward ref record.
3135   if (!Val) {
3136     auto I = ForwardRefVals.find(Name);
3137     if (I != ForwardRefVals.end())
3138       Val = I->second.first;
3139   }
3140 
3141   // If we have the value in the symbol table or fwd-ref table, return it.
3142   if (Val)
3143     return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
3144 
3145   // Don't make placeholders with invalid type.
3146   if (!Ty->isFirstClassType()) {
3147     P.error(Loc, "invalid use of a non-first-class type");
3148     return nullptr;
3149   }
3150 
3151   // Otherwise, create a new forward reference for this value and remember it.
3152   Value *FwdVal;
3153   if (Ty->isLabelTy()) {
3154     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3155   } else {
3156     FwdVal = new Argument(Ty, Name);
3157   }
3158 
3159   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3160   return FwdVal;
3161 }
3162 
3163 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc,
3164                                           bool IsCall) {
3165   // Look this name up in the normal function symbol table.
3166   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3167 
3168   // If this is a forward reference for the value, see if we already created a
3169   // forward ref record.
3170   if (!Val) {
3171     auto I = ForwardRefValIDs.find(ID);
3172     if (I != ForwardRefValIDs.end())
3173       Val = I->second.first;
3174   }
3175 
3176   // If we have the value in the symbol table or fwd-ref table, return it.
3177   if (Val)
3178     return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
3179 
3180   if (!Ty->isFirstClassType()) {
3181     P.error(Loc, "invalid use of a non-first-class type");
3182     return nullptr;
3183   }
3184 
3185   // Otherwise, create a new forward reference for this value and remember it.
3186   Value *FwdVal;
3187   if (Ty->isLabelTy()) {
3188     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3189   } else {
3190     FwdVal = new Argument(Ty);
3191   }
3192 
3193   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3194   return FwdVal;
3195 }
3196 
3197 /// setInstName - After an instruction is parsed and inserted into its
3198 /// basic block, this installs its name.
3199 bool LLParser::PerFunctionState::setInstName(int NameID,
3200                                              const std::string &NameStr,
3201                                              LocTy NameLoc, Instruction *Inst) {
3202   // If this instruction has void type, it cannot have a name or ID specified.
3203   if (Inst->getType()->isVoidTy()) {
3204     if (NameID != -1 || !NameStr.empty())
3205       return P.error(NameLoc, "instructions returning void cannot have a name");
3206     return false;
3207   }
3208 
3209   // If this was a numbered instruction, verify that the instruction is the
3210   // expected value and resolve any forward references.
3211   if (NameStr.empty()) {
3212     // If neither a name nor an ID was specified, just use the next ID.
3213     if (NameID == -1)
3214       NameID = NumberedVals.size();
3215 
3216     if (unsigned(NameID) != NumberedVals.size())
3217       return P.error(NameLoc, "instruction expected to be numbered '%" +
3218                                   Twine(NumberedVals.size()) + "'");
3219 
3220     auto FI = ForwardRefValIDs.find(NameID);
3221     if (FI != ForwardRefValIDs.end()) {
3222       Value *Sentinel = FI->second.first;
3223       if (Sentinel->getType() != Inst->getType())
3224         return P.error(NameLoc, "instruction forward referenced with type '" +
3225                                     getTypeString(FI->second.first->getType()) +
3226                                     "'");
3227 
3228       Sentinel->replaceAllUsesWith(Inst);
3229       Sentinel->deleteValue();
3230       ForwardRefValIDs.erase(FI);
3231     }
3232 
3233     NumberedVals.push_back(Inst);
3234     return false;
3235   }
3236 
3237   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
3238   auto FI = ForwardRefVals.find(NameStr);
3239   if (FI != ForwardRefVals.end()) {
3240     Value *Sentinel = FI->second.first;
3241     if (Sentinel->getType() != Inst->getType())
3242       return P.error(NameLoc, "instruction forward referenced with type '" +
3243                                   getTypeString(FI->second.first->getType()) +
3244                                   "'");
3245 
3246     Sentinel->replaceAllUsesWith(Inst);
3247     Sentinel->deleteValue();
3248     ForwardRefVals.erase(FI);
3249   }
3250 
3251   // Set the name on the instruction.
3252   Inst->setName(NameStr);
3253 
3254   if (Inst->getName() != NameStr)
3255     return P.error(NameLoc, "multiple definition of local value named '" +
3256                                 NameStr + "'");
3257   return false;
3258 }
3259 
3260 /// getBB - Get a basic block with the specified name or ID, creating a
3261 /// forward reference record if needed.
3262 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3263                                               LocTy Loc) {
3264   return dyn_cast_or_null<BasicBlock>(
3265       getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3266 }
3267 
3268 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3269   return dyn_cast_or_null<BasicBlock>(
3270       getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3271 }
3272 
3273 /// defineBB - Define the specified basic block, which is either named or
3274 /// unnamed.  If there is an error, this returns null otherwise it returns
3275 /// the block being defined.
3276 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3277                                                  int NameID, LocTy Loc) {
3278   BasicBlock *BB;
3279   if (Name.empty()) {
3280     if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3281       P.error(Loc, "label expected to be numbered '" +
3282                        Twine(NumberedVals.size()) + "'");
3283       return nullptr;
3284     }
3285     BB = getBB(NumberedVals.size(), Loc);
3286     if (!BB) {
3287       P.error(Loc, "unable to create block numbered '" +
3288                        Twine(NumberedVals.size()) + "'");
3289       return nullptr;
3290     }
3291   } else {
3292     BB = getBB(Name, Loc);
3293     if (!BB) {
3294       P.error(Loc, "unable to create block named '" + Name + "'");
3295       return nullptr;
3296     }
3297   }
3298 
3299   // Move the block to the end of the function.  Forward ref'd blocks are
3300   // inserted wherever they happen to be referenced.
3301   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3302 
3303   // Remove the block from forward ref sets.
3304   if (Name.empty()) {
3305     ForwardRefValIDs.erase(NumberedVals.size());
3306     NumberedVals.push_back(BB);
3307   } else {
3308     // BB forward references are already in the function symbol table.
3309     ForwardRefVals.erase(Name);
3310   }
3311 
3312   return BB;
3313 }
3314 
3315 //===----------------------------------------------------------------------===//
3316 // Constants.
3317 //===----------------------------------------------------------------------===//
3318 
3319 /// parseValID - parse an abstract value that doesn't necessarily have a
3320 /// type implied.  For example, if we parse "4" we don't know what integer type
3321 /// it has.  The value will later be combined with its type and checked for
3322 /// sanity.  PFS is used to convert function-local operands of metadata (since
3323 /// metadata operands are not just parsed here but also converted to values).
3324 /// PFS can be null when we are not parsing metadata values inside a function.
3325 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS) {
3326   ID.Loc = Lex.getLoc();
3327   switch (Lex.getKind()) {
3328   default:
3329     return tokError("expected value token");
3330   case lltok::GlobalID:  // @42
3331     ID.UIntVal = Lex.getUIntVal();
3332     ID.Kind = ValID::t_GlobalID;
3333     break;
3334   case lltok::GlobalVar:  // @foo
3335     ID.StrVal = Lex.getStrVal();
3336     ID.Kind = ValID::t_GlobalName;
3337     break;
3338   case lltok::LocalVarID:  // %42
3339     ID.UIntVal = Lex.getUIntVal();
3340     ID.Kind = ValID::t_LocalID;
3341     break;
3342   case lltok::LocalVar:  // %foo
3343     ID.StrVal = Lex.getStrVal();
3344     ID.Kind = ValID::t_LocalName;
3345     break;
3346   case lltok::APSInt:
3347     ID.APSIntVal = Lex.getAPSIntVal();
3348     ID.Kind = ValID::t_APSInt;
3349     break;
3350   case lltok::APFloat:
3351     ID.APFloatVal = Lex.getAPFloatVal();
3352     ID.Kind = ValID::t_APFloat;
3353     break;
3354   case lltok::kw_true:
3355     ID.ConstantVal = ConstantInt::getTrue(Context);
3356     ID.Kind = ValID::t_Constant;
3357     break;
3358   case lltok::kw_false:
3359     ID.ConstantVal = ConstantInt::getFalse(Context);
3360     ID.Kind = ValID::t_Constant;
3361     break;
3362   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3363   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3364   case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3365   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3366   case lltok::kw_none: ID.Kind = ValID::t_None; break;
3367 
3368   case lltok::lbrace: {
3369     // ValID ::= '{' ConstVector '}'
3370     Lex.Lex();
3371     SmallVector<Constant*, 16> Elts;
3372     if (parseGlobalValueVector(Elts) ||
3373         parseToken(lltok::rbrace, "expected end of struct constant"))
3374       return true;
3375 
3376     ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3377     ID.UIntVal = Elts.size();
3378     memcpy(ID.ConstantStructElts.get(), Elts.data(),
3379            Elts.size() * sizeof(Elts[0]));
3380     ID.Kind = ValID::t_ConstantStruct;
3381     return false;
3382   }
3383   case lltok::less: {
3384     // ValID ::= '<' ConstVector '>'         --> Vector.
3385     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3386     Lex.Lex();
3387     bool isPackedStruct = EatIfPresent(lltok::lbrace);
3388 
3389     SmallVector<Constant*, 16> Elts;
3390     LocTy FirstEltLoc = Lex.getLoc();
3391     if (parseGlobalValueVector(Elts) ||
3392         (isPackedStruct &&
3393          parseToken(lltok::rbrace, "expected end of packed struct")) ||
3394         parseToken(lltok::greater, "expected end of constant"))
3395       return true;
3396 
3397     if (isPackedStruct) {
3398       ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3399       memcpy(ID.ConstantStructElts.get(), Elts.data(),
3400              Elts.size() * sizeof(Elts[0]));
3401       ID.UIntVal = Elts.size();
3402       ID.Kind = ValID::t_PackedConstantStruct;
3403       return false;
3404     }
3405 
3406     if (Elts.empty())
3407       return error(ID.Loc, "constant vector must not be empty");
3408 
3409     if (!Elts[0]->getType()->isIntegerTy() &&
3410         !Elts[0]->getType()->isFloatingPointTy() &&
3411         !Elts[0]->getType()->isPointerTy())
3412       return error(
3413           FirstEltLoc,
3414           "vector elements must have integer, pointer or floating point type");
3415 
3416     // Verify that all the vector elements have the same type.
3417     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3418       if (Elts[i]->getType() != Elts[0]->getType())
3419         return error(FirstEltLoc, "vector element #" + Twine(i) +
3420                                       " is not of type '" +
3421                                       getTypeString(Elts[0]->getType()));
3422 
3423     ID.ConstantVal = ConstantVector::get(Elts);
3424     ID.Kind = ValID::t_Constant;
3425     return false;
3426   }
3427   case lltok::lsquare: {   // Array Constant
3428     Lex.Lex();
3429     SmallVector<Constant*, 16> Elts;
3430     LocTy FirstEltLoc = Lex.getLoc();
3431     if (parseGlobalValueVector(Elts) ||
3432         parseToken(lltok::rsquare, "expected end of array constant"))
3433       return true;
3434 
3435     // Handle empty element.
3436     if (Elts.empty()) {
3437       // Use undef instead of an array because it's inconvenient to determine
3438       // the element type at this point, there being no elements to examine.
3439       ID.Kind = ValID::t_EmptyArray;
3440       return false;
3441     }
3442 
3443     if (!Elts[0]->getType()->isFirstClassType())
3444       return error(FirstEltLoc, "invalid array element type: " +
3445                                     getTypeString(Elts[0]->getType()));
3446 
3447     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3448 
3449     // Verify all elements are correct type!
3450     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3451       if (Elts[i]->getType() != Elts[0]->getType())
3452         return error(FirstEltLoc, "array element #" + Twine(i) +
3453                                       " is not of type '" +
3454                                       getTypeString(Elts[0]->getType()));
3455     }
3456 
3457     ID.ConstantVal = ConstantArray::get(ATy, Elts);
3458     ID.Kind = ValID::t_Constant;
3459     return false;
3460   }
3461   case lltok::kw_c:  // c "foo"
3462     Lex.Lex();
3463     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3464                                                   false);
3465     if (parseToken(lltok::StringConstant, "expected string"))
3466       return true;
3467     ID.Kind = ValID::t_Constant;
3468     return false;
3469 
3470   case lltok::kw_asm: {
3471     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3472     //             STRINGCONSTANT
3473     bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3474     Lex.Lex();
3475     if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3476         parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3477         parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3478         parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3479         parseStringConstant(ID.StrVal) ||
3480         parseToken(lltok::comma, "expected comma in inline asm expression") ||
3481         parseToken(lltok::StringConstant, "expected constraint string"))
3482       return true;
3483     ID.StrVal2 = Lex.getStrVal();
3484     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3485                  (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3486     ID.Kind = ValID::t_InlineAsm;
3487     return false;
3488   }
3489 
3490   case lltok::kw_blockaddress: {
3491     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3492     Lex.Lex();
3493 
3494     ValID Fn, Label;
3495 
3496     if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3497         parseValID(Fn) ||
3498         parseToken(lltok::comma,
3499                    "expected comma in block address expression") ||
3500         parseValID(Label) ||
3501         parseToken(lltok::rparen, "expected ')' in block address expression"))
3502       return true;
3503 
3504     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3505       return error(Fn.Loc, "expected function name in blockaddress");
3506     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3507       return error(Label.Loc, "expected basic block name in blockaddress");
3508 
3509     // Try to find the function (but skip it if it's forward-referenced).
3510     GlobalValue *GV = nullptr;
3511     if (Fn.Kind == ValID::t_GlobalID) {
3512       if (Fn.UIntVal < NumberedVals.size())
3513         GV = NumberedVals[Fn.UIntVal];
3514     } else if (!ForwardRefVals.count(Fn.StrVal)) {
3515       GV = M->getNamedValue(Fn.StrVal);
3516     }
3517     Function *F = nullptr;
3518     if (GV) {
3519       // Confirm that it's actually a function with a definition.
3520       if (!isa<Function>(GV))
3521         return error(Fn.Loc, "expected function name in blockaddress");
3522       F = cast<Function>(GV);
3523       if (F->isDeclaration())
3524         return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3525     }
3526 
3527     if (!F) {
3528       // Make a global variable as a placeholder for this reference.
3529       GlobalValue *&FwdRef =
3530           ForwardRefBlockAddresses.insert(std::make_pair(
3531                                               std::move(Fn),
3532                                               std::map<ValID, GlobalValue *>()))
3533               .first->second.insert(std::make_pair(std::move(Label), nullptr))
3534               .first->second;
3535       if (!FwdRef)
3536         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3537                                     GlobalValue::InternalLinkage, nullptr, "");
3538       ID.ConstantVal = FwdRef;
3539       ID.Kind = ValID::t_Constant;
3540       return false;
3541     }
3542 
3543     // We found the function; now find the basic block.  Don't use PFS, since we
3544     // might be inside a constant expression.
3545     BasicBlock *BB;
3546     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3547       if (Label.Kind == ValID::t_LocalID)
3548         BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3549       else
3550         BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3551       if (!BB)
3552         return error(Label.Loc, "referenced value is not a basic block");
3553     } else {
3554       if (Label.Kind == ValID::t_LocalID)
3555         return error(Label.Loc, "cannot take address of numeric label after "
3556                                 "the function is defined");
3557       BB = dyn_cast_or_null<BasicBlock>(
3558           F->getValueSymbolTable()->lookup(Label.StrVal));
3559       if (!BB)
3560         return error(Label.Loc, "referenced value is not a basic block");
3561     }
3562 
3563     ID.ConstantVal = BlockAddress::get(F, BB);
3564     ID.Kind = ValID::t_Constant;
3565     return false;
3566   }
3567 
3568   case lltok::kw_dso_local_equivalent: {
3569     // ValID ::= 'dso_local_equivalent' @foo
3570     Lex.Lex();
3571 
3572     ValID Fn;
3573 
3574     if (parseValID(Fn))
3575       return true;
3576 
3577     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3578       return error(Fn.Loc,
3579                    "expected global value name in dso_local_equivalent");
3580 
3581     // Try to find the function (but skip it if it's forward-referenced).
3582     GlobalValue *GV = nullptr;
3583     if (Fn.Kind == ValID::t_GlobalID) {
3584       if (Fn.UIntVal < NumberedVals.size())
3585         GV = NumberedVals[Fn.UIntVal];
3586     } else if (!ForwardRefVals.count(Fn.StrVal)) {
3587       GV = M->getNamedValue(Fn.StrVal);
3588     }
3589 
3590     assert(GV && "Could not find a corresponding global variable");
3591 
3592     if (!GV->getValueType()->isFunctionTy())
3593       return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3594                            "in dso_local_equivalent");
3595 
3596     ID.ConstantVal = DSOLocalEquivalent::get(GV);
3597     ID.Kind = ValID::t_Constant;
3598     return false;
3599   }
3600 
3601   case lltok::kw_trunc:
3602   case lltok::kw_zext:
3603   case lltok::kw_sext:
3604   case lltok::kw_fptrunc:
3605   case lltok::kw_fpext:
3606   case lltok::kw_bitcast:
3607   case lltok::kw_addrspacecast:
3608   case lltok::kw_uitofp:
3609   case lltok::kw_sitofp:
3610   case lltok::kw_fptoui:
3611   case lltok::kw_fptosi:
3612   case lltok::kw_inttoptr:
3613   case lltok::kw_ptrtoint: {
3614     unsigned Opc = Lex.getUIntVal();
3615     Type *DestTy = nullptr;
3616     Constant *SrcVal;
3617     Lex.Lex();
3618     if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3619         parseGlobalTypeAndValue(SrcVal) ||
3620         parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3621         parseType(DestTy) ||
3622         parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3623       return true;
3624     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3625       return error(ID.Loc, "invalid cast opcode for cast from '" +
3626                                getTypeString(SrcVal->getType()) + "' to '" +
3627                                getTypeString(DestTy) + "'");
3628     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3629                                                  SrcVal, DestTy);
3630     ID.Kind = ValID::t_Constant;
3631     return false;
3632   }
3633   case lltok::kw_extractvalue: {
3634     Lex.Lex();
3635     Constant *Val;
3636     SmallVector<unsigned, 4> Indices;
3637     if (parseToken(lltok::lparen,
3638                    "expected '(' in extractvalue constantexpr") ||
3639         parseGlobalTypeAndValue(Val) || parseIndexList(Indices) ||
3640         parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3641       return true;
3642 
3643     if (!Val->getType()->isAggregateType())
3644       return error(ID.Loc, "extractvalue operand must be aggregate type");
3645     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3646       return error(ID.Loc, "invalid indices for extractvalue");
3647     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3648     ID.Kind = ValID::t_Constant;
3649     return false;
3650   }
3651   case lltok::kw_insertvalue: {
3652     Lex.Lex();
3653     Constant *Val0, *Val1;
3654     SmallVector<unsigned, 4> Indices;
3655     if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") ||
3656         parseGlobalTypeAndValue(Val0) ||
3657         parseToken(lltok::comma,
3658                    "expected comma in insertvalue constantexpr") ||
3659         parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) ||
3660         parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3661       return true;
3662     if (!Val0->getType()->isAggregateType())
3663       return error(ID.Loc, "insertvalue operand must be aggregate type");
3664     Type *IndexedType =
3665         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3666     if (!IndexedType)
3667       return error(ID.Loc, "invalid indices for insertvalue");
3668     if (IndexedType != Val1->getType())
3669       return error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3670                                getTypeString(Val1->getType()) +
3671                                "' instead of '" + getTypeString(IndexedType) +
3672                                "'");
3673     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3674     ID.Kind = ValID::t_Constant;
3675     return false;
3676   }
3677   case lltok::kw_icmp:
3678   case lltok::kw_fcmp: {
3679     unsigned PredVal, Opc = Lex.getUIntVal();
3680     Constant *Val0, *Val1;
3681     Lex.Lex();
3682     if (parseCmpPredicate(PredVal, Opc) ||
3683         parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3684         parseGlobalTypeAndValue(Val0) ||
3685         parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3686         parseGlobalTypeAndValue(Val1) ||
3687         parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3688       return true;
3689 
3690     if (Val0->getType() != Val1->getType())
3691       return error(ID.Loc, "compare operands must have the same type");
3692 
3693     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3694 
3695     if (Opc == Instruction::FCmp) {
3696       if (!Val0->getType()->isFPOrFPVectorTy())
3697         return error(ID.Loc, "fcmp requires floating point operands");
3698       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3699     } else {
3700       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3701       if (!Val0->getType()->isIntOrIntVectorTy() &&
3702           !Val0->getType()->isPtrOrPtrVectorTy())
3703         return error(ID.Loc, "icmp requires pointer or integer operands");
3704       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3705     }
3706     ID.Kind = ValID::t_Constant;
3707     return false;
3708   }
3709 
3710   // Unary Operators.
3711   case lltok::kw_fneg: {
3712     unsigned Opc = Lex.getUIntVal();
3713     Constant *Val;
3714     Lex.Lex();
3715     if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3716         parseGlobalTypeAndValue(Val) ||
3717         parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3718       return true;
3719 
3720     // Check that the type is valid for the operator.
3721     switch (Opc) {
3722     case Instruction::FNeg:
3723       if (!Val->getType()->isFPOrFPVectorTy())
3724         return error(ID.Loc, "constexpr requires fp operands");
3725       break;
3726     default: llvm_unreachable("Unknown unary operator!");
3727     }
3728     unsigned Flags = 0;
3729     Constant *C = ConstantExpr::get(Opc, Val, Flags);
3730     ID.ConstantVal = C;
3731     ID.Kind = ValID::t_Constant;
3732     return false;
3733   }
3734   // Binary Operators.
3735   case lltok::kw_add:
3736   case lltok::kw_fadd:
3737   case lltok::kw_sub:
3738   case lltok::kw_fsub:
3739   case lltok::kw_mul:
3740   case lltok::kw_fmul:
3741   case lltok::kw_udiv:
3742   case lltok::kw_sdiv:
3743   case lltok::kw_fdiv:
3744   case lltok::kw_urem:
3745   case lltok::kw_srem:
3746   case lltok::kw_frem:
3747   case lltok::kw_shl:
3748   case lltok::kw_lshr:
3749   case lltok::kw_ashr: {
3750     bool NUW = false;
3751     bool NSW = false;
3752     bool Exact = false;
3753     unsigned Opc = Lex.getUIntVal();
3754     Constant *Val0, *Val1;
3755     Lex.Lex();
3756     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3757         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3758       if (EatIfPresent(lltok::kw_nuw))
3759         NUW = true;
3760       if (EatIfPresent(lltok::kw_nsw)) {
3761         NSW = true;
3762         if (EatIfPresent(lltok::kw_nuw))
3763           NUW = true;
3764       }
3765     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3766                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3767       if (EatIfPresent(lltok::kw_exact))
3768         Exact = true;
3769     }
3770     if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3771         parseGlobalTypeAndValue(Val0) ||
3772         parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3773         parseGlobalTypeAndValue(Val1) ||
3774         parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3775       return true;
3776     if (Val0->getType() != Val1->getType())
3777       return error(ID.Loc, "operands of constexpr must have same type");
3778     // Check that the type is valid for the operator.
3779     switch (Opc) {
3780     case Instruction::Add:
3781     case Instruction::Sub:
3782     case Instruction::Mul:
3783     case Instruction::UDiv:
3784     case Instruction::SDiv:
3785     case Instruction::URem:
3786     case Instruction::SRem:
3787     case Instruction::Shl:
3788     case Instruction::AShr:
3789     case Instruction::LShr:
3790       if (!Val0->getType()->isIntOrIntVectorTy())
3791         return error(ID.Loc, "constexpr requires integer operands");
3792       break;
3793     case Instruction::FAdd:
3794     case Instruction::FSub:
3795     case Instruction::FMul:
3796     case Instruction::FDiv:
3797     case Instruction::FRem:
3798       if (!Val0->getType()->isFPOrFPVectorTy())
3799         return error(ID.Loc, "constexpr requires fp operands");
3800       break;
3801     default: llvm_unreachable("Unknown binary operator!");
3802     }
3803     unsigned Flags = 0;
3804     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3805     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3806     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3807     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3808     ID.ConstantVal = C;
3809     ID.Kind = ValID::t_Constant;
3810     return false;
3811   }
3812 
3813   // Logical Operations
3814   case lltok::kw_and:
3815   case lltok::kw_or:
3816   case lltok::kw_xor: {
3817     unsigned Opc = Lex.getUIntVal();
3818     Constant *Val0, *Val1;
3819     Lex.Lex();
3820     if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3821         parseGlobalTypeAndValue(Val0) ||
3822         parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3823         parseGlobalTypeAndValue(Val1) ||
3824         parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3825       return true;
3826     if (Val0->getType() != Val1->getType())
3827       return error(ID.Loc, "operands of constexpr must have same type");
3828     if (!Val0->getType()->isIntOrIntVectorTy())
3829       return error(ID.Loc,
3830                    "constexpr requires integer or integer vector operands");
3831     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3832     ID.Kind = ValID::t_Constant;
3833     return false;
3834   }
3835 
3836   case lltok::kw_getelementptr:
3837   case lltok::kw_shufflevector:
3838   case lltok::kw_insertelement:
3839   case lltok::kw_extractelement:
3840   case lltok::kw_select: {
3841     unsigned Opc = Lex.getUIntVal();
3842     SmallVector<Constant*, 16> Elts;
3843     bool InBounds = false;
3844     Type *Ty;
3845     Lex.Lex();
3846 
3847     if (Opc == Instruction::GetElementPtr)
3848       InBounds = EatIfPresent(lltok::kw_inbounds);
3849 
3850     if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3851       return true;
3852 
3853     LocTy ExplicitTypeLoc = Lex.getLoc();
3854     if (Opc == Instruction::GetElementPtr) {
3855       if (parseType(Ty) ||
3856           parseToken(lltok::comma, "expected comma after getelementptr's type"))
3857         return true;
3858     }
3859 
3860     Optional<unsigned> InRangeOp;
3861     if (parseGlobalValueVector(
3862             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3863         parseToken(lltok::rparen, "expected ')' in constantexpr"))
3864       return true;
3865 
3866     if (Opc == Instruction::GetElementPtr) {
3867       if (Elts.size() == 0 ||
3868           !Elts[0]->getType()->isPtrOrPtrVectorTy())
3869         return error(ID.Loc, "base of getelementptr must be a pointer");
3870 
3871       Type *BaseType = Elts[0]->getType();
3872       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3873       if (Ty != BasePointerType->getElementType()) {
3874         return error(
3875             ExplicitTypeLoc,
3876             typeComparisonErrorMessage(
3877                 "explicit pointee type doesn't match operand's pointee type",
3878                 Ty, BasePointerType->getElementType()));
3879       }
3880 
3881       unsigned GEPWidth =
3882           BaseType->isVectorTy()
3883               ? cast<FixedVectorType>(BaseType)->getNumElements()
3884               : 0;
3885 
3886       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3887       for (Constant *Val : Indices) {
3888         Type *ValTy = Val->getType();
3889         if (!ValTy->isIntOrIntVectorTy())
3890           return error(ID.Loc, "getelementptr index must be an integer");
3891         if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3892           unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3893           if (GEPWidth && (ValNumEl != GEPWidth))
3894             return error(
3895                 ID.Loc,
3896                 "getelementptr vector index has a wrong number of elements");
3897           // GEPWidth may have been unknown because the base is a scalar,
3898           // but it is known now.
3899           GEPWidth = ValNumEl;
3900         }
3901       }
3902 
3903       SmallPtrSet<Type*, 4> Visited;
3904       if (!Indices.empty() && !Ty->isSized(&Visited))
3905         return error(ID.Loc, "base element of getelementptr must be sized");
3906 
3907       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3908         return error(ID.Loc, "invalid getelementptr indices");
3909 
3910       if (InRangeOp) {
3911         if (*InRangeOp == 0)
3912           return error(ID.Loc,
3913                        "inrange keyword may not appear on pointer operand");
3914         --*InRangeOp;
3915       }
3916 
3917       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3918                                                       InBounds, InRangeOp);
3919     } else if (Opc == Instruction::Select) {
3920       if (Elts.size() != 3)
3921         return error(ID.Loc, "expected three operands to select");
3922       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3923                                                               Elts[2]))
3924         return error(ID.Loc, Reason);
3925       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3926     } else if (Opc == Instruction::ShuffleVector) {
3927       if (Elts.size() != 3)
3928         return error(ID.Loc, "expected three operands to shufflevector");
3929       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3930         return error(ID.Loc, "invalid operands to shufflevector");
3931       SmallVector<int, 16> Mask;
3932       ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3933       ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3934     } else if (Opc == Instruction::ExtractElement) {
3935       if (Elts.size() != 2)
3936         return error(ID.Loc, "expected two operands to extractelement");
3937       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3938         return error(ID.Loc, "invalid extractelement operands");
3939       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3940     } else {
3941       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3942       if (Elts.size() != 3)
3943         return error(ID.Loc, "expected three operands to insertelement");
3944       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3945         return error(ID.Loc, "invalid insertelement operands");
3946       ID.ConstantVal =
3947                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3948     }
3949 
3950     ID.Kind = ValID::t_Constant;
3951     return false;
3952   }
3953   }
3954 
3955   Lex.Lex();
3956   return false;
3957 }
3958 
3959 /// parseGlobalValue - parse a global value with the specified type.
3960 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3961   C = nullptr;
3962   ValID ID;
3963   Value *V = nullptr;
3964   bool Parsed = parseValID(ID) ||
3965                 convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3966   if (V && !(C = dyn_cast<Constant>(V)))
3967     return error(ID.Loc, "global values must be constants");
3968   return Parsed;
3969 }
3970 
3971 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3972   Type *Ty = nullptr;
3973   return parseType(Ty) || parseGlobalValue(Ty, V);
3974 }
3975 
3976 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3977   C = nullptr;
3978 
3979   LocTy KwLoc = Lex.getLoc();
3980   if (!EatIfPresent(lltok::kw_comdat))
3981     return false;
3982 
3983   if (EatIfPresent(lltok::lparen)) {
3984     if (Lex.getKind() != lltok::ComdatVar)
3985       return tokError("expected comdat variable");
3986     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3987     Lex.Lex();
3988     if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3989       return true;
3990   } else {
3991     if (GlobalName.empty())
3992       return tokError("comdat cannot be unnamed");
3993     C = getComdat(std::string(GlobalName), KwLoc);
3994   }
3995 
3996   return false;
3997 }
3998 
3999 /// parseGlobalValueVector
4000 ///   ::= /*empty*/
4001 ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
4002 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
4003                                       Optional<unsigned> *InRangeOp) {
4004   // Empty list.
4005   if (Lex.getKind() == lltok::rbrace ||
4006       Lex.getKind() == lltok::rsquare ||
4007       Lex.getKind() == lltok::greater ||
4008       Lex.getKind() == lltok::rparen)
4009     return false;
4010 
4011   do {
4012     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
4013       *InRangeOp = Elts.size();
4014 
4015     Constant *C;
4016     if (parseGlobalTypeAndValue(C))
4017       return true;
4018     Elts.push_back(C);
4019   } while (EatIfPresent(lltok::comma));
4020 
4021   return false;
4022 }
4023 
4024 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4025   SmallVector<Metadata *, 16> Elts;
4026   if (parseMDNodeVector(Elts))
4027     return true;
4028 
4029   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4030   return false;
4031 }
4032 
4033 /// MDNode:
4034 ///  ::= !{ ... }
4035 ///  ::= !7
4036 ///  ::= !DILocation(...)
4037 bool LLParser::parseMDNode(MDNode *&N) {
4038   if (Lex.getKind() == lltok::MetadataVar)
4039     return parseSpecializedMDNode(N);
4040 
4041   return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4042 }
4043 
4044 bool LLParser::parseMDNodeTail(MDNode *&N) {
4045   // !{ ... }
4046   if (Lex.getKind() == lltok::lbrace)
4047     return parseMDTuple(N);
4048 
4049   // !42
4050   return parseMDNodeID(N);
4051 }
4052 
4053 namespace {
4054 
4055 /// Structure to represent an optional metadata field.
4056 template <class FieldTy> struct MDFieldImpl {
4057   typedef MDFieldImpl ImplTy;
4058   FieldTy Val;
4059   bool Seen;
4060 
4061   void assign(FieldTy Val) {
4062     Seen = true;
4063     this->Val = std::move(Val);
4064   }
4065 
4066   explicit MDFieldImpl(FieldTy Default)
4067       : Val(std::move(Default)), Seen(false) {}
4068 };
4069 
4070 /// Structure to represent an optional metadata field that
4071 /// can be of either type (A or B) and encapsulates the
4072 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4073 /// to reimplement the specifics for representing each Field.
4074 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4075   typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4076   FieldTypeA A;
4077   FieldTypeB B;
4078   bool Seen;
4079 
4080   enum {
4081     IsInvalid = 0,
4082     IsTypeA = 1,
4083     IsTypeB = 2
4084   } WhatIs;
4085 
4086   void assign(FieldTypeA A) {
4087     Seen = true;
4088     this->A = std::move(A);
4089     WhatIs = IsTypeA;
4090   }
4091 
4092   void assign(FieldTypeB B) {
4093     Seen = true;
4094     this->B = std::move(B);
4095     WhatIs = IsTypeB;
4096   }
4097 
4098   explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4099       : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4100         WhatIs(IsInvalid) {}
4101 };
4102 
4103 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4104   uint64_t Max;
4105 
4106   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4107       : ImplTy(Default), Max(Max) {}
4108 };
4109 
4110 struct LineField : public MDUnsignedField {
4111   LineField() : MDUnsignedField(0, UINT32_MAX) {}
4112 };
4113 
4114 struct ColumnField : public MDUnsignedField {
4115   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4116 };
4117 
4118 struct DwarfTagField : public MDUnsignedField {
4119   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4120   DwarfTagField(dwarf::Tag DefaultTag)
4121       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4122 };
4123 
4124 struct DwarfMacinfoTypeField : public MDUnsignedField {
4125   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4126   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4127     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4128 };
4129 
4130 struct DwarfAttEncodingField : public MDUnsignedField {
4131   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4132 };
4133 
4134 struct DwarfVirtualityField : public MDUnsignedField {
4135   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4136 };
4137 
4138 struct DwarfLangField : public MDUnsignedField {
4139   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4140 };
4141 
4142 struct DwarfCCField : public MDUnsignedField {
4143   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4144 };
4145 
4146 struct EmissionKindField : public MDUnsignedField {
4147   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4148 };
4149 
4150 struct NameTableKindField : public MDUnsignedField {
4151   NameTableKindField()
4152       : MDUnsignedField(
4153             0, (unsigned)
4154                    DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4155 };
4156 
4157 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4158   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4159 };
4160 
4161 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4162   DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4163 };
4164 
4165 struct MDAPSIntField : public MDFieldImpl<APSInt> {
4166   MDAPSIntField() : ImplTy(APSInt()) {}
4167 };
4168 
4169 struct MDSignedField : public MDFieldImpl<int64_t> {
4170   int64_t Min;
4171   int64_t Max;
4172 
4173   MDSignedField(int64_t Default = 0)
4174       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
4175   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4176       : ImplTy(Default), Min(Min), Max(Max) {}
4177 };
4178 
4179 struct MDBoolField : public MDFieldImpl<bool> {
4180   MDBoolField(bool Default = false) : ImplTy(Default) {}
4181 };
4182 
4183 struct MDField : public MDFieldImpl<Metadata *> {
4184   bool AllowNull;
4185 
4186   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4187 };
4188 
4189 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
4190   MDConstant() : ImplTy(nullptr) {}
4191 };
4192 
4193 struct MDStringField : public MDFieldImpl<MDString *> {
4194   bool AllowEmpty;
4195   MDStringField(bool AllowEmpty = true)
4196       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4197 };
4198 
4199 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4200   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4201 };
4202 
4203 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4204   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4205 };
4206 
4207 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4208   MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4209       : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4210 
4211   MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4212                     bool AllowNull = true)
4213       : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4214 
4215   bool isMDSignedField() const { return WhatIs == IsTypeA; }
4216   bool isMDField() const { return WhatIs == IsTypeB; }
4217   int64_t getMDSignedValue() const {
4218     assert(isMDSignedField() && "Wrong field type");
4219     return A.Val;
4220   }
4221   Metadata *getMDFieldValue() const {
4222     assert(isMDField() && "Wrong field type");
4223     return B.Val;
4224   }
4225 };
4226 
4227 struct MDSignedOrUnsignedField
4228     : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
4229   MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
4230 
4231   bool isMDSignedField() const { return WhatIs == IsTypeA; }
4232   bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
4233   int64_t getMDSignedValue() const {
4234     assert(isMDSignedField() && "Wrong field type");
4235     return A.Val;
4236   }
4237   uint64_t getMDUnsignedValue() const {
4238     assert(isMDUnsignedField() && "Wrong field type");
4239     return B.Val;
4240   }
4241 };
4242 
4243 } // end anonymous namespace
4244 
4245 namespace llvm {
4246 
4247 template <>
4248 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4249   if (Lex.getKind() != lltok::APSInt)
4250     return tokError("expected integer");
4251 
4252   Result.assign(Lex.getAPSIntVal());
4253   Lex.Lex();
4254   return false;
4255 }
4256 
4257 template <>
4258 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4259                             MDUnsignedField &Result) {
4260   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4261     return tokError("expected unsigned integer");
4262 
4263   auto &U = Lex.getAPSIntVal();
4264   if (U.ugt(Result.Max))
4265     return tokError("value for '" + Name + "' too large, limit is " +
4266                     Twine(Result.Max));
4267   Result.assign(U.getZExtValue());
4268   assert(Result.Val <= Result.Max && "Expected value in range");
4269   Lex.Lex();
4270   return false;
4271 }
4272 
4273 template <>
4274 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4275   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4276 }
4277 template <>
4278 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4279   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4280 }
4281 
4282 template <>
4283 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4284   if (Lex.getKind() == lltok::APSInt)
4285     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4286 
4287   if (Lex.getKind() != lltok::DwarfTag)
4288     return tokError("expected DWARF tag");
4289 
4290   unsigned Tag = dwarf::getTag(Lex.getStrVal());
4291   if (Tag == dwarf::DW_TAG_invalid)
4292     return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4293   assert(Tag <= Result.Max && "Expected valid DWARF tag");
4294 
4295   Result.assign(Tag);
4296   Lex.Lex();
4297   return false;
4298 }
4299 
4300 template <>
4301 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4302                             DwarfMacinfoTypeField &Result) {
4303   if (Lex.getKind() == lltok::APSInt)
4304     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4305 
4306   if (Lex.getKind() != lltok::DwarfMacinfo)
4307     return tokError("expected DWARF macinfo type");
4308 
4309   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4310   if (Macinfo == dwarf::DW_MACINFO_invalid)
4311     return tokError("invalid DWARF macinfo type" + Twine(" '") +
4312                     Lex.getStrVal() + "'");
4313   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4314 
4315   Result.assign(Macinfo);
4316   Lex.Lex();
4317   return false;
4318 }
4319 
4320 template <>
4321 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4322                             DwarfVirtualityField &Result) {
4323   if (Lex.getKind() == lltok::APSInt)
4324     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4325 
4326   if (Lex.getKind() != lltok::DwarfVirtuality)
4327     return tokError("expected DWARF virtuality code");
4328 
4329   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4330   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4331     return tokError("invalid DWARF virtuality code" + Twine(" '") +
4332                     Lex.getStrVal() + "'");
4333   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4334   Result.assign(Virtuality);
4335   Lex.Lex();
4336   return false;
4337 }
4338 
4339 template <>
4340 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4341   if (Lex.getKind() == lltok::APSInt)
4342     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4343 
4344   if (Lex.getKind() != lltok::DwarfLang)
4345     return tokError("expected DWARF language");
4346 
4347   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4348   if (!Lang)
4349     return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4350                     "'");
4351   assert(Lang <= Result.Max && "Expected valid DWARF language");
4352   Result.assign(Lang);
4353   Lex.Lex();
4354   return false;
4355 }
4356 
4357 template <>
4358 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4359   if (Lex.getKind() == lltok::APSInt)
4360     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4361 
4362   if (Lex.getKind() != lltok::DwarfCC)
4363     return tokError("expected DWARF calling convention");
4364 
4365   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4366   if (!CC)
4367     return tokError("invalid DWARF calling convention" + Twine(" '") +
4368                     Lex.getStrVal() + "'");
4369   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4370   Result.assign(CC);
4371   Lex.Lex();
4372   return false;
4373 }
4374 
4375 template <>
4376 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4377                             EmissionKindField &Result) {
4378   if (Lex.getKind() == lltok::APSInt)
4379     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4380 
4381   if (Lex.getKind() != lltok::EmissionKind)
4382     return tokError("expected emission kind");
4383 
4384   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4385   if (!Kind)
4386     return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4387                     "'");
4388   assert(*Kind <= Result.Max && "Expected valid emission kind");
4389   Result.assign(*Kind);
4390   Lex.Lex();
4391   return false;
4392 }
4393 
4394 template <>
4395 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4396                             NameTableKindField &Result) {
4397   if (Lex.getKind() == lltok::APSInt)
4398     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4399 
4400   if (Lex.getKind() != lltok::NameTableKind)
4401     return tokError("expected nameTable kind");
4402 
4403   auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4404   if (!Kind)
4405     return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4406                     "'");
4407   assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4408   Result.assign((unsigned)*Kind);
4409   Lex.Lex();
4410   return false;
4411 }
4412 
4413 template <>
4414 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4415                             DwarfAttEncodingField &Result) {
4416   if (Lex.getKind() == lltok::APSInt)
4417     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4418 
4419   if (Lex.getKind() != lltok::DwarfAttEncoding)
4420     return tokError("expected DWARF type attribute encoding");
4421 
4422   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4423   if (!Encoding)
4424     return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4425                     Lex.getStrVal() + "'");
4426   assert(Encoding <= Result.Max && "Expected valid DWARF language");
4427   Result.assign(Encoding);
4428   Lex.Lex();
4429   return false;
4430 }
4431 
4432 /// DIFlagField
4433 ///  ::= uint32
4434 ///  ::= DIFlagVector
4435 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4436 template <>
4437 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4438 
4439   // parser for a single flag.
4440   auto parseFlag = [&](DINode::DIFlags &Val) {
4441     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4442       uint32_t TempVal = static_cast<uint32_t>(Val);
4443       bool Res = parseUInt32(TempVal);
4444       Val = static_cast<DINode::DIFlags>(TempVal);
4445       return Res;
4446     }
4447 
4448     if (Lex.getKind() != lltok::DIFlag)
4449       return tokError("expected debug info flag");
4450 
4451     Val = DINode::getFlag(Lex.getStrVal());
4452     if (!Val)
4453       return tokError(Twine("invalid debug info flag flag '") +
4454                       Lex.getStrVal() + "'");
4455     Lex.Lex();
4456     return false;
4457   };
4458 
4459   // parse the flags and combine them together.
4460   DINode::DIFlags Combined = DINode::FlagZero;
4461   do {
4462     DINode::DIFlags Val;
4463     if (parseFlag(Val))
4464       return true;
4465     Combined |= Val;
4466   } while (EatIfPresent(lltok::bar));
4467 
4468   Result.assign(Combined);
4469   return false;
4470 }
4471 
4472 /// DISPFlagField
4473 ///  ::= uint32
4474 ///  ::= DISPFlagVector
4475 ///  ::= DISPFlagVector '|' DISPFlag* '|' uint32
4476 template <>
4477 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4478 
4479   // parser for a single flag.
4480   auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4481     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4482       uint32_t TempVal = static_cast<uint32_t>(Val);
4483       bool Res = parseUInt32(TempVal);
4484       Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4485       return Res;
4486     }
4487 
4488     if (Lex.getKind() != lltok::DISPFlag)
4489       return tokError("expected debug info flag");
4490 
4491     Val = DISubprogram::getFlag(Lex.getStrVal());
4492     if (!Val)
4493       return tokError(Twine("invalid subprogram debug info flag '") +
4494                       Lex.getStrVal() + "'");
4495     Lex.Lex();
4496     return false;
4497   };
4498 
4499   // parse the flags and combine them together.
4500   DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4501   do {
4502     DISubprogram::DISPFlags Val;
4503     if (parseFlag(Val))
4504       return true;
4505     Combined |= Val;
4506   } while (EatIfPresent(lltok::bar));
4507 
4508   Result.assign(Combined);
4509   return false;
4510 }
4511 
4512 template <>
4513 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4514   if (Lex.getKind() != lltok::APSInt)
4515     return tokError("expected signed integer");
4516 
4517   auto &S = Lex.getAPSIntVal();
4518   if (S < Result.Min)
4519     return tokError("value for '" + Name + "' too small, limit is " +
4520                     Twine(Result.Min));
4521   if (S > Result.Max)
4522     return tokError("value for '" + Name + "' too large, limit is " +
4523                     Twine(Result.Max));
4524   Result.assign(S.getExtValue());
4525   assert(Result.Val >= Result.Min && "Expected value in range");
4526   assert(Result.Val <= Result.Max && "Expected value in range");
4527   Lex.Lex();
4528   return false;
4529 }
4530 
4531 template <>
4532 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4533   switch (Lex.getKind()) {
4534   default:
4535     return tokError("expected 'true' or 'false'");
4536   case lltok::kw_true:
4537     Result.assign(true);
4538     break;
4539   case lltok::kw_false:
4540     Result.assign(false);
4541     break;
4542   }
4543   Lex.Lex();
4544   return false;
4545 }
4546 
4547 template <>
4548 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4549   if (Lex.getKind() == lltok::kw_null) {
4550     if (!Result.AllowNull)
4551       return tokError("'" + Name + "' cannot be null");
4552     Lex.Lex();
4553     Result.assign(nullptr);
4554     return false;
4555   }
4556 
4557   Metadata *MD;
4558   if (parseMetadata(MD, nullptr))
4559     return true;
4560 
4561   Result.assign(MD);
4562   return false;
4563 }
4564 
4565 template <>
4566 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4567                             MDSignedOrMDField &Result) {
4568   // Try to parse a signed int.
4569   if (Lex.getKind() == lltok::APSInt) {
4570     MDSignedField Res = Result.A;
4571     if (!parseMDField(Loc, Name, Res)) {
4572       Result.assign(Res);
4573       return false;
4574     }
4575     return true;
4576   }
4577 
4578   // Otherwise, try to parse as an MDField.
4579   MDField Res = Result.B;
4580   if (!parseMDField(Loc, Name, Res)) {
4581     Result.assign(Res);
4582     return false;
4583   }
4584 
4585   return true;
4586 }
4587 
4588 template <>
4589 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4590   LocTy ValueLoc = Lex.getLoc();
4591   std::string S;
4592   if (parseStringConstant(S))
4593     return true;
4594 
4595   if (!Result.AllowEmpty && S.empty())
4596     return error(ValueLoc, "'" + Name + "' cannot be empty");
4597 
4598   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4599   return false;
4600 }
4601 
4602 template <>
4603 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4604   SmallVector<Metadata *, 4> MDs;
4605   if (parseMDNodeVector(MDs))
4606     return true;
4607 
4608   Result.assign(std::move(MDs));
4609   return false;
4610 }
4611 
4612 template <>
4613 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4614                             ChecksumKindField &Result) {
4615   Optional<DIFile::ChecksumKind> CSKind =
4616       DIFile::getChecksumKind(Lex.getStrVal());
4617 
4618   if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4619     return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4620                     "'");
4621 
4622   Result.assign(*CSKind);
4623   Lex.Lex();
4624   return false;
4625 }
4626 
4627 } // end namespace llvm
4628 
4629 template <class ParserTy>
4630 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4631   do {
4632     if (Lex.getKind() != lltok::LabelStr)
4633       return tokError("expected field label here");
4634 
4635     if (ParseField())
4636       return true;
4637   } while (EatIfPresent(lltok::comma));
4638 
4639   return false;
4640 }
4641 
4642 template <class ParserTy>
4643 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4644   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4645   Lex.Lex();
4646 
4647   if (parseToken(lltok::lparen, "expected '(' here"))
4648     return true;
4649   if (Lex.getKind() != lltok::rparen)
4650     if (parseMDFieldsImplBody(ParseField))
4651       return true;
4652 
4653   ClosingLoc = Lex.getLoc();
4654   return parseToken(lltok::rparen, "expected ')' here");
4655 }
4656 
4657 template <class FieldTy>
4658 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4659   if (Result.Seen)
4660     return tokError("field '" + Name + "' cannot be specified more than once");
4661 
4662   LocTy Loc = Lex.getLoc();
4663   Lex.Lex();
4664   return parseMDField(Loc, Name, Result);
4665 }
4666 
4667 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4668   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4669 
4670 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
4671   if (Lex.getStrVal() == #CLASS)                                               \
4672     return parse##CLASS(N, IsDistinct);
4673 #include "llvm/IR/Metadata.def"
4674 
4675   return tokError("expected metadata type");
4676 }
4677 
4678 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4679 #define NOP_FIELD(NAME, TYPE, INIT)
4680 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
4681   if (!NAME.Seen)                                                              \
4682     return error(ClosingLoc, "missing required field '" #NAME "'");
4683 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
4684   if (Lex.getStrVal() == #NAME)                                                \
4685     return parseMDField(#NAME, NAME);
4686 #define PARSE_MD_FIELDS()                                                      \
4687   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
4688   do {                                                                         \
4689     LocTy ClosingLoc;                                                          \
4690     if (parseMDFieldsImpl(                                                     \
4691             [&]() -> bool {                                                    \
4692               VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                  \
4693               return tokError(Twine("invalid field '") + Lex.getStrVal() +     \
4694                               "'");                                            \
4695             },                                                                 \
4696             ClosingLoc))                                                       \
4697       return true;                                                             \
4698     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
4699   } while (false)
4700 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
4701   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4702 
4703 /// parseDILocationFields:
4704 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4705 ///   isImplicitCode: true)
4706 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4707 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4708   OPTIONAL(line, LineField, );                                                 \
4709   OPTIONAL(column, ColumnField, );                                             \
4710   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4711   OPTIONAL(inlinedAt, MDField, );                                              \
4712   OPTIONAL(isImplicitCode, MDBoolField, (false));
4713   PARSE_MD_FIELDS();
4714 #undef VISIT_MD_FIELDS
4715 
4716   Result =
4717       GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4718                                    inlinedAt.Val, isImplicitCode.Val));
4719   return false;
4720 }
4721 
4722 /// parseGenericDINode:
4723 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4724 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4725 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4726   REQUIRED(tag, DwarfTagField, );                                              \
4727   OPTIONAL(header, MDStringField, );                                           \
4728   OPTIONAL(operands, MDFieldList, );
4729   PARSE_MD_FIELDS();
4730 #undef VISIT_MD_FIELDS
4731 
4732   Result = GET_OR_DISTINCT(GenericDINode,
4733                            (Context, tag.Val, header.Val, operands.Val));
4734   return false;
4735 }
4736 
4737 /// parseDISubrange:
4738 ///   ::= !DISubrange(count: 30, lowerBound: 2)
4739 ///   ::= !DISubrange(count: !node, lowerBound: 2)
4740 ///   ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4741 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4742 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4743   OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false));              \
4744   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4745   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4746   OPTIONAL(stride, MDSignedOrMDField, );
4747   PARSE_MD_FIELDS();
4748 #undef VISIT_MD_FIELDS
4749 
4750   Metadata *Count = nullptr;
4751   Metadata *LowerBound = nullptr;
4752   Metadata *UpperBound = nullptr;
4753   Metadata *Stride = nullptr;
4754 
4755   auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4756     if (Bound.isMDSignedField())
4757       return ConstantAsMetadata::get(ConstantInt::getSigned(
4758           Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4759     if (Bound.isMDField())
4760       return Bound.getMDFieldValue();
4761     return nullptr;
4762   };
4763 
4764   Count = convToMetadata(count);
4765   LowerBound = convToMetadata(lowerBound);
4766   UpperBound = convToMetadata(upperBound);
4767   Stride = convToMetadata(stride);
4768 
4769   Result = GET_OR_DISTINCT(DISubrange,
4770                            (Context, Count, LowerBound, UpperBound, Stride));
4771 
4772   return false;
4773 }
4774 
4775 /// parseDIGenericSubrange:
4776 ///   ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4777 ///   !node3)
4778 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4779 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4780   OPTIONAL(count, MDSignedOrMDField, );                                        \
4781   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4782   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4783   OPTIONAL(stride, MDSignedOrMDField, );
4784   PARSE_MD_FIELDS();
4785 #undef VISIT_MD_FIELDS
4786 
4787   auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4788     if (Bound.isMDSignedField())
4789       return DIExpression::get(
4790           Context, {dwarf::DW_OP_consts,
4791                     static_cast<uint64_t>(Bound.getMDSignedValue())});
4792     if (Bound.isMDField())
4793       return Bound.getMDFieldValue();
4794     return nullptr;
4795   };
4796 
4797   Metadata *Count = ConvToMetadata(count);
4798   Metadata *LowerBound = ConvToMetadata(lowerBound);
4799   Metadata *UpperBound = ConvToMetadata(upperBound);
4800   Metadata *Stride = ConvToMetadata(stride);
4801 
4802   Result = GET_OR_DISTINCT(DIGenericSubrange,
4803                            (Context, Count, LowerBound, UpperBound, Stride));
4804 
4805   return false;
4806 }
4807 
4808 /// parseDIEnumerator:
4809 ///   ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4810 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4811 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4812   REQUIRED(name, MDStringField, );                                             \
4813   REQUIRED(value, MDAPSIntField, );                                            \
4814   OPTIONAL(isUnsigned, MDBoolField, (false));
4815   PARSE_MD_FIELDS();
4816 #undef VISIT_MD_FIELDS
4817 
4818   if (isUnsigned.Val && value.Val.isNegative())
4819     return tokError("unsigned enumerator with negative value");
4820 
4821   APSInt Value(value.Val);
4822   // Add a leading zero so that unsigned values with the msb set are not
4823   // mistaken for negative values when used for signed enumerators.
4824   if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4825     Value = Value.zext(Value.getBitWidth() + 1);
4826 
4827   Result =
4828       GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4829 
4830   return false;
4831 }
4832 
4833 /// parseDIBasicType:
4834 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4835 ///                    encoding: DW_ATE_encoding, flags: 0)
4836 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4837 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4838   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
4839   OPTIONAL(name, MDStringField, );                                             \
4840   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4841   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4842   OPTIONAL(encoding, DwarfAttEncodingField, );                                 \
4843   OPTIONAL(flags, DIFlagField, );
4844   PARSE_MD_FIELDS();
4845 #undef VISIT_MD_FIELDS
4846 
4847   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4848                                          align.Val, encoding.Val, flags.Val));
4849   return false;
4850 }
4851 
4852 /// parseDIStringType:
4853 ///   ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4854 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4855 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4856   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type));                   \
4857   OPTIONAL(name, MDStringField, );                                             \
4858   OPTIONAL(stringLength, MDField, );                                           \
4859   OPTIONAL(stringLengthExpression, MDField, );                                 \
4860   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4861   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4862   OPTIONAL(encoding, DwarfAttEncodingField, );
4863   PARSE_MD_FIELDS();
4864 #undef VISIT_MD_FIELDS
4865 
4866   Result = GET_OR_DISTINCT(DIStringType,
4867                            (Context, tag.Val, name.Val, stringLength.Val,
4868                             stringLengthExpression.Val, size.Val, align.Val,
4869                             encoding.Val));
4870   return false;
4871 }
4872 
4873 /// parseDIDerivedType:
4874 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4875 ///                      line: 7, scope: !1, baseType: !2, size: 32,
4876 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
4877 ///                      dwarfAddressSpace: 3)
4878 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4879 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4880   REQUIRED(tag, DwarfTagField, );                                              \
4881   OPTIONAL(name, MDStringField, );                                             \
4882   OPTIONAL(file, MDField, );                                                   \
4883   OPTIONAL(line, LineField, );                                                 \
4884   OPTIONAL(scope, MDField, );                                                  \
4885   REQUIRED(baseType, MDField, );                                               \
4886   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4887   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4888   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4889   OPTIONAL(flags, DIFlagField, );                                              \
4890   OPTIONAL(extraData, MDField, );                                              \
4891   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4892   PARSE_MD_FIELDS();
4893 #undef VISIT_MD_FIELDS
4894 
4895   Optional<unsigned> DWARFAddressSpace;
4896   if (dwarfAddressSpace.Val != UINT32_MAX)
4897     DWARFAddressSpace = dwarfAddressSpace.Val;
4898 
4899   Result = GET_OR_DISTINCT(DIDerivedType,
4900                            (Context, tag.Val, name.Val, file.Val, line.Val,
4901                             scope.Val, baseType.Val, size.Val, align.Val,
4902                             offset.Val, DWARFAddressSpace, flags.Val,
4903                             extraData.Val));
4904   return false;
4905 }
4906 
4907 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4908 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4909   REQUIRED(tag, DwarfTagField, );                                              \
4910   OPTIONAL(name, MDStringField, );                                             \
4911   OPTIONAL(file, MDField, );                                                   \
4912   OPTIONAL(line, LineField, );                                                 \
4913   OPTIONAL(scope, MDField, );                                                  \
4914   OPTIONAL(baseType, MDField, );                                               \
4915   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4916   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4917   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4918   OPTIONAL(flags, DIFlagField, );                                              \
4919   OPTIONAL(elements, MDField, );                                               \
4920   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
4921   OPTIONAL(vtableHolder, MDField, );                                           \
4922   OPTIONAL(templateParams, MDField, );                                         \
4923   OPTIONAL(identifier, MDStringField, );                                       \
4924   OPTIONAL(discriminator, MDField, );                                          \
4925   OPTIONAL(dataLocation, MDField, );                                           \
4926   OPTIONAL(associated, MDField, );                                             \
4927   OPTIONAL(allocated, MDField, );                                              \
4928   OPTIONAL(rank, MDSignedOrMDField, );
4929   PARSE_MD_FIELDS();
4930 #undef VISIT_MD_FIELDS
4931 
4932   Metadata *Rank = nullptr;
4933   if (rank.isMDSignedField())
4934     Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4935         Type::getInt64Ty(Context), rank.getMDSignedValue()));
4936   else if (rank.isMDField())
4937     Rank = rank.getMDFieldValue();
4938 
4939   // If this has an identifier try to build an ODR type.
4940   if (identifier.Val)
4941     if (auto *CT = DICompositeType::buildODRType(
4942             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4943             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4944             elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4945             discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4946             Rank)) {
4947       Result = CT;
4948       return false;
4949     }
4950 
4951   // Create a new node, and save it in the context if it belongs in the type
4952   // map.
4953   Result = GET_OR_DISTINCT(
4954       DICompositeType,
4955       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4956        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4957        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4958        discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4959        Rank));
4960   return false;
4961 }
4962 
4963 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4964 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4965   OPTIONAL(flags, DIFlagField, );                                              \
4966   OPTIONAL(cc, DwarfCCField, );                                                \
4967   REQUIRED(types, MDField, );
4968   PARSE_MD_FIELDS();
4969 #undef VISIT_MD_FIELDS
4970 
4971   Result = GET_OR_DISTINCT(DISubroutineType,
4972                            (Context, flags.Val, cc.Val, types.Val));
4973   return false;
4974 }
4975 
4976 /// parseDIFileType:
4977 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4978 ///                   checksumkind: CSK_MD5,
4979 ///                   checksum: "000102030405060708090a0b0c0d0e0f",
4980 ///                   source: "source file contents")
4981 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4982   // The default constructed value for checksumkind is required, but will never
4983   // be used, as the parser checks if the field was actually Seen before using
4984   // the Val.
4985 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4986   REQUIRED(filename, MDStringField, );                                         \
4987   REQUIRED(directory, MDStringField, );                                        \
4988   OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5));                \
4989   OPTIONAL(checksum, MDStringField, );                                         \
4990   OPTIONAL(source, MDStringField, );
4991   PARSE_MD_FIELDS();
4992 #undef VISIT_MD_FIELDS
4993 
4994   Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4995   if (checksumkind.Seen && checksum.Seen)
4996     OptChecksum.emplace(checksumkind.Val, checksum.Val);
4997   else if (checksumkind.Seen || checksum.Seen)
4998     return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4999 
5000   Optional<MDString *> OptSource;
5001   if (source.Seen)
5002     OptSource = source.Val;
5003   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
5004                                     OptChecksum, OptSource));
5005   return false;
5006 }
5007 
5008 /// parseDICompileUnit:
5009 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5010 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
5011 ///                      splitDebugFilename: "abc.debug",
5012 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5013 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5014 ///                      sysroot: "/", sdk: "MacOSX.sdk")
5015 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5016   if (!IsDistinct)
5017     return Lex.Error("missing 'distinct', required for !DICompileUnit");
5018 
5019 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5020   REQUIRED(language, DwarfLangField, );                                        \
5021   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
5022   OPTIONAL(producer, MDStringField, );                                         \
5023   OPTIONAL(isOptimized, MDBoolField, );                                        \
5024   OPTIONAL(flags, MDStringField, );                                            \
5025   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
5026   OPTIONAL(splitDebugFilename, MDStringField, );                               \
5027   OPTIONAL(emissionKind, EmissionKindField, );                                 \
5028   OPTIONAL(enums, MDField, );                                                  \
5029   OPTIONAL(retainedTypes, MDField, );                                          \
5030   OPTIONAL(globals, MDField, );                                                \
5031   OPTIONAL(imports, MDField, );                                                \
5032   OPTIONAL(macros, MDField, );                                                 \
5033   OPTIONAL(dwoId, MDUnsignedField, );                                          \
5034   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
5035   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);                       \
5036   OPTIONAL(nameTableKind, NameTableKindField, );                               \
5037   OPTIONAL(rangesBaseAddress, MDBoolField, = false);                           \
5038   OPTIONAL(sysroot, MDStringField, );                                          \
5039   OPTIONAL(sdk, MDStringField, );
5040   PARSE_MD_FIELDS();
5041 #undef VISIT_MD_FIELDS
5042 
5043   Result = DICompileUnit::getDistinct(
5044       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5045       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5046       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5047       splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5048       rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5049   return false;
5050 }
5051 
5052 /// parseDISubprogram:
5053 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5054 ///                     file: !1, line: 7, type: !2, isLocal: false,
5055 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
5056 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
5057 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
5058 ///                     spFlags: 10, isOptimized: false, templateParams: !4,
5059 ///                     declaration: !5, retainedNodes: !6, thrownTypes: !7)
5060 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5061   auto Loc = Lex.getLoc();
5062 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5063   OPTIONAL(scope, MDField, );                                                  \
5064   OPTIONAL(name, MDStringField, );                                             \
5065   OPTIONAL(linkageName, MDStringField, );                                      \
5066   OPTIONAL(file, MDField, );                                                   \
5067   OPTIONAL(line, LineField, );                                                 \
5068   OPTIONAL(type, MDField, );                                                   \
5069   OPTIONAL(isLocal, MDBoolField, );                                            \
5070   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
5071   OPTIONAL(scopeLine, LineField, );                                            \
5072   OPTIONAL(containingType, MDField, );                                         \
5073   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
5074   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
5075   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
5076   OPTIONAL(flags, DIFlagField, );                                              \
5077   OPTIONAL(spFlags, DISPFlagField, );                                          \
5078   OPTIONAL(isOptimized, MDBoolField, );                                        \
5079   OPTIONAL(unit, MDField, );                                                   \
5080   OPTIONAL(templateParams, MDField, );                                         \
5081   OPTIONAL(declaration, MDField, );                                            \
5082   OPTIONAL(retainedNodes, MDField, );                                          \
5083   OPTIONAL(thrownTypes, MDField, );
5084   PARSE_MD_FIELDS();
5085 #undef VISIT_MD_FIELDS
5086 
5087   // An explicit spFlags field takes precedence over individual fields in
5088   // older IR versions.
5089   DISubprogram::DISPFlags SPFlags =
5090       spFlags.Seen ? spFlags.Val
5091                    : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5092                                              isOptimized.Val, virtuality.Val);
5093   if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5094     return Lex.Error(
5095         Loc,
5096         "missing 'distinct', required for !DISubprogram that is a Definition");
5097   Result = GET_OR_DISTINCT(
5098       DISubprogram,
5099       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5100        type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5101        thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5102        declaration.Val, retainedNodes.Val, thrownTypes.Val));
5103   return false;
5104 }
5105 
5106 /// parseDILexicalBlock:
5107 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5108 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5109 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5110   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5111   OPTIONAL(file, MDField, );                                                   \
5112   OPTIONAL(line, LineField, );                                                 \
5113   OPTIONAL(column, ColumnField, );
5114   PARSE_MD_FIELDS();
5115 #undef VISIT_MD_FIELDS
5116 
5117   Result = GET_OR_DISTINCT(
5118       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5119   return false;
5120 }
5121 
5122 /// parseDILexicalBlockFile:
5123 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5124 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5125 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5126   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5127   OPTIONAL(file, MDField, );                                                   \
5128   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5129   PARSE_MD_FIELDS();
5130 #undef VISIT_MD_FIELDS
5131 
5132   Result = GET_OR_DISTINCT(DILexicalBlockFile,
5133                            (Context, scope.Val, file.Val, discriminator.Val));
5134   return false;
5135 }
5136 
5137 /// parseDICommonBlock:
5138 ///   ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5139 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5140 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5141   REQUIRED(scope, MDField, );                                                  \
5142   OPTIONAL(declaration, MDField, );                                            \
5143   OPTIONAL(name, MDStringField, );                                             \
5144   OPTIONAL(file, MDField, );                                                   \
5145   OPTIONAL(line, LineField, );
5146   PARSE_MD_FIELDS();
5147 #undef VISIT_MD_FIELDS
5148 
5149   Result = GET_OR_DISTINCT(DICommonBlock,
5150                            (Context, scope.Val, declaration.Val, name.Val,
5151                             file.Val, line.Val));
5152   return false;
5153 }
5154 
5155 /// parseDINamespace:
5156 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5157 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5158 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5159   REQUIRED(scope, MDField, );                                                  \
5160   OPTIONAL(name, MDStringField, );                                             \
5161   OPTIONAL(exportSymbols, MDBoolField, );
5162   PARSE_MD_FIELDS();
5163 #undef VISIT_MD_FIELDS
5164 
5165   Result = GET_OR_DISTINCT(DINamespace,
5166                            (Context, scope.Val, name.Val, exportSymbols.Val));
5167   return false;
5168 }
5169 
5170 /// parseDIMacro:
5171 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5172 ///   "SomeValue")
5173 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5174 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5175   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
5176   OPTIONAL(line, LineField, );                                                 \
5177   REQUIRED(name, MDStringField, );                                             \
5178   OPTIONAL(value, MDStringField, );
5179   PARSE_MD_FIELDS();
5180 #undef VISIT_MD_FIELDS
5181 
5182   Result = GET_OR_DISTINCT(DIMacro,
5183                            (Context, type.Val, line.Val, name.Val, value.Val));
5184   return false;
5185 }
5186 
5187 /// parseDIMacroFile:
5188 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5189 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5190 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5191   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
5192   OPTIONAL(line, LineField, );                                                 \
5193   REQUIRED(file, MDField, );                                                   \
5194   OPTIONAL(nodes, MDField, );
5195   PARSE_MD_FIELDS();
5196 #undef VISIT_MD_FIELDS
5197 
5198   Result = GET_OR_DISTINCT(DIMacroFile,
5199                            (Context, type.Val, line.Val, file.Val, nodes.Val));
5200   return false;
5201 }
5202 
5203 /// parseDIModule:
5204 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5205 ///   "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5206 ///   file: !1, line: 4, isDecl: false)
5207 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5208 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5209   REQUIRED(scope, MDField, );                                                  \
5210   REQUIRED(name, MDStringField, );                                             \
5211   OPTIONAL(configMacros, MDStringField, );                                     \
5212   OPTIONAL(includePath, MDStringField, );                                      \
5213   OPTIONAL(apinotes, MDStringField, );                                         \
5214   OPTIONAL(file, MDField, );                                                   \
5215   OPTIONAL(line, LineField, );                                                 \
5216   OPTIONAL(isDecl, MDBoolField, );
5217   PARSE_MD_FIELDS();
5218 #undef VISIT_MD_FIELDS
5219 
5220   Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5221                                       configMacros.Val, includePath.Val,
5222                                       apinotes.Val, line.Val, isDecl.Val));
5223   return false;
5224 }
5225 
5226 /// parseDITemplateTypeParameter:
5227 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5228 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5229 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5230   OPTIONAL(name, MDStringField, );                                             \
5231   REQUIRED(type, MDField, );                                                   \
5232   OPTIONAL(defaulted, MDBoolField, );
5233   PARSE_MD_FIELDS();
5234 #undef VISIT_MD_FIELDS
5235 
5236   Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5237                            (Context, name.Val, type.Val, defaulted.Val));
5238   return false;
5239 }
5240 
5241 /// parseDITemplateValueParameter:
5242 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5243 ///                                 name: "V", type: !1, defaulted: false,
5244 ///                                 value: i32 7)
5245 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5246 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5247   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
5248   OPTIONAL(name, MDStringField, );                                             \
5249   OPTIONAL(type, MDField, );                                                   \
5250   OPTIONAL(defaulted, MDBoolField, );                                          \
5251   REQUIRED(value, MDField, );
5252 
5253   PARSE_MD_FIELDS();
5254 #undef VISIT_MD_FIELDS
5255 
5256   Result = GET_OR_DISTINCT(
5257       DITemplateValueParameter,
5258       (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5259   return false;
5260 }
5261 
5262 /// parseDIGlobalVariable:
5263 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5264 ///                         file: !1, line: 7, type: !2, isLocal: false,
5265 ///                         isDefinition: true, templateParams: !3,
5266 ///                         declaration: !4, align: 8)
5267 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5268 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5269   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
5270   OPTIONAL(scope, MDField, );                                                  \
5271   OPTIONAL(linkageName, MDStringField, );                                      \
5272   OPTIONAL(file, MDField, );                                                   \
5273   OPTIONAL(line, LineField, );                                                 \
5274   OPTIONAL(type, MDField, );                                                   \
5275   OPTIONAL(isLocal, MDBoolField, );                                            \
5276   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
5277   OPTIONAL(templateParams, MDField, );                                         \
5278   OPTIONAL(declaration, MDField, );                                            \
5279   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
5280   PARSE_MD_FIELDS();
5281 #undef VISIT_MD_FIELDS
5282 
5283   Result =
5284       GET_OR_DISTINCT(DIGlobalVariable,
5285                       (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5286                        line.Val, type.Val, isLocal.Val, isDefinition.Val,
5287                        declaration.Val, templateParams.Val, align.Val));
5288   return false;
5289 }
5290 
5291 /// parseDILocalVariable:
5292 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5293 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5294 ///                        align: 8)
5295 ///   ::= !DILocalVariable(scope: !0, name: "foo",
5296 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5297 ///                        align: 8)
5298 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5299 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5300   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5301   OPTIONAL(name, MDStringField, );                                             \
5302   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
5303   OPTIONAL(file, MDField, );                                                   \
5304   OPTIONAL(line, LineField, );                                                 \
5305   OPTIONAL(type, MDField, );                                                   \
5306   OPTIONAL(flags, DIFlagField, );                                              \
5307   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
5308   PARSE_MD_FIELDS();
5309 #undef VISIT_MD_FIELDS
5310 
5311   Result = GET_OR_DISTINCT(DILocalVariable,
5312                            (Context, scope.Val, name.Val, file.Val, line.Val,
5313                             type.Val, arg.Val, flags.Val, align.Val));
5314   return false;
5315 }
5316 
5317 /// parseDILabel:
5318 ///   ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5319 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5320 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5321   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5322   REQUIRED(name, MDStringField, );                                             \
5323   REQUIRED(file, MDField, );                                                   \
5324   REQUIRED(line, LineField, );
5325   PARSE_MD_FIELDS();
5326 #undef VISIT_MD_FIELDS
5327 
5328   Result = GET_OR_DISTINCT(DILabel,
5329                            (Context, scope.Val, name.Val, file.Val, line.Val));
5330   return false;
5331 }
5332 
5333 /// parseDIExpression:
5334 ///   ::= !DIExpression(0, 7, -1)
5335 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5336   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5337   Lex.Lex();
5338 
5339   if (parseToken(lltok::lparen, "expected '(' here"))
5340     return true;
5341 
5342   SmallVector<uint64_t, 8> Elements;
5343   if (Lex.getKind() != lltok::rparen)
5344     do {
5345       if (Lex.getKind() == lltok::DwarfOp) {
5346         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5347           Lex.Lex();
5348           Elements.push_back(Op);
5349           continue;
5350         }
5351         return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5352       }
5353 
5354       if (Lex.getKind() == lltok::DwarfAttEncoding) {
5355         if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5356           Lex.Lex();
5357           Elements.push_back(Op);
5358           continue;
5359         }
5360         return tokError(Twine("invalid DWARF attribute encoding '") +
5361                         Lex.getStrVal() + "'");
5362       }
5363 
5364       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5365         return tokError("expected unsigned integer");
5366 
5367       auto &U = Lex.getAPSIntVal();
5368       if (U.ugt(UINT64_MAX))
5369         return tokError("element too large, limit is " + Twine(UINT64_MAX));
5370       Elements.push_back(U.getZExtValue());
5371       Lex.Lex();
5372     } while (EatIfPresent(lltok::comma));
5373 
5374   if (parseToken(lltok::rparen, "expected ')' here"))
5375     return true;
5376 
5377   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5378   return false;
5379 }
5380 
5381 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5382   return parseDIArgList(Result, IsDistinct, nullptr);
5383 }
5384 /// ParseDIArgList:
5385 ///   ::= !DIArgList(i32 7, i64 %0)
5386 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5387                               PerFunctionState *PFS) {
5388   assert(PFS && "Expected valid function state");
5389   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5390   Lex.Lex();
5391 
5392   if (parseToken(lltok::lparen, "expected '(' here"))
5393     return true;
5394 
5395   SmallVector<ValueAsMetadata *, 4> Args;
5396   if (Lex.getKind() != lltok::rparen)
5397     do {
5398       Metadata *MD;
5399       if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5400         return true;
5401       Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5402     } while (EatIfPresent(lltok::comma));
5403 
5404   if (parseToken(lltok::rparen, "expected ')' here"))
5405     return true;
5406 
5407   Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5408   return false;
5409 }
5410 
5411 /// parseDIGlobalVariableExpression:
5412 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5413 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5414                                                bool IsDistinct) {
5415 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5416   REQUIRED(var, MDField, );                                                    \
5417   REQUIRED(expr, MDField, );
5418   PARSE_MD_FIELDS();
5419 #undef VISIT_MD_FIELDS
5420 
5421   Result =
5422       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5423   return false;
5424 }
5425 
5426 /// parseDIObjCProperty:
5427 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5428 ///                       getter: "getFoo", attributes: 7, type: !2)
5429 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5430 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5431   OPTIONAL(name, MDStringField, );                                             \
5432   OPTIONAL(file, MDField, );                                                   \
5433   OPTIONAL(line, LineField, );                                                 \
5434   OPTIONAL(setter, MDStringField, );                                           \
5435   OPTIONAL(getter, MDStringField, );                                           \
5436   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
5437   OPTIONAL(type, MDField, );
5438   PARSE_MD_FIELDS();
5439 #undef VISIT_MD_FIELDS
5440 
5441   Result = GET_OR_DISTINCT(DIObjCProperty,
5442                            (Context, name.Val, file.Val, line.Val, setter.Val,
5443                             getter.Val, attributes.Val, type.Val));
5444   return false;
5445 }
5446 
5447 /// parseDIImportedEntity:
5448 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5449 ///                         line: 7, name: "foo")
5450 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5451 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5452   REQUIRED(tag, DwarfTagField, );                                              \
5453   REQUIRED(scope, MDField, );                                                  \
5454   OPTIONAL(entity, MDField, );                                                 \
5455   OPTIONAL(file, MDField, );                                                   \
5456   OPTIONAL(line, LineField, );                                                 \
5457   OPTIONAL(name, MDStringField, );
5458   PARSE_MD_FIELDS();
5459 #undef VISIT_MD_FIELDS
5460 
5461   Result = GET_OR_DISTINCT(
5462       DIImportedEntity,
5463       (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
5464   return false;
5465 }
5466 
5467 #undef PARSE_MD_FIELD
5468 #undef NOP_FIELD
5469 #undef REQUIRE_FIELD
5470 #undef DECLARE_FIELD
5471 
5472 /// parseMetadataAsValue
5473 ///  ::= metadata i32 %local
5474 ///  ::= metadata i32 @global
5475 ///  ::= metadata i32 7
5476 ///  ::= metadata !0
5477 ///  ::= metadata !{...}
5478 ///  ::= metadata !"string"
5479 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5480   // Note: the type 'metadata' has already been parsed.
5481   Metadata *MD;
5482   if (parseMetadata(MD, &PFS))
5483     return true;
5484 
5485   V = MetadataAsValue::get(Context, MD);
5486   return false;
5487 }
5488 
5489 /// parseValueAsMetadata
5490 ///  ::= i32 %local
5491 ///  ::= i32 @global
5492 ///  ::= i32 7
5493 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5494                                     PerFunctionState *PFS) {
5495   Type *Ty;
5496   LocTy Loc;
5497   if (parseType(Ty, TypeMsg, Loc))
5498     return true;
5499   if (Ty->isMetadataTy())
5500     return error(Loc, "invalid metadata-value-metadata roundtrip");
5501 
5502   Value *V;
5503   if (parseValue(Ty, V, PFS))
5504     return true;
5505 
5506   MD = ValueAsMetadata::get(V);
5507   return false;
5508 }
5509 
5510 /// parseMetadata
5511 ///  ::= i32 %local
5512 ///  ::= i32 @global
5513 ///  ::= i32 7
5514 ///  ::= !42
5515 ///  ::= !{...}
5516 ///  ::= !"string"
5517 ///  ::= !DILocation(...)
5518 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5519   if (Lex.getKind() == lltok::MetadataVar) {
5520     MDNode *N;
5521     // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5522     // so parsing this requires a Function State.
5523     if (Lex.getStrVal() == "DIArgList") {
5524       if (parseDIArgList(N, false, PFS))
5525         return true;
5526     } else if (parseSpecializedMDNode(N)) {
5527       return true;
5528     }
5529     MD = N;
5530     return false;
5531   }
5532 
5533   // ValueAsMetadata:
5534   // <type> <value>
5535   if (Lex.getKind() != lltok::exclaim)
5536     return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5537 
5538   // '!'.
5539   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5540   Lex.Lex();
5541 
5542   // MDString:
5543   //   ::= '!' STRINGCONSTANT
5544   if (Lex.getKind() == lltok::StringConstant) {
5545     MDString *S;
5546     if (parseMDString(S))
5547       return true;
5548     MD = S;
5549     return false;
5550   }
5551 
5552   // MDNode:
5553   // !{ ... }
5554   // !7
5555   MDNode *N;
5556   if (parseMDNodeTail(N))
5557     return true;
5558   MD = N;
5559   return false;
5560 }
5561 
5562 //===----------------------------------------------------------------------===//
5563 // Function Parsing.
5564 //===----------------------------------------------------------------------===//
5565 
5566 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5567                                    PerFunctionState *PFS, bool IsCall) {
5568   if (Ty->isFunctionTy())
5569     return error(ID.Loc, "functions are not values, refer to them as pointers");
5570 
5571   switch (ID.Kind) {
5572   case ValID::t_LocalID:
5573     if (!PFS)
5574       return error(ID.Loc, "invalid use of function-local name");
5575     V = PFS->getVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5576     return V == nullptr;
5577   case ValID::t_LocalName:
5578     if (!PFS)
5579       return error(ID.Loc, "invalid use of function-local name");
5580     V = PFS->getVal(ID.StrVal, Ty, ID.Loc, IsCall);
5581     return V == nullptr;
5582   case ValID::t_InlineAsm: {
5583     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5584       return error(ID.Loc, "invalid type for inline asm constraint string");
5585     V = InlineAsm::get(
5586         ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5587         InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5588     return false;
5589   }
5590   case ValID::t_GlobalName:
5591     V = getGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5592     return V == nullptr;
5593   case ValID::t_GlobalID:
5594     V = getGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5595     return V == nullptr;
5596   case ValID::t_APSInt:
5597     if (!Ty->isIntegerTy())
5598       return error(ID.Loc, "integer constant must have integer type");
5599     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5600     V = ConstantInt::get(Context, ID.APSIntVal);
5601     return false;
5602   case ValID::t_APFloat:
5603     if (!Ty->isFloatingPointTy() ||
5604         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5605       return error(ID.Loc, "floating point constant invalid for type");
5606 
5607     // The lexer has no type info, so builds all half, bfloat, float, and double
5608     // FP constants as double.  Fix this here.  Long double does not need this.
5609     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5610       // Check for signaling before potentially converting and losing that info.
5611       bool IsSNAN = ID.APFloatVal.isSignaling();
5612       bool Ignored;
5613       if (Ty->isHalfTy())
5614         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5615                               &Ignored);
5616       else if (Ty->isBFloatTy())
5617         ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5618                               &Ignored);
5619       else if (Ty->isFloatTy())
5620         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5621                               &Ignored);
5622       if (IsSNAN) {
5623         // The convert call above may quiet an SNaN, so manufacture another
5624         // SNaN. The bitcast works because the payload (significand) parameter
5625         // is truncated to fit.
5626         APInt Payload = ID.APFloatVal.bitcastToAPInt();
5627         ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5628                                          ID.APFloatVal.isNegative(), &Payload);
5629       }
5630     }
5631     V = ConstantFP::get(Context, ID.APFloatVal);
5632 
5633     if (V->getType() != Ty)
5634       return error(ID.Loc, "floating point constant does not have type '" +
5635                                getTypeString(Ty) + "'");
5636 
5637     return false;
5638   case ValID::t_Null:
5639     if (!Ty->isPointerTy())
5640       return error(ID.Loc, "null must be a pointer type");
5641     V = ConstantPointerNull::get(cast<PointerType>(Ty));
5642     return false;
5643   case ValID::t_Undef:
5644     // FIXME: LabelTy should not be a first-class type.
5645     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5646       return error(ID.Loc, "invalid type for undef constant");
5647     V = UndefValue::get(Ty);
5648     return false;
5649   case ValID::t_EmptyArray:
5650     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5651       return error(ID.Loc, "invalid empty array initializer");
5652     V = UndefValue::get(Ty);
5653     return false;
5654   case ValID::t_Zero:
5655     // FIXME: LabelTy should not be a first-class type.
5656     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5657       return error(ID.Loc, "invalid type for null constant");
5658     V = Constant::getNullValue(Ty);
5659     return false;
5660   case ValID::t_None:
5661     if (!Ty->isTokenTy())
5662       return error(ID.Loc, "invalid type for none constant");
5663     V = Constant::getNullValue(Ty);
5664     return false;
5665   case ValID::t_Poison:
5666     // FIXME: LabelTy should not be a first-class type.
5667     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5668       return error(ID.Loc, "invalid type for poison constant");
5669     V = PoisonValue::get(Ty);
5670     return false;
5671   case ValID::t_Constant:
5672     if (ID.ConstantVal->getType() != Ty)
5673       return error(ID.Loc, "constant expression type mismatch");
5674     V = ID.ConstantVal;
5675     return false;
5676   case ValID::t_ConstantStruct:
5677   case ValID::t_PackedConstantStruct:
5678     if (StructType *ST = dyn_cast<StructType>(Ty)) {
5679       if (ST->getNumElements() != ID.UIntVal)
5680         return error(ID.Loc,
5681                      "initializer with struct type has wrong # elements");
5682       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5683         return error(ID.Loc, "packed'ness of initializer and type don't match");
5684 
5685       // Verify that the elements are compatible with the structtype.
5686       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5687         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5688           return error(
5689               ID.Loc,
5690               "element " + Twine(i) +
5691                   " of struct initializer doesn't match struct element type");
5692 
5693       V = ConstantStruct::get(
5694           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5695     } else
5696       return error(ID.Loc, "constant expression type mismatch");
5697     return false;
5698   }
5699   llvm_unreachable("Invalid ValID");
5700 }
5701 
5702 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5703   C = nullptr;
5704   ValID ID;
5705   auto Loc = Lex.getLoc();
5706   if (parseValID(ID, /*PFS=*/nullptr))
5707     return true;
5708   switch (ID.Kind) {
5709   case ValID::t_APSInt:
5710   case ValID::t_APFloat:
5711   case ValID::t_Undef:
5712   case ValID::t_Constant:
5713   case ValID::t_ConstantStruct:
5714   case ValID::t_PackedConstantStruct: {
5715     Value *V;
5716     if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5717       return true;
5718     assert(isa<Constant>(V) && "Expected a constant value");
5719     C = cast<Constant>(V);
5720     return false;
5721   }
5722   case ValID::t_Null:
5723     C = Constant::getNullValue(Ty);
5724     return false;
5725   default:
5726     return error(Loc, "expected a constant value");
5727   }
5728 }
5729 
5730 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5731   V = nullptr;
5732   ValID ID;
5733   return parseValID(ID, PFS) ||
5734          convertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5735 }
5736 
5737 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5738   Type *Ty = nullptr;
5739   return parseType(Ty) || parseValue(Ty, V, PFS);
5740 }
5741 
5742 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5743                                       PerFunctionState &PFS) {
5744   Value *V;
5745   Loc = Lex.getLoc();
5746   if (parseTypeAndValue(V, PFS))
5747     return true;
5748   if (!isa<BasicBlock>(V))
5749     return error(Loc, "expected a basic block");
5750   BB = cast<BasicBlock>(V);
5751   return false;
5752 }
5753 
5754 /// FunctionHeader
5755 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5756 ///       OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5757 ///       '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5758 ///       OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5759 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5760   // parse the linkage.
5761   LocTy LinkageLoc = Lex.getLoc();
5762   unsigned Linkage;
5763   unsigned Visibility;
5764   unsigned DLLStorageClass;
5765   bool DSOLocal;
5766   AttrBuilder RetAttrs;
5767   unsigned CC;
5768   bool HasLinkage;
5769   Type *RetType = nullptr;
5770   LocTy RetTypeLoc = Lex.getLoc();
5771   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5772                            DSOLocal) ||
5773       parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5774       parseType(RetType, RetTypeLoc, true /*void allowed*/))
5775     return true;
5776 
5777   // Verify that the linkage is ok.
5778   switch ((GlobalValue::LinkageTypes)Linkage) {
5779   case GlobalValue::ExternalLinkage:
5780     break; // always ok.
5781   case GlobalValue::ExternalWeakLinkage:
5782     if (IsDefine)
5783       return error(LinkageLoc, "invalid linkage for function definition");
5784     break;
5785   case GlobalValue::PrivateLinkage:
5786   case GlobalValue::InternalLinkage:
5787   case GlobalValue::AvailableExternallyLinkage:
5788   case GlobalValue::LinkOnceAnyLinkage:
5789   case GlobalValue::LinkOnceODRLinkage:
5790   case GlobalValue::WeakAnyLinkage:
5791   case GlobalValue::WeakODRLinkage:
5792     if (!IsDefine)
5793       return error(LinkageLoc, "invalid linkage for function declaration");
5794     break;
5795   case GlobalValue::AppendingLinkage:
5796   case GlobalValue::CommonLinkage:
5797     return error(LinkageLoc, "invalid function linkage type");
5798   }
5799 
5800   if (!isValidVisibilityForLinkage(Visibility, Linkage))
5801     return error(LinkageLoc,
5802                  "symbol with local linkage must have default visibility");
5803 
5804   if (!FunctionType::isValidReturnType(RetType))
5805     return error(RetTypeLoc, "invalid function return type");
5806 
5807   LocTy NameLoc = Lex.getLoc();
5808 
5809   std::string FunctionName;
5810   if (Lex.getKind() == lltok::GlobalVar) {
5811     FunctionName = Lex.getStrVal();
5812   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
5813     unsigned NameID = Lex.getUIntVal();
5814 
5815     if (NameID != NumberedVals.size())
5816       return tokError("function expected to be numbered '%" +
5817                       Twine(NumberedVals.size()) + "'");
5818   } else {
5819     return tokError("expected function name");
5820   }
5821 
5822   Lex.Lex();
5823 
5824   if (Lex.getKind() != lltok::lparen)
5825     return tokError("expected '(' in function argument list");
5826 
5827   SmallVector<ArgInfo, 8> ArgList;
5828   bool IsVarArg;
5829   AttrBuilder FuncAttrs;
5830   std::vector<unsigned> FwdRefAttrGrps;
5831   LocTy BuiltinLoc;
5832   std::string Section;
5833   std::string Partition;
5834   MaybeAlign Alignment;
5835   std::string GC;
5836   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5837   unsigned AddrSpace = 0;
5838   Constant *Prefix = nullptr;
5839   Constant *Prologue = nullptr;
5840   Constant *PersonalityFn = nullptr;
5841   Comdat *C;
5842 
5843   if (parseArgumentList(ArgList, IsVarArg) ||
5844       parseOptionalUnnamedAddr(UnnamedAddr) ||
5845       parseOptionalProgramAddrSpace(AddrSpace) ||
5846       parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5847                                  BuiltinLoc) ||
5848       (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5849       (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5850       parseOptionalComdat(FunctionName, C) ||
5851       parseOptionalAlignment(Alignment) ||
5852       (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5853       (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5854       (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5855       (EatIfPresent(lltok::kw_personality) &&
5856        parseGlobalTypeAndValue(PersonalityFn)))
5857     return true;
5858 
5859   if (FuncAttrs.contains(Attribute::Builtin))
5860     return error(BuiltinLoc, "'builtin' attribute not valid on function");
5861 
5862   // If the alignment was parsed as an attribute, move to the alignment field.
5863   if (FuncAttrs.hasAlignmentAttr()) {
5864     Alignment = FuncAttrs.getAlignment();
5865     FuncAttrs.removeAttribute(Attribute::Alignment);
5866   }
5867 
5868   // Okay, if we got here, the function is syntactically valid.  Convert types
5869   // and do semantic checks.
5870   std::vector<Type*> ParamTypeList;
5871   SmallVector<AttributeSet, 8> Attrs;
5872 
5873   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5874     ParamTypeList.push_back(ArgList[i].Ty);
5875     Attrs.push_back(ArgList[i].Attrs);
5876   }
5877 
5878   AttributeList PAL =
5879       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5880                          AttributeSet::get(Context, RetAttrs), Attrs);
5881 
5882   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5883     return error(RetTypeLoc, "functions with 'sret' argument must return void");
5884 
5885   FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5886   PointerType *PFT = PointerType::get(FT, AddrSpace);
5887 
5888   Fn = nullptr;
5889   if (!FunctionName.empty()) {
5890     // If this was a definition of a forward reference, remove the definition
5891     // from the forward reference table and fill in the forward ref.
5892     auto FRVI = ForwardRefVals.find(FunctionName);
5893     if (FRVI != ForwardRefVals.end()) {
5894       Fn = M->getFunction(FunctionName);
5895       if (!Fn)
5896         return error(FRVI->second.second, "invalid forward reference to "
5897                                           "function as global value!");
5898       if (Fn->getType() != PFT)
5899         return error(FRVI->second.second,
5900                      "invalid forward reference to "
5901                      "function '" +
5902                          FunctionName +
5903                          "' with wrong type: "
5904                          "expected '" +
5905                          getTypeString(PFT) + "' but was '" +
5906                          getTypeString(Fn->getType()) + "'");
5907       ForwardRefVals.erase(FRVI);
5908     } else if ((Fn = M->getFunction(FunctionName))) {
5909       // Reject redefinitions.
5910       return error(NameLoc,
5911                    "invalid redefinition of function '" + FunctionName + "'");
5912     } else if (M->getNamedValue(FunctionName)) {
5913       return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5914     }
5915 
5916   } else {
5917     // If this is a definition of a forward referenced function, make sure the
5918     // types agree.
5919     auto I = ForwardRefValIDs.find(NumberedVals.size());
5920     if (I != ForwardRefValIDs.end()) {
5921       Fn = cast<Function>(I->second.first);
5922       if (Fn->getType() != PFT)
5923         return error(NameLoc, "type of definition and forward reference of '@" +
5924                                   Twine(NumberedVals.size()) +
5925                                   "' disagree: "
5926                                   "expected '" +
5927                                   getTypeString(PFT) + "' but was '" +
5928                                   getTypeString(Fn->getType()) + "'");
5929       ForwardRefValIDs.erase(I);
5930     }
5931   }
5932 
5933   if (!Fn)
5934     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5935                           FunctionName, M);
5936   else // Move the forward-reference to the correct spot in the module.
5937     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5938 
5939   assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5940 
5941   if (FunctionName.empty())
5942     NumberedVals.push_back(Fn);
5943 
5944   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5945   maybeSetDSOLocal(DSOLocal, *Fn);
5946   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5947   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5948   Fn->setCallingConv(CC);
5949   Fn->setAttributes(PAL);
5950   Fn->setUnnamedAddr(UnnamedAddr);
5951   Fn->setAlignment(MaybeAlign(Alignment));
5952   Fn->setSection(Section);
5953   Fn->setPartition(Partition);
5954   Fn->setComdat(C);
5955   Fn->setPersonalityFn(PersonalityFn);
5956   if (!GC.empty()) Fn->setGC(GC);
5957   Fn->setPrefixData(Prefix);
5958   Fn->setPrologueData(Prologue);
5959   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5960 
5961   // Add all of the arguments we parsed to the function.
5962   Function::arg_iterator ArgIt = Fn->arg_begin();
5963   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5964     // If the argument has a name, insert it into the argument symbol table.
5965     if (ArgList[i].Name.empty()) continue;
5966 
5967     // Set the name, if it conflicted, it will be auto-renamed.
5968     ArgIt->setName(ArgList[i].Name);
5969 
5970     if (ArgIt->getName() != ArgList[i].Name)
5971       return error(ArgList[i].Loc,
5972                    "redefinition of argument '%" + ArgList[i].Name + "'");
5973   }
5974 
5975   if (IsDefine)
5976     return false;
5977 
5978   // Check the declaration has no block address forward references.
5979   ValID ID;
5980   if (FunctionName.empty()) {
5981     ID.Kind = ValID::t_GlobalID;
5982     ID.UIntVal = NumberedVals.size() - 1;
5983   } else {
5984     ID.Kind = ValID::t_GlobalName;
5985     ID.StrVal = FunctionName;
5986   }
5987   auto Blocks = ForwardRefBlockAddresses.find(ID);
5988   if (Blocks != ForwardRefBlockAddresses.end())
5989     return error(Blocks->first.Loc,
5990                  "cannot take blockaddress inside a declaration");
5991   return false;
5992 }
5993 
5994 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5995   ValID ID;
5996   if (FunctionNumber == -1) {
5997     ID.Kind = ValID::t_GlobalName;
5998     ID.StrVal = std::string(F.getName());
5999   } else {
6000     ID.Kind = ValID::t_GlobalID;
6001     ID.UIntVal = FunctionNumber;
6002   }
6003 
6004   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6005   if (Blocks == P.ForwardRefBlockAddresses.end())
6006     return false;
6007 
6008   for (const auto &I : Blocks->second) {
6009     const ValID &BBID = I.first;
6010     GlobalValue *GV = I.second;
6011 
6012     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6013            "Expected local id or name");
6014     BasicBlock *BB;
6015     if (BBID.Kind == ValID::t_LocalName)
6016       BB = getBB(BBID.StrVal, BBID.Loc);
6017     else
6018       BB = getBB(BBID.UIntVal, BBID.Loc);
6019     if (!BB)
6020       return P.error(BBID.Loc, "referenced value is not a basic block");
6021 
6022     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
6023     GV->eraseFromParent();
6024   }
6025 
6026   P.ForwardRefBlockAddresses.erase(Blocks);
6027   return false;
6028 }
6029 
6030 /// parseFunctionBody
6031 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
6032 bool LLParser::parseFunctionBody(Function &Fn) {
6033   if (Lex.getKind() != lltok::lbrace)
6034     return tokError("expected '{' in function body");
6035   Lex.Lex();  // eat the {.
6036 
6037   int FunctionNumber = -1;
6038   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
6039 
6040   PerFunctionState PFS(*this, Fn, FunctionNumber);
6041 
6042   // Resolve block addresses and allow basic blocks to be forward-declared
6043   // within this function.
6044   if (PFS.resolveForwardRefBlockAddresses())
6045     return true;
6046   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
6047 
6048   // We need at least one basic block.
6049   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6050     return tokError("function body requires at least one basic block");
6051 
6052   while (Lex.getKind() != lltok::rbrace &&
6053          Lex.getKind() != lltok::kw_uselistorder)
6054     if (parseBasicBlock(PFS))
6055       return true;
6056 
6057   while (Lex.getKind() != lltok::rbrace)
6058     if (parseUseListOrder(&PFS))
6059       return true;
6060 
6061   // Eat the }.
6062   Lex.Lex();
6063 
6064   // Verify function is ok.
6065   return PFS.finishFunction();
6066 }
6067 
6068 /// parseBasicBlock
6069 ///   ::= (LabelStr|LabelID)? Instruction*
6070 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6071   // If this basic block starts out with a name, remember it.
6072   std::string Name;
6073   int NameID = -1;
6074   LocTy NameLoc = Lex.getLoc();
6075   if (Lex.getKind() == lltok::LabelStr) {
6076     Name = Lex.getStrVal();
6077     Lex.Lex();
6078   } else if (Lex.getKind() == lltok::LabelID) {
6079     NameID = Lex.getUIntVal();
6080     Lex.Lex();
6081   }
6082 
6083   BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6084   if (!BB)
6085     return true;
6086 
6087   std::string NameStr;
6088 
6089   // parse the instructions in this block until we get a terminator.
6090   Instruction *Inst;
6091   do {
6092     // This instruction may have three possibilities for a name: a) none
6093     // specified, b) name specified "%foo =", c) number specified: "%4 =".
6094     LocTy NameLoc = Lex.getLoc();
6095     int NameID = -1;
6096     NameStr = "";
6097 
6098     if (Lex.getKind() == lltok::LocalVarID) {
6099       NameID = Lex.getUIntVal();
6100       Lex.Lex();
6101       if (parseToken(lltok::equal, "expected '=' after instruction id"))
6102         return true;
6103     } else if (Lex.getKind() == lltok::LocalVar) {
6104       NameStr = Lex.getStrVal();
6105       Lex.Lex();
6106       if (parseToken(lltok::equal, "expected '=' after instruction name"))
6107         return true;
6108     }
6109 
6110     switch (parseInstruction(Inst, BB, PFS)) {
6111     default:
6112       llvm_unreachable("Unknown parseInstruction result!");
6113     case InstError: return true;
6114     case InstNormal:
6115       BB->getInstList().push_back(Inst);
6116 
6117       // With a normal result, we check to see if the instruction is followed by
6118       // a comma and metadata.
6119       if (EatIfPresent(lltok::comma))
6120         if (parseInstructionMetadata(*Inst))
6121           return true;
6122       break;
6123     case InstExtraComma:
6124       BB->getInstList().push_back(Inst);
6125 
6126       // If the instruction parser ate an extra comma at the end of it, it
6127       // *must* be followed by metadata.
6128       if (parseInstructionMetadata(*Inst))
6129         return true;
6130       break;
6131     }
6132 
6133     // Set the name on the instruction.
6134     if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6135       return true;
6136   } while (!Inst->isTerminator());
6137 
6138   return false;
6139 }
6140 
6141 //===----------------------------------------------------------------------===//
6142 // Instruction Parsing.
6143 //===----------------------------------------------------------------------===//
6144 
6145 /// parseInstruction - parse one of the many different instructions.
6146 ///
6147 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6148                                PerFunctionState &PFS) {
6149   lltok::Kind Token = Lex.getKind();
6150   if (Token == lltok::Eof)
6151     return tokError("found end of file when expecting more instructions");
6152   LocTy Loc = Lex.getLoc();
6153   unsigned KeywordVal = Lex.getUIntVal();
6154   Lex.Lex();  // Eat the keyword.
6155 
6156   switch (Token) {
6157   default:
6158     return error(Loc, "expected instruction opcode");
6159   // Terminator Instructions.
6160   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6161   case lltok::kw_ret:
6162     return parseRet(Inst, BB, PFS);
6163   case lltok::kw_br:
6164     return parseBr(Inst, PFS);
6165   case lltok::kw_switch:
6166     return parseSwitch(Inst, PFS);
6167   case lltok::kw_indirectbr:
6168     return parseIndirectBr(Inst, PFS);
6169   case lltok::kw_invoke:
6170     return parseInvoke(Inst, PFS);
6171   case lltok::kw_resume:
6172     return parseResume(Inst, PFS);
6173   case lltok::kw_cleanupret:
6174     return parseCleanupRet(Inst, PFS);
6175   case lltok::kw_catchret:
6176     return parseCatchRet(Inst, PFS);
6177   case lltok::kw_catchswitch:
6178     return parseCatchSwitch(Inst, PFS);
6179   case lltok::kw_catchpad:
6180     return parseCatchPad(Inst, PFS);
6181   case lltok::kw_cleanuppad:
6182     return parseCleanupPad(Inst, PFS);
6183   case lltok::kw_callbr:
6184     return parseCallBr(Inst, PFS);
6185   // Unary Operators.
6186   case lltok::kw_fneg: {
6187     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6188     int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6189     if (Res != 0)
6190       return Res;
6191     if (FMF.any())
6192       Inst->setFastMathFlags(FMF);
6193     return false;
6194   }
6195   // Binary Operators.
6196   case lltok::kw_add:
6197   case lltok::kw_sub:
6198   case lltok::kw_mul:
6199   case lltok::kw_shl: {
6200     bool NUW = EatIfPresent(lltok::kw_nuw);
6201     bool NSW = EatIfPresent(lltok::kw_nsw);
6202     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6203 
6204     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6205       return true;
6206 
6207     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6208     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6209     return false;
6210   }
6211   case lltok::kw_fadd:
6212   case lltok::kw_fsub:
6213   case lltok::kw_fmul:
6214   case lltok::kw_fdiv:
6215   case lltok::kw_frem: {
6216     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6217     int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6218     if (Res != 0)
6219       return Res;
6220     if (FMF.any())
6221       Inst->setFastMathFlags(FMF);
6222     return 0;
6223   }
6224 
6225   case lltok::kw_sdiv:
6226   case lltok::kw_udiv:
6227   case lltok::kw_lshr:
6228   case lltok::kw_ashr: {
6229     bool Exact = EatIfPresent(lltok::kw_exact);
6230 
6231     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6232       return true;
6233     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6234     return false;
6235   }
6236 
6237   case lltok::kw_urem:
6238   case lltok::kw_srem:
6239     return parseArithmetic(Inst, PFS, KeywordVal,
6240                            /*IsFP*/ false);
6241   case lltok::kw_and:
6242   case lltok::kw_or:
6243   case lltok::kw_xor:
6244     return parseLogical(Inst, PFS, KeywordVal);
6245   case lltok::kw_icmp:
6246     return parseCompare(Inst, PFS, KeywordVal);
6247   case lltok::kw_fcmp: {
6248     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6249     int Res = parseCompare(Inst, PFS, KeywordVal);
6250     if (Res != 0)
6251       return Res;
6252     if (FMF.any())
6253       Inst->setFastMathFlags(FMF);
6254     return 0;
6255   }
6256 
6257   // Casts.
6258   case lltok::kw_trunc:
6259   case lltok::kw_zext:
6260   case lltok::kw_sext:
6261   case lltok::kw_fptrunc:
6262   case lltok::kw_fpext:
6263   case lltok::kw_bitcast:
6264   case lltok::kw_addrspacecast:
6265   case lltok::kw_uitofp:
6266   case lltok::kw_sitofp:
6267   case lltok::kw_fptoui:
6268   case lltok::kw_fptosi:
6269   case lltok::kw_inttoptr:
6270   case lltok::kw_ptrtoint:
6271     return parseCast(Inst, PFS, KeywordVal);
6272   // Other.
6273   case lltok::kw_select: {
6274     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6275     int Res = parseSelect(Inst, PFS);
6276     if (Res != 0)
6277       return Res;
6278     if (FMF.any()) {
6279       if (!isa<FPMathOperator>(Inst))
6280         return error(Loc, "fast-math-flags specified for select without "
6281                           "floating-point scalar or vector return type");
6282       Inst->setFastMathFlags(FMF);
6283     }
6284     return 0;
6285   }
6286   case lltok::kw_va_arg:
6287     return parseVAArg(Inst, PFS);
6288   case lltok::kw_extractelement:
6289     return parseExtractElement(Inst, PFS);
6290   case lltok::kw_insertelement:
6291     return parseInsertElement(Inst, PFS);
6292   case lltok::kw_shufflevector:
6293     return parseShuffleVector(Inst, PFS);
6294   case lltok::kw_phi: {
6295     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6296     int Res = parsePHI(Inst, PFS);
6297     if (Res != 0)
6298       return Res;
6299     if (FMF.any()) {
6300       if (!isa<FPMathOperator>(Inst))
6301         return error(Loc, "fast-math-flags specified for phi without "
6302                           "floating-point scalar or vector return type");
6303       Inst->setFastMathFlags(FMF);
6304     }
6305     return 0;
6306   }
6307   case lltok::kw_landingpad:
6308     return parseLandingPad(Inst, PFS);
6309   case lltok::kw_freeze:
6310     return parseFreeze(Inst, PFS);
6311   // Call.
6312   case lltok::kw_call:
6313     return parseCall(Inst, PFS, CallInst::TCK_None);
6314   case lltok::kw_tail:
6315     return parseCall(Inst, PFS, CallInst::TCK_Tail);
6316   case lltok::kw_musttail:
6317     return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6318   case lltok::kw_notail:
6319     return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6320   // Memory.
6321   case lltok::kw_alloca:
6322     return parseAlloc(Inst, PFS);
6323   case lltok::kw_load:
6324     return parseLoad(Inst, PFS);
6325   case lltok::kw_store:
6326     return parseStore(Inst, PFS);
6327   case lltok::kw_cmpxchg:
6328     return parseCmpXchg(Inst, PFS);
6329   case lltok::kw_atomicrmw:
6330     return parseAtomicRMW(Inst, PFS);
6331   case lltok::kw_fence:
6332     return parseFence(Inst, PFS);
6333   case lltok::kw_getelementptr:
6334     return parseGetElementPtr(Inst, PFS);
6335   case lltok::kw_extractvalue:
6336     return parseExtractValue(Inst, PFS);
6337   case lltok::kw_insertvalue:
6338     return parseInsertValue(Inst, PFS);
6339   }
6340 }
6341 
6342 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6343 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6344   if (Opc == Instruction::FCmp) {
6345     switch (Lex.getKind()) {
6346     default:
6347       return tokError("expected fcmp predicate (e.g. 'oeq')");
6348     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6349     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6350     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6351     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6352     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6353     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6354     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6355     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6356     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6357     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6358     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6359     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6360     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6361     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6362     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6363     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6364     }
6365   } else {
6366     switch (Lex.getKind()) {
6367     default:
6368       return tokError("expected icmp predicate (e.g. 'eq')");
6369     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
6370     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
6371     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6372     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6373     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6374     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6375     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6376     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6377     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6378     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6379     }
6380   }
6381   Lex.Lex();
6382   return false;
6383 }
6384 
6385 //===----------------------------------------------------------------------===//
6386 // Terminator Instructions.
6387 //===----------------------------------------------------------------------===//
6388 
6389 /// parseRet - parse a return instruction.
6390 ///   ::= 'ret' void (',' !dbg, !1)*
6391 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
6392 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6393                         PerFunctionState &PFS) {
6394   SMLoc TypeLoc = Lex.getLoc();
6395   Type *Ty = nullptr;
6396   if (parseType(Ty, true /*void allowed*/))
6397     return true;
6398 
6399   Type *ResType = PFS.getFunction().getReturnType();
6400 
6401   if (Ty->isVoidTy()) {
6402     if (!ResType->isVoidTy())
6403       return error(TypeLoc, "value doesn't match function result type '" +
6404                                 getTypeString(ResType) + "'");
6405 
6406     Inst = ReturnInst::Create(Context);
6407     return false;
6408   }
6409 
6410   Value *RV;
6411   if (parseValue(Ty, RV, PFS))
6412     return true;
6413 
6414   if (ResType != RV->getType())
6415     return error(TypeLoc, "value doesn't match function result type '" +
6416                               getTypeString(ResType) + "'");
6417 
6418   Inst = ReturnInst::Create(Context, RV);
6419   return false;
6420 }
6421 
6422 /// parseBr
6423 ///   ::= 'br' TypeAndValue
6424 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6425 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6426   LocTy Loc, Loc2;
6427   Value *Op0;
6428   BasicBlock *Op1, *Op2;
6429   if (parseTypeAndValue(Op0, Loc, PFS))
6430     return true;
6431 
6432   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6433     Inst = BranchInst::Create(BB);
6434     return false;
6435   }
6436 
6437   if (Op0->getType() != Type::getInt1Ty(Context))
6438     return error(Loc, "branch condition must have 'i1' type");
6439 
6440   if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6441       parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6442       parseToken(lltok::comma, "expected ',' after true destination") ||
6443       parseTypeAndBasicBlock(Op2, Loc2, PFS))
6444     return true;
6445 
6446   Inst = BranchInst::Create(Op1, Op2, Op0);
6447   return false;
6448 }
6449 
6450 /// parseSwitch
6451 ///  Instruction
6452 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6453 ///  JumpTable
6454 ///    ::= (TypeAndValue ',' TypeAndValue)*
6455 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6456   LocTy CondLoc, BBLoc;
6457   Value *Cond;
6458   BasicBlock *DefaultBB;
6459   if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6460       parseToken(lltok::comma, "expected ',' after switch condition") ||
6461       parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6462       parseToken(lltok::lsquare, "expected '[' with switch table"))
6463     return true;
6464 
6465   if (!Cond->getType()->isIntegerTy())
6466     return error(CondLoc, "switch condition must have integer type");
6467 
6468   // parse the jump table pairs.
6469   SmallPtrSet<Value*, 32> SeenCases;
6470   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6471   while (Lex.getKind() != lltok::rsquare) {
6472     Value *Constant;
6473     BasicBlock *DestBB;
6474 
6475     if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6476         parseToken(lltok::comma, "expected ',' after case value") ||
6477         parseTypeAndBasicBlock(DestBB, PFS))
6478       return true;
6479 
6480     if (!SeenCases.insert(Constant).second)
6481       return error(CondLoc, "duplicate case value in switch");
6482     if (!isa<ConstantInt>(Constant))
6483       return error(CondLoc, "case value is not a constant integer");
6484 
6485     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6486   }
6487 
6488   Lex.Lex();  // Eat the ']'.
6489 
6490   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6491   for (unsigned i = 0, e = Table.size(); i != e; ++i)
6492     SI->addCase(Table[i].first, Table[i].second);
6493   Inst = SI;
6494   return false;
6495 }
6496 
6497 /// parseIndirectBr
6498 ///  Instruction
6499 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6500 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6501   LocTy AddrLoc;
6502   Value *Address;
6503   if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6504       parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6505       parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6506     return true;
6507 
6508   if (!Address->getType()->isPointerTy())
6509     return error(AddrLoc, "indirectbr address must have pointer type");
6510 
6511   // parse the destination list.
6512   SmallVector<BasicBlock*, 16> DestList;
6513 
6514   if (Lex.getKind() != lltok::rsquare) {
6515     BasicBlock *DestBB;
6516     if (parseTypeAndBasicBlock(DestBB, PFS))
6517       return true;
6518     DestList.push_back(DestBB);
6519 
6520     while (EatIfPresent(lltok::comma)) {
6521       if (parseTypeAndBasicBlock(DestBB, PFS))
6522         return true;
6523       DestList.push_back(DestBB);
6524     }
6525   }
6526 
6527   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6528     return true;
6529 
6530   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6531   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6532     IBI->addDestination(DestList[i]);
6533   Inst = IBI;
6534   return false;
6535 }
6536 
6537 /// parseInvoke
6538 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6539 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6540 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6541   LocTy CallLoc = Lex.getLoc();
6542   AttrBuilder RetAttrs, FnAttrs;
6543   std::vector<unsigned> FwdRefAttrGrps;
6544   LocTy NoBuiltinLoc;
6545   unsigned CC;
6546   unsigned InvokeAddrSpace;
6547   Type *RetType = nullptr;
6548   LocTy RetTypeLoc;
6549   ValID CalleeID;
6550   SmallVector<ParamInfo, 16> ArgList;
6551   SmallVector<OperandBundleDef, 2> BundleList;
6552 
6553   BasicBlock *NormalBB, *UnwindBB;
6554   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6555       parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6556       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6557       parseValID(CalleeID) || parseParameterList(ArgList, PFS) ||
6558       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6559                                  NoBuiltinLoc) ||
6560       parseOptionalOperandBundles(BundleList, PFS) ||
6561       parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6562       parseTypeAndBasicBlock(NormalBB, PFS) ||
6563       parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6564       parseTypeAndBasicBlock(UnwindBB, PFS))
6565     return true;
6566 
6567   // If RetType is a non-function pointer type, then this is the short syntax
6568   // for the call, which means that RetType is just the return type.  Infer the
6569   // rest of the function argument types from the arguments that are present.
6570   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6571   if (!Ty) {
6572     // Pull out the types of all of the arguments...
6573     std::vector<Type*> ParamTypes;
6574     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6575       ParamTypes.push_back(ArgList[i].V->getType());
6576 
6577     if (!FunctionType::isValidReturnType(RetType))
6578       return error(RetTypeLoc, "Invalid result type for LLVM function");
6579 
6580     Ty = FunctionType::get(RetType, ParamTypes, false);
6581   }
6582 
6583   CalleeID.FTy = Ty;
6584 
6585   // Look up the callee.
6586   Value *Callee;
6587   if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6588                           Callee, &PFS, /*IsCall=*/true))
6589     return true;
6590 
6591   // Set up the Attribute for the function.
6592   SmallVector<Value *, 8> Args;
6593   SmallVector<AttributeSet, 8> ArgAttrs;
6594 
6595   // Loop through FunctionType's arguments and ensure they are specified
6596   // correctly.  Also, gather any parameter attributes.
6597   FunctionType::param_iterator I = Ty->param_begin();
6598   FunctionType::param_iterator E = Ty->param_end();
6599   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6600     Type *ExpectedTy = nullptr;
6601     if (I != E) {
6602       ExpectedTy = *I++;
6603     } else if (!Ty->isVarArg()) {
6604       return error(ArgList[i].Loc, "too many arguments specified");
6605     }
6606 
6607     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6608       return error(ArgList[i].Loc, "argument is not of expected type '" +
6609                                        getTypeString(ExpectedTy) + "'");
6610     Args.push_back(ArgList[i].V);
6611     ArgAttrs.push_back(ArgList[i].Attrs);
6612   }
6613 
6614   if (I != E)
6615     return error(CallLoc, "not enough parameters specified for call");
6616 
6617   if (FnAttrs.hasAlignmentAttr())
6618     return error(CallLoc, "invoke instructions may not have an alignment");
6619 
6620   // Finish off the Attribute and check them
6621   AttributeList PAL =
6622       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6623                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6624 
6625   InvokeInst *II =
6626       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6627   II->setCallingConv(CC);
6628   II->setAttributes(PAL);
6629   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6630   Inst = II;
6631   return false;
6632 }
6633 
6634 /// parseResume
6635 ///   ::= 'resume' TypeAndValue
6636 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6637   Value *Exn; LocTy ExnLoc;
6638   if (parseTypeAndValue(Exn, ExnLoc, PFS))
6639     return true;
6640 
6641   ResumeInst *RI = ResumeInst::Create(Exn);
6642   Inst = RI;
6643   return false;
6644 }
6645 
6646 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6647                                   PerFunctionState &PFS) {
6648   if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6649     return true;
6650 
6651   while (Lex.getKind() != lltok::rsquare) {
6652     // If this isn't the first argument, we need a comma.
6653     if (!Args.empty() &&
6654         parseToken(lltok::comma, "expected ',' in argument list"))
6655       return true;
6656 
6657     // parse the argument.
6658     LocTy ArgLoc;
6659     Type *ArgTy = nullptr;
6660     if (parseType(ArgTy, ArgLoc))
6661       return true;
6662 
6663     Value *V;
6664     if (ArgTy->isMetadataTy()) {
6665       if (parseMetadataAsValue(V, PFS))
6666         return true;
6667     } else {
6668       if (parseValue(ArgTy, V, PFS))
6669         return true;
6670     }
6671     Args.push_back(V);
6672   }
6673 
6674   Lex.Lex();  // Lex the ']'.
6675   return false;
6676 }
6677 
6678 /// parseCleanupRet
6679 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6680 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6681   Value *CleanupPad = nullptr;
6682 
6683   if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6684     return true;
6685 
6686   if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6687     return true;
6688 
6689   if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6690     return true;
6691 
6692   BasicBlock *UnwindBB = nullptr;
6693   if (Lex.getKind() == lltok::kw_to) {
6694     Lex.Lex();
6695     if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6696       return true;
6697   } else {
6698     if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6699       return true;
6700     }
6701   }
6702 
6703   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6704   return false;
6705 }
6706 
6707 /// parseCatchRet
6708 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
6709 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6710   Value *CatchPad = nullptr;
6711 
6712   if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6713     return true;
6714 
6715   if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6716     return true;
6717 
6718   BasicBlock *BB;
6719   if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6720       parseTypeAndBasicBlock(BB, PFS))
6721     return true;
6722 
6723   Inst = CatchReturnInst::Create(CatchPad, BB);
6724   return false;
6725 }
6726 
6727 /// parseCatchSwitch
6728 ///   ::= 'catchswitch' within Parent
6729 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6730   Value *ParentPad;
6731 
6732   if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6733     return true;
6734 
6735   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6736       Lex.getKind() != lltok::LocalVarID)
6737     return tokError("expected scope value for catchswitch");
6738 
6739   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6740     return true;
6741 
6742   if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6743     return true;
6744 
6745   SmallVector<BasicBlock *, 32> Table;
6746   do {
6747     BasicBlock *DestBB;
6748     if (parseTypeAndBasicBlock(DestBB, PFS))
6749       return true;
6750     Table.push_back(DestBB);
6751   } while (EatIfPresent(lltok::comma));
6752 
6753   if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6754     return true;
6755 
6756   if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6757     return true;
6758 
6759   BasicBlock *UnwindBB = nullptr;
6760   if (EatIfPresent(lltok::kw_to)) {
6761     if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6762       return true;
6763   } else {
6764     if (parseTypeAndBasicBlock(UnwindBB, PFS))
6765       return true;
6766   }
6767 
6768   auto *CatchSwitch =
6769       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6770   for (BasicBlock *DestBB : Table)
6771     CatchSwitch->addHandler(DestBB);
6772   Inst = CatchSwitch;
6773   return false;
6774 }
6775 
6776 /// parseCatchPad
6777 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6778 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6779   Value *CatchSwitch = nullptr;
6780 
6781   if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6782     return true;
6783 
6784   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6785     return tokError("expected scope value for catchpad");
6786 
6787   if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6788     return true;
6789 
6790   SmallVector<Value *, 8> Args;
6791   if (parseExceptionArgs(Args, PFS))
6792     return true;
6793 
6794   Inst = CatchPadInst::Create(CatchSwitch, Args);
6795   return false;
6796 }
6797 
6798 /// parseCleanupPad
6799 ///   ::= 'cleanuppad' within Parent ParamList
6800 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6801   Value *ParentPad = nullptr;
6802 
6803   if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6804     return true;
6805 
6806   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6807       Lex.getKind() != lltok::LocalVarID)
6808     return tokError("expected scope value for cleanuppad");
6809 
6810   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6811     return true;
6812 
6813   SmallVector<Value *, 8> Args;
6814   if (parseExceptionArgs(Args, PFS))
6815     return true;
6816 
6817   Inst = CleanupPadInst::Create(ParentPad, Args);
6818   return false;
6819 }
6820 
6821 //===----------------------------------------------------------------------===//
6822 // Unary Operators.
6823 //===----------------------------------------------------------------------===//
6824 
6825 /// parseUnaryOp
6826 ///  ::= UnaryOp TypeAndValue ',' Value
6827 ///
6828 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6829 /// operand is allowed.
6830 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6831                             unsigned Opc, bool IsFP) {
6832   LocTy Loc; Value *LHS;
6833   if (parseTypeAndValue(LHS, Loc, PFS))
6834     return true;
6835 
6836   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6837                     : LHS->getType()->isIntOrIntVectorTy();
6838 
6839   if (!Valid)
6840     return error(Loc, "invalid operand type for instruction");
6841 
6842   Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6843   return false;
6844 }
6845 
6846 /// parseCallBr
6847 ///   ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6848 ///       OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6849 ///       '[' LabelList ']'
6850 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6851   LocTy CallLoc = Lex.getLoc();
6852   AttrBuilder RetAttrs, FnAttrs;
6853   std::vector<unsigned> FwdRefAttrGrps;
6854   LocTy NoBuiltinLoc;
6855   unsigned CC;
6856   Type *RetType = nullptr;
6857   LocTy RetTypeLoc;
6858   ValID CalleeID;
6859   SmallVector<ParamInfo, 16> ArgList;
6860   SmallVector<OperandBundleDef, 2> BundleList;
6861 
6862   BasicBlock *DefaultDest;
6863   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6864       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6865       parseValID(CalleeID) || parseParameterList(ArgList, PFS) ||
6866       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6867                                  NoBuiltinLoc) ||
6868       parseOptionalOperandBundles(BundleList, PFS) ||
6869       parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6870       parseTypeAndBasicBlock(DefaultDest, PFS) ||
6871       parseToken(lltok::lsquare, "expected '[' in callbr"))
6872     return true;
6873 
6874   // parse the destination list.
6875   SmallVector<BasicBlock *, 16> IndirectDests;
6876 
6877   if (Lex.getKind() != lltok::rsquare) {
6878     BasicBlock *DestBB;
6879     if (parseTypeAndBasicBlock(DestBB, PFS))
6880       return true;
6881     IndirectDests.push_back(DestBB);
6882 
6883     while (EatIfPresent(lltok::comma)) {
6884       if (parseTypeAndBasicBlock(DestBB, PFS))
6885         return true;
6886       IndirectDests.push_back(DestBB);
6887     }
6888   }
6889 
6890   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6891     return true;
6892 
6893   // If RetType is a non-function pointer type, then this is the short syntax
6894   // for the call, which means that RetType is just the return type.  Infer the
6895   // rest of the function argument types from the arguments that are present.
6896   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6897   if (!Ty) {
6898     // Pull out the types of all of the arguments...
6899     std::vector<Type *> ParamTypes;
6900     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6901       ParamTypes.push_back(ArgList[i].V->getType());
6902 
6903     if (!FunctionType::isValidReturnType(RetType))
6904       return error(RetTypeLoc, "Invalid result type for LLVM function");
6905 
6906     Ty = FunctionType::get(RetType, ParamTypes, false);
6907   }
6908 
6909   CalleeID.FTy = Ty;
6910 
6911   // Look up the callee.
6912   Value *Callee;
6913   if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6914                           /*IsCall=*/true))
6915     return true;
6916 
6917   // Set up the Attribute for the function.
6918   SmallVector<Value *, 8> Args;
6919   SmallVector<AttributeSet, 8> ArgAttrs;
6920 
6921   // Loop through FunctionType's arguments and ensure they are specified
6922   // correctly.  Also, gather any parameter attributes.
6923   FunctionType::param_iterator I = Ty->param_begin();
6924   FunctionType::param_iterator E = Ty->param_end();
6925   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6926     Type *ExpectedTy = nullptr;
6927     if (I != E) {
6928       ExpectedTy = *I++;
6929     } else if (!Ty->isVarArg()) {
6930       return error(ArgList[i].Loc, "too many arguments specified");
6931     }
6932 
6933     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6934       return error(ArgList[i].Loc, "argument is not of expected type '" +
6935                                        getTypeString(ExpectedTy) + "'");
6936     Args.push_back(ArgList[i].V);
6937     ArgAttrs.push_back(ArgList[i].Attrs);
6938   }
6939 
6940   if (I != E)
6941     return error(CallLoc, "not enough parameters specified for call");
6942 
6943   if (FnAttrs.hasAlignmentAttr())
6944     return error(CallLoc, "callbr instructions may not have an alignment");
6945 
6946   // Finish off the Attribute and check them
6947   AttributeList PAL =
6948       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6949                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6950 
6951   CallBrInst *CBI =
6952       CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6953                          BundleList);
6954   CBI->setCallingConv(CC);
6955   CBI->setAttributes(PAL);
6956   ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6957   Inst = CBI;
6958   return false;
6959 }
6960 
6961 //===----------------------------------------------------------------------===//
6962 // Binary Operators.
6963 //===----------------------------------------------------------------------===//
6964 
6965 /// parseArithmetic
6966 ///  ::= ArithmeticOps TypeAndValue ',' Value
6967 ///
6968 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6969 /// operand is allowed.
6970 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6971                                unsigned Opc, bool IsFP) {
6972   LocTy Loc; Value *LHS, *RHS;
6973   if (parseTypeAndValue(LHS, Loc, PFS) ||
6974       parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6975       parseValue(LHS->getType(), RHS, PFS))
6976     return true;
6977 
6978   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6979                     : LHS->getType()->isIntOrIntVectorTy();
6980 
6981   if (!Valid)
6982     return error(Loc, "invalid operand type for instruction");
6983 
6984   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6985   return false;
6986 }
6987 
6988 /// parseLogical
6989 ///  ::= ArithmeticOps TypeAndValue ',' Value {
6990 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6991                             unsigned Opc) {
6992   LocTy Loc; Value *LHS, *RHS;
6993   if (parseTypeAndValue(LHS, Loc, PFS) ||
6994       parseToken(lltok::comma, "expected ',' in logical operation") ||
6995       parseValue(LHS->getType(), RHS, PFS))
6996     return true;
6997 
6998   if (!LHS->getType()->isIntOrIntVectorTy())
6999     return error(Loc,
7000                  "instruction requires integer or integer vector operands");
7001 
7002   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7003   return false;
7004 }
7005 
7006 /// parseCompare
7007 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
7008 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
7009 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7010                             unsigned Opc) {
7011   // parse the integer/fp comparison predicate.
7012   LocTy Loc;
7013   unsigned Pred;
7014   Value *LHS, *RHS;
7015   if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7016       parseToken(lltok::comma, "expected ',' after compare value") ||
7017       parseValue(LHS->getType(), RHS, PFS))
7018     return true;
7019 
7020   if (Opc == Instruction::FCmp) {
7021     if (!LHS->getType()->isFPOrFPVectorTy())
7022       return error(Loc, "fcmp requires floating point operands");
7023     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7024   } else {
7025     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7026     if (!LHS->getType()->isIntOrIntVectorTy() &&
7027         !LHS->getType()->isPtrOrPtrVectorTy())
7028       return error(Loc, "icmp requires integer operands");
7029     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7030   }
7031   return false;
7032 }
7033 
7034 //===----------------------------------------------------------------------===//
7035 // Other Instructions.
7036 //===----------------------------------------------------------------------===//
7037 
7038 /// parseCast
7039 ///   ::= CastOpc TypeAndValue 'to' Type
7040 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7041                          unsigned Opc) {
7042   LocTy Loc;
7043   Value *Op;
7044   Type *DestTy = nullptr;
7045   if (parseTypeAndValue(Op, Loc, PFS) ||
7046       parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7047       parseType(DestTy))
7048     return true;
7049 
7050   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
7051     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
7052     return error(Loc, "invalid cast opcode for cast from '" +
7053                           getTypeString(Op->getType()) + "' to '" +
7054                           getTypeString(DestTy) + "'");
7055   }
7056   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7057   return false;
7058 }
7059 
7060 /// parseSelect
7061 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7062 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7063   LocTy Loc;
7064   Value *Op0, *Op1, *Op2;
7065   if (parseTypeAndValue(Op0, Loc, PFS) ||
7066       parseToken(lltok::comma, "expected ',' after select condition") ||
7067       parseTypeAndValue(Op1, PFS) ||
7068       parseToken(lltok::comma, "expected ',' after select value") ||
7069       parseTypeAndValue(Op2, PFS))
7070     return true;
7071 
7072   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7073     return error(Loc, Reason);
7074 
7075   Inst = SelectInst::Create(Op0, Op1, Op2);
7076   return false;
7077 }
7078 
7079 /// parseVAArg
7080 ///   ::= 'va_arg' TypeAndValue ',' Type
7081 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7082   Value *Op;
7083   Type *EltTy = nullptr;
7084   LocTy TypeLoc;
7085   if (parseTypeAndValue(Op, PFS) ||
7086       parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7087       parseType(EltTy, TypeLoc))
7088     return true;
7089 
7090   if (!EltTy->isFirstClassType())
7091     return error(TypeLoc, "va_arg requires operand with first class type");
7092 
7093   Inst = new VAArgInst(Op, EltTy);
7094   return false;
7095 }
7096 
7097 /// parseExtractElement
7098 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
7099 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7100   LocTy Loc;
7101   Value *Op0, *Op1;
7102   if (parseTypeAndValue(Op0, Loc, PFS) ||
7103       parseToken(lltok::comma, "expected ',' after extract value") ||
7104       parseTypeAndValue(Op1, PFS))
7105     return true;
7106 
7107   if (!ExtractElementInst::isValidOperands(Op0, Op1))
7108     return error(Loc, "invalid extractelement operands");
7109 
7110   Inst = ExtractElementInst::Create(Op0, Op1);
7111   return false;
7112 }
7113 
7114 /// parseInsertElement
7115 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7116 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7117   LocTy Loc;
7118   Value *Op0, *Op1, *Op2;
7119   if (parseTypeAndValue(Op0, Loc, PFS) ||
7120       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7121       parseTypeAndValue(Op1, PFS) ||
7122       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7123       parseTypeAndValue(Op2, PFS))
7124     return true;
7125 
7126   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7127     return error(Loc, "invalid insertelement operands");
7128 
7129   Inst = InsertElementInst::Create(Op0, Op1, Op2);
7130   return false;
7131 }
7132 
7133 /// parseShuffleVector
7134 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7135 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7136   LocTy Loc;
7137   Value *Op0, *Op1, *Op2;
7138   if (parseTypeAndValue(Op0, Loc, PFS) ||
7139       parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7140       parseTypeAndValue(Op1, PFS) ||
7141       parseToken(lltok::comma, "expected ',' after shuffle value") ||
7142       parseTypeAndValue(Op2, PFS))
7143     return true;
7144 
7145   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7146     return error(Loc, "invalid shufflevector operands");
7147 
7148   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7149   return false;
7150 }
7151 
7152 /// parsePHI
7153 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7154 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7155   Type *Ty = nullptr;  LocTy TypeLoc;
7156   Value *Op0, *Op1;
7157 
7158   if (parseType(Ty, TypeLoc) ||
7159       parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7160       parseValue(Ty, Op0, PFS) ||
7161       parseToken(lltok::comma, "expected ',' after insertelement value") ||
7162       parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7163       parseToken(lltok::rsquare, "expected ']' in phi value list"))
7164     return true;
7165 
7166   bool AteExtraComma = false;
7167   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
7168 
7169   while (true) {
7170     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7171 
7172     if (!EatIfPresent(lltok::comma))
7173       break;
7174 
7175     if (Lex.getKind() == lltok::MetadataVar) {
7176       AteExtraComma = true;
7177       break;
7178     }
7179 
7180     if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7181         parseValue(Ty, Op0, PFS) ||
7182         parseToken(lltok::comma, "expected ',' after insertelement value") ||
7183         parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7184         parseToken(lltok::rsquare, "expected ']' in phi value list"))
7185       return true;
7186   }
7187 
7188   if (!Ty->isFirstClassType())
7189     return error(TypeLoc, "phi node must have first class type");
7190 
7191   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7192   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7193     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7194   Inst = PN;
7195   return AteExtraComma ? InstExtraComma : InstNormal;
7196 }
7197 
7198 /// parseLandingPad
7199 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7200 /// Clause
7201 ///   ::= 'catch' TypeAndValue
7202 ///   ::= 'filter'
7203 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7204 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7205   Type *Ty = nullptr; LocTy TyLoc;
7206 
7207   if (parseType(Ty, TyLoc))
7208     return true;
7209 
7210   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7211   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7212 
7213   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7214     LandingPadInst::ClauseType CT;
7215     if (EatIfPresent(lltok::kw_catch))
7216       CT = LandingPadInst::Catch;
7217     else if (EatIfPresent(lltok::kw_filter))
7218       CT = LandingPadInst::Filter;
7219     else
7220       return tokError("expected 'catch' or 'filter' clause type");
7221 
7222     Value *V;
7223     LocTy VLoc;
7224     if (parseTypeAndValue(V, VLoc, PFS))
7225       return true;
7226 
7227     // A 'catch' type expects a non-array constant. A filter clause expects an
7228     // array constant.
7229     if (CT == LandingPadInst::Catch) {
7230       if (isa<ArrayType>(V->getType()))
7231         error(VLoc, "'catch' clause has an invalid type");
7232     } else {
7233       if (!isa<ArrayType>(V->getType()))
7234         error(VLoc, "'filter' clause has an invalid type");
7235     }
7236 
7237     Constant *CV = dyn_cast<Constant>(V);
7238     if (!CV)
7239       return error(VLoc, "clause argument must be a constant");
7240     LP->addClause(CV);
7241   }
7242 
7243   Inst = LP.release();
7244   return false;
7245 }
7246 
7247 /// parseFreeze
7248 ///   ::= 'freeze' Type Value
7249 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7250   LocTy Loc;
7251   Value *Op;
7252   if (parseTypeAndValue(Op, Loc, PFS))
7253     return true;
7254 
7255   Inst = new FreezeInst(Op);
7256   return false;
7257 }
7258 
7259 /// parseCall
7260 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
7261 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7262 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7263 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7264 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7265 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7266 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
7267 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7268 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7269                          CallInst::TailCallKind TCK) {
7270   AttrBuilder RetAttrs, FnAttrs;
7271   std::vector<unsigned> FwdRefAttrGrps;
7272   LocTy BuiltinLoc;
7273   unsigned CallAddrSpace;
7274   unsigned CC;
7275   Type *RetType = nullptr;
7276   LocTy RetTypeLoc;
7277   ValID CalleeID;
7278   SmallVector<ParamInfo, 16> ArgList;
7279   SmallVector<OperandBundleDef, 2> BundleList;
7280   LocTy CallLoc = Lex.getLoc();
7281 
7282   if (TCK != CallInst::TCK_None &&
7283       parseToken(lltok::kw_call,
7284                  "expected 'tail call', 'musttail call', or 'notail call'"))
7285     return true;
7286 
7287   FastMathFlags FMF = EatFastMathFlagsIfPresent();
7288 
7289   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7290       parseOptionalProgramAddrSpace(CallAddrSpace) ||
7291       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7292       parseValID(CalleeID) ||
7293       parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7294                          PFS.getFunction().isVarArg()) ||
7295       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7296       parseOptionalOperandBundles(BundleList, PFS))
7297     return true;
7298 
7299   // If RetType is a non-function pointer type, then this is the short syntax
7300   // for the call, which means that RetType is just the return type.  Infer the
7301   // rest of the function argument types from the arguments that are present.
7302   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
7303   if (!Ty) {
7304     // Pull out the types of all of the arguments...
7305     std::vector<Type*> ParamTypes;
7306     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7307       ParamTypes.push_back(ArgList[i].V->getType());
7308 
7309     if (!FunctionType::isValidReturnType(RetType))
7310       return error(RetTypeLoc, "Invalid result type for LLVM function");
7311 
7312     Ty = FunctionType::get(RetType, ParamTypes, false);
7313   }
7314 
7315   CalleeID.FTy = Ty;
7316 
7317   // Look up the callee.
7318   Value *Callee;
7319   if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7320                           &PFS, /*IsCall=*/true))
7321     return true;
7322 
7323   // Set up the Attribute for the function.
7324   SmallVector<AttributeSet, 8> Attrs;
7325 
7326   SmallVector<Value*, 8> Args;
7327 
7328   // Loop through FunctionType's arguments and ensure they are specified
7329   // correctly.  Also, gather any parameter attributes.
7330   FunctionType::param_iterator I = Ty->param_begin();
7331   FunctionType::param_iterator E = Ty->param_end();
7332   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7333     Type *ExpectedTy = nullptr;
7334     if (I != E) {
7335       ExpectedTy = *I++;
7336     } else if (!Ty->isVarArg()) {
7337       return error(ArgList[i].Loc, "too many arguments specified");
7338     }
7339 
7340     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7341       return error(ArgList[i].Loc, "argument is not of expected type '" +
7342                                        getTypeString(ExpectedTy) + "'");
7343     Args.push_back(ArgList[i].V);
7344     Attrs.push_back(ArgList[i].Attrs);
7345   }
7346 
7347   if (I != E)
7348     return error(CallLoc, "not enough parameters specified for call");
7349 
7350   if (FnAttrs.hasAlignmentAttr())
7351     return error(CallLoc, "call instructions may not have an alignment");
7352 
7353   // Finish off the Attribute and check them
7354   AttributeList PAL =
7355       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7356                          AttributeSet::get(Context, RetAttrs), Attrs);
7357 
7358   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7359   CI->setTailCallKind(TCK);
7360   CI->setCallingConv(CC);
7361   if (FMF.any()) {
7362     if (!isa<FPMathOperator>(CI)) {
7363       CI->deleteValue();
7364       return error(CallLoc, "fast-math-flags specified for call without "
7365                             "floating-point scalar or vector return type");
7366     }
7367     CI->setFastMathFlags(FMF);
7368   }
7369   CI->setAttributes(PAL);
7370   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7371   Inst = CI;
7372   return false;
7373 }
7374 
7375 //===----------------------------------------------------------------------===//
7376 // Memory Instructions.
7377 //===----------------------------------------------------------------------===//
7378 
7379 /// parseAlloc
7380 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7381 ///       (',' 'align' i32)? (',', 'addrspace(n))?
7382 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7383   Value *Size = nullptr;
7384   LocTy SizeLoc, TyLoc, ASLoc;
7385   MaybeAlign Alignment;
7386   unsigned AddrSpace = 0;
7387   Type *Ty = nullptr;
7388 
7389   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7390   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7391 
7392   if (parseType(Ty, TyLoc))
7393     return true;
7394 
7395   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7396     return error(TyLoc, "invalid type for alloca");
7397 
7398   bool AteExtraComma = false;
7399   if (EatIfPresent(lltok::comma)) {
7400     if (Lex.getKind() == lltok::kw_align) {
7401       if (parseOptionalAlignment(Alignment))
7402         return true;
7403       if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7404         return true;
7405     } else if (Lex.getKind() == lltok::kw_addrspace) {
7406       ASLoc = Lex.getLoc();
7407       if (parseOptionalAddrSpace(AddrSpace))
7408         return true;
7409     } else if (Lex.getKind() == lltok::MetadataVar) {
7410       AteExtraComma = true;
7411     } else {
7412       if (parseTypeAndValue(Size, SizeLoc, PFS))
7413         return true;
7414       if (EatIfPresent(lltok::comma)) {
7415         if (Lex.getKind() == lltok::kw_align) {
7416           if (parseOptionalAlignment(Alignment))
7417             return true;
7418           if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7419             return true;
7420         } else if (Lex.getKind() == lltok::kw_addrspace) {
7421           ASLoc = Lex.getLoc();
7422           if (parseOptionalAddrSpace(AddrSpace))
7423             return true;
7424         } else if (Lex.getKind() == lltok::MetadataVar) {
7425           AteExtraComma = true;
7426         }
7427       }
7428     }
7429   }
7430 
7431   if (Size && !Size->getType()->isIntegerTy())
7432     return error(SizeLoc, "element count must have integer type");
7433 
7434   SmallPtrSet<Type *, 4> Visited;
7435   if (!Alignment && !Ty->isSized(&Visited))
7436     return error(TyLoc, "Cannot allocate unsized type");
7437   if (!Alignment)
7438     Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7439   AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7440   AI->setUsedWithInAlloca(IsInAlloca);
7441   AI->setSwiftError(IsSwiftError);
7442   Inst = AI;
7443   return AteExtraComma ? InstExtraComma : InstNormal;
7444 }
7445 
7446 /// parseLoad
7447 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7448 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
7449 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7450 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7451   Value *Val; LocTy Loc;
7452   MaybeAlign Alignment;
7453   bool AteExtraComma = false;
7454   bool isAtomic = false;
7455   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7456   SyncScope::ID SSID = SyncScope::System;
7457 
7458   if (Lex.getKind() == lltok::kw_atomic) {
7459     isAtomic = true;
7460     Lex.Lex();
7461   }
7462 
7463   bool isVolatile = false;
7464   if (Lex.getKind() == lltok::kw_volatile) {
7465     isVolatile = true;
7466     Lex.Lex();
7467   }
7468 
7469   Type *Ty;
7470   LocTy ExplicitTypeLoc = Lex.getLoc();
7471   if (parseType(Ty) ||
7472       parseToken(lltok::comma, "expected comma after load's type") ||
7473       parseTypeAndValue(Val, Loc, PFS) ||
7474       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7475       parseOptionalCommaAlign(Alignment, AteExtraComma))
7476     return true;
7477 
7478   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7479     return error(Loc, "load operand must be a pointer to a first class type");
7480   if (isAtomic && !Alignment)
7481     return error(Loc, "atomic load must have explicit non-zero alignment");
7482   if (Ordering == AtomicOrdering::Release ||
7483       Ordering == AtomicOrdering::AcquireRelease)
7484     return error(Loc, "atomic load cannot use Release ordering");
7485 
7486   if (Ty != cast<PointerType>(Val->getType())->getElementType()) {
7487     return error(
7488         ExplicitTypeLoc,
7489         typeComparisonErrorMessage(
7490             "explicit pointee type doesn't match operand's pointee type", Ty,
7491             cast<PointerType>(Val->getType())->getElementType()));
7492   }
7493   SmallPtrSet<Type *, 4> Visited;
7494   if (!Alignment && !Ty->isSized(&Visited))
7495     return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7496   if (!Alignment)
7497     Alignment = M->getDataLayout().getABITypeAlign(Ty);
7498   Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7499   return AteExtraComma ? InstExtraComma : InstNormal;
7500 }
7501 
7502 /// parseStore
7503 
7504 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7505 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7506 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7507 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7508   Value *Val, *Ptr; LocTy Loc, PtrLoc;
7509   MaybeAlign Alignment;
7510   bool AteExtraComma = false;
7511   bool isAtomic = false;
7512   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7513   SyncScope::ID SSID = SyncScope::System;
7514 
7515   if (Lex.getKind() == lltok::kw_atomic) {
7516     isAtomic = true;
7517     Lex.Lex();
7518   }
7519 
7520   bool isVolatile = false;
7521   if (Lex.getKind() == lltok::kw_volatile) {
7522     isVolatile = true;
7523     Lex.Lex();
7524   }
7525 
7526   if (parseTypeAndValue(Val, Loc, PFS) ||
7527       parseToken(lltok::comma, "expected ',' after store operand") ||
7528       parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7529       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7530       parseOptionalCommaAlign(Alignment, AteExtraComma))
7531     return true;
7532 
7533   if (!Ptr->getType()->isPointerTy())
7534     return error(PtrLoc, "store operand must be a pointer");
7535   if (!Val->getType()->isFirstClassType())
7536     return error(Loc, "store operand must be a first class value");
7537   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7538     return error(Loc, "stored value and pointer type do not match");
7539   if (isAtomic && !Alignment)
7540     return error(Loc, "atomic store must have explicit non-zero alignment");
7541   if (Ordering == AtomicOrdering::Acquire ||
7542       Ordering == AtomicOrdering::AcquireRelease)
7543     return error(Loc, "atomic store cannot use Acquire ordering");
7544   SmallPtrSet<Type *, 4> Visited;
7545   if (!Alignment && !Val->getType()->isSized(&Visited))
7546     return error(Loc, "storing unsized types is not allowed");
7547   if (!Alignment)
7548     Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7549 
7550   Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7551   return AteExtraComma ? InstExtraComma : InstNormal;
7552 }
7553 
7554 /// parseCmpXchg
7555 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7556 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7557 ///       'Align'?
7558 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7559   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7560   bool AteExtraComma = false;
7561   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7562   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7563   SyncScope::ID SSID = SyncScope::System;
7564   bool isVolatile = false;
7565   bool isWeak = false;
7566   MaybeAlign Alignment;
7567 
7568   if (EatIfPresent(lltok::kw_weak))
7569     isWeak = true;
7570 
7571   if (EatIfPresent(lltok::kw_volatile))
7572     isVolatile = true;
7573 
7574   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7575       parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7576       parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7577       parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7578       parseTypeAndValue(New, NewLoc, PFS) ||
7579       parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7580       parseOrdering(FailureOrdering) ||
7581       parseOptionalCommaAlign(Alignment, AteExtraComma))
7582     return true;
7583 
7584   if (SuccessOrdering == AtomicOrdering::Unordered ||
7585       FailureOrdering == AtomicOrdering::Unordered)
7586     return tokError("cmpxchg cannot be unordered");
7587   if (FailureOrdering == AtomicOrdering::Release ||
7588       FailureOrdering == AtomicOrdering::AcquireRelease)
7589     return tokError(
7590         "cmpxchg failure ordering cannot include release semantics");
7591   if (!Ptr->getType()->isPointerTy())
7592     return error(PtrLoc, "cmpxchg operand must be a pointer");
7593   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
7594     return error(CmpLoc, "compare value and pointer type do not match");
7595   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
7596     return error(NewLoc, "new value and pointer type do not match");
7597   if (!New->getType()->isFirstClassType())
7598     return error(NewLoc, "cmpxchg operand must be a first class value");
7599 
7600   const Align DefaultAlignment(
7601       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7602           Cmp->getType()));
7603 
7604   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
7605       Ptr, Cmp, New, Alignment.getValueOr(DefaultAlignment), SuccessOrdering,
7606       FailureOrdering, SSID);
7607   CXI->setVolatile(isVolatile);
7608   CXI->setWeak(isWeak);
7609 
7610   Inst = CXI;
7611   return AteExtraComma ? InstExtraComma : InstNormal;
7612 }
7613 
7614 /// parseAtomicRMW
7615 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7616 ///       'singlethread'? AtomicOrdering
7617 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7618   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7619   bool AteExtraComma = false;
7620   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7621   SyncScope::ID SSID = SyncScope::System;
7622   bool isVolatile = false;
7623   bool IsFP = false;
7624   AtomicRMWInst::BinOp Operation;
7625   MaybeAlign Alignment;
7626 
7627   if (EatIfPresent(lltok::kw_volatile))
7628     isVolatile = true;
7629 
7630   switch (Lex.getKind()) {
7631   default:
7632     return tokError("expected binary operation in atomicrmw");
7633   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7634   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7635   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7636   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7637   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7638   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7639   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7640   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7641   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7642   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7643   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7644   case lltok::kw_fadd:
7645     Operation = AtomicRMWInst::FAdd;
7646     IsFP = true;
7647     break;
7648   case lltok::kw_fsub:
7649     Operation = AtomicRMWInst::FSub;
7650     IsFP = true;
7651     break;
7652   }
7653   Lex.Lex();  // Eat the operation.
7654 
7655   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7656       parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7657       parseTypeAndValue(Val, ValLoc, PFS) ||
7658       parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7659       parseOptionalCommaAlign(Alignment, AteExtraComma))
7660     return true;
7661 
7662   if (Ordering == AtomicOrdering::Unordered)
7663     return tokError("atomicrmw cannot be unordered");
7664   if (!Ptr->getType()->isPointerTy())
7665     return error(PtrLoc, "atomicrmw operand must be a pointer");
7666   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7667     return error(ValLoc, "atomicrmw value and pointer type do not match");
7668 
7669   if (Operation == AtomicRMWInst::Xchg) {
7670     if (!Val->getType()->isIntegerTy() &&
7671         !Val->getType()->isFloatingPointTy()) {
7672       return error(ValLoc,
7673                    "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7674                        " operand must be an integer or floating point type");
7675     }
7676   } else if (IsFP) {
7677     if (!Val->getType()->isFloatingPointTy()) {
7678       return error(ValLoc, "atomicrmw " +
7679                                AtomicRMWInst::getOperationName(Operation) +
7680                                " operand must be a floating point type");
7681     }
7682   } else {
7683     if (!Val->getType()->isIntegerTy()) {
7684       return error(ValLoc, "atomicrmw " +
7685                                AtomicRMWInst::getOperationName(Operation) +
7686                                " operand must be an integer");
7687     }
7688   }
7689 
7690   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7691   if (Size < 8 || (Size & (Size - 1)))
7692     return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7693                          " integer");
7694   const Align DefaultAlignment(
7695       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7696           Val->getType()));
7697   AtomicRMWInst *RMWI =
7698       new AtomicRMWInst(Operation, Ptr, Val,
7699                         Alignment.getValueOr(DefaultAlignment), Ordering, SSID);
7700   RMWI->setVolatile(isVolatile);
7701   Inst = RMWI;
7702   return AteExtraComma ? InstExtraComma : InstNormal;
7703 }
7704 
7705 /// parseFence
7706 ///   ::= 'fence' 'singlethread'? AtomicOrdering
7707 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7708   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7709   SyncScope::ID SSID = SyncScope::System;
7710   if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7711     return true;
7712 
7713   if (Ordering == AtomicOrdering::Unordered)
7714     return tokError("fence cannot be unordered");
7715   if (Ordering == AtomicOrdering::Monotonic)
7716     return tokError("fence cannot be monotonic");
7717 
7718   Inst = new FenceInst(Context, Ordering, SSID);
7719   return InstNormal;
7720 }
7721 
7722 /// parseGetElementPtr
7723 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7724 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7725   Value *Ptr = nullptr;
7726   Value *Val = nullptr;
7727   LocTy Loc, EltLoc;
7728 
7729   bool InBounds = EatIfPresent(lltok::kw_inbounds);
7730 
7731   Type *Ty = nullptr;
7732   LocTy ExplicitTypeLoc = Lex.getLoc();
7733   if (parseType(Ty) ||
7734       parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7735       parseTypeAndValue(Ptr, Loc, PFS))
7736     return true;
7737 
7738   Type *BaseType = Ptr->getType();
7739   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7740   if (!BasePointerType)
7741     return error(Loc, "base of getelementptr must be a pointer");
7742 
7743   if (Ty != BasePointerType->getElementType()) {
7744     return error(
7745         ExplicitTypeLoc,
7746         typeComparisonErrorMessage(
7747             "explicit pointee type doesn't match operand's pointee type", Ty,
7748             BasePointerType->getElementType()));
7749   }
7750 
7751   SmallVector<Value*, 16> Indices;
7752   bool AteExtraComma = false;
7753   // GEP returns a vector of pointers if at least one of parameters is a vector.
7754   // All vector parameters should have the same vector width.
7755   ElementCount GEPWidth = BaseType->isVectorTy()
7756                               ? cast<VectorType>(BaseType)->getElementCount()
7757                               : ElementCount::getFixed(0);
7758 
7759   while (EatIfPresent(lltok::comma)) {
7760     if (Lex.getKind() == lltok::MetadataVar) {
7761       AteExtraComma = true;
7762       break;
7763     }
7764     if (parseTypeAndValue(Val, EltLoc, PFS))
7765       return true;
7766     if (!Val->getType()->isIntOrIntVectorTy())
7767       return error(EltLoc, "getelementptr index must be an integer");
7768 
7769     if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7770       ElementCount ValNumEl = ValVTy->getElementCount();
7771       if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7772         return error(
7773             EltLoc,
7774             "getelementptr vector index has a wrong number of elements");
7775       GEPWidth = ValNumEl;
7776     }
7777     Indices.push_back(Val);
7778   }
7779 
7780   SmallPtrSet<Type*, 4> Visited;
7781   if (!Indices.empty() && !Ty->isSized(&Visited))
7782     return error(Loc, "base element of getelementptr must be sized");
7783 
7784   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7785     return error(Loc, "invalid getelementptr indices");
7786   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7787   if (InBounds)
7788     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7789   return AteExtraComma ? InstExtraComma : InstNormal;
7790 }
7791 
7792 /// parseExtractValue
7793 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
7794 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7795   Value *Val; LocTy Loc;
7796   SmallVector<unsigned, 4> Indices;
7797   bool AteExtraComma;
7798   if (parseTypeAndValue(Val, Loc, PFS) ||
7799       parseIndexList(Indices, AteExtraComma))
7800     return true;
7801 
7802   if (!Val->getType()->isAggregateType())
7803     return error(Loc, "extractvalue operand must be aggregate type");
7804 
7805   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7806     return error(Loc, "invalid indices for extractvalue");
7807   Inst = ExtractValueInst::Create(Val, Indices);
7808   return AteExtraComma ? InstExtraComma : InstNormal;
7809 }
7810 
7811 /// parseInsertValue
7812 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7813 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7814   Value *Val0, *Val1; LocTy Loc0, Loc1;
7815   SmallVector<unsigned, 4> Indices;
7816   bool AteExtraComma;
7817   if (parseTypeAndValue(Val0, Loc0, PFS) ||
7818       parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7819       parseTypeAndValue(Val1, Loc1, PFS) ||
7820       parseIndexList(Indices, AteExtraComma))
7821     return true;
7822 
7823   if (!Val0->getType()->isAggregateType())
7824     return error(Loc0, "insertvalue operand must be aggregate type");
7825 
7826   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7827   if (!IndexedType)
7828     return error(Loc0, "invalid indices for insertvalue");
7829   if (IndexedType != Val1->getType())
7830     return error(Loc1, "insertvalue operand and field disagree in type: '" +
7831                            getTypeString(Val1->getType()) + "' instead of '" +
7832                            getTypeString(IndexedType) + "'");
7833   Inst = InsertValueInst::Create(Val0, Val1, Indices);
7834   return AteExtraComma ? InstExtraComma : InstNormal;
7835 }
7836 
7837 //===----------------------------------------------------------------------===//
7838 // Embedded metadata.
7839 //===----------------------------------------------------------------------===//
7840 
7841 /// parseMDNodeVector
7842 ///   ::= { Element (',' Element)* }
7843 /// Element
7844 ///   ::= 'null' | TypeAndValue
7845 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7846   if (parseToken(lltok::lbrace, "expected '{' here"))
7847     return true;
7848 
7849   // Check for an empty list.
7850   if (EatIfPresent(lltok::rbrace))
7851     return false;
7852 
7853   do {
7854     // Null is a special case since it is typeless.
7855     if (EatIfPresent(lltok::kw_null)) {
7856       Elts.push_back(nullptr);
7857       continue;
7858     }
7859 
7860     Metadata *MD;
7861     if (parseMetadata(MD, nullptr))
7862       return true;
7863     Elts.push_back(MD);
7864   } while (EatIfPresent(lltok::comma));
7865 
7866   return parseToken(lltok::rbrace, "expected end of metadata node");
7867 }
7868 
7869 //===----------------------------------------------------------------------===//
7870 // Use-list order directives.
7871 //===----------------------------------------------------------------------===//
7872 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7873                                 SMLoc Loc) {
7874   if (V->use_empty())
7875     return error(Loc, "value has no uses");
7876 
7877   unsigned NumUses = 0;
7878   SmallDenseMap<const Use *, unsigned, 16> Order;
7879   for (const Use &U : V->uses()) {
7880     if (++NumUses > Indexes.size())
7881       break;
7882     Order[&U] = Indexes[NumUses - 1];
7883   }
7884   if (NumUses < 2)
7885     return error(Loc, "value only has one use");
7886   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7887     return error(Loc,
7888                  "wrong number of indexes, expected " + Twine(V->getNumUses()));
7889 
7890   V->sortUseList([&](const Use &L, const Use &R) {
7891     return Order.lookup(&L) < Order.lookup(&R);
7892   });
7893   return false;
7894 }
7895 
7896 /// parseUseListOrderIndexes
7897 ///   ::= '{' uint32 (',' uint32)+ '}'
7898 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7899   SMLoc Loc = Lex.getLoc();
7900   if (parseToken(lltok::lbrace, "expected '{' here"))
7901     return true;
7902   if (Lex.getKind() == lltok::rbrace)
7903     return Lex.Error("expected non-empty list of uselistorder indexes");
7904 
7905   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
7906   // indexes should be distinct numbers in the range [0, size-1], and should
7907   // not be in order.
7908   unsigned Offset = 0;
7909   unsigned Max = 0;
7910   bool IsOrdered = true;
7911   assert(Indexes.empty() && "Expected empty order vector");
7912   do {
7913     unsigned Index;
7914     if (parseUInt32(Index))
7915       return true;
7916 
7917     // Update consistency checks.
7918     Offset += Index - Indexes.size();
7919     Max = std::max(Max, Index);
7920     IsOrdered &= Index == Indexes.size();
7921 
7922     Indexes.push_back(Index);
7923   } while (EatIfPresent(lltok::comma));
7924 
7925   if (parseToken(lltok::rbrace, "expected '}' here"))
7926     return true;
7927 
7928   if (Indexes.size() < 2)
7929     return error(Loc, "expected >= 2 uselistorder indexes");
7930   if (Offset != 0 || Max >= Indexes.size())
7931     return error(Loc,
7932                  "expected distinct uselistorder indexes in range [0, size)");
7933   if (IsOrdered)
7934     return error(Loc, "expected uselistorder indexes to change the order");
7935 
7936   return false;
7937 }
7938 
7939 /// parseUseListOrder
7940 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7941 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7942   SMLoc Loc = Lex.getLoc();
7943   if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7944     return true;
7945 
7946   Value *V;
7947   SmallVector<unsigned, 16> Indexes;
7948   if (parseTypeAndValue(V, PFS) ||
7949       parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7950       parseUseListOrderIndexes(Indexes))
7951     return true;
7952 
7953   return sortUseListOrder(V, Indexes, Loc);
7954 }
7955 
7956 /// parseUseListOrderBB
7957 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7958 bool LLParser::parseUseListOrderBB() {
7959   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7960   SMLoc Loc = Lex.getLoc();
7961   Lex.Lex();
7962 
7963   ValID Fn, Label;
7964   SmallVector<unsigned, 16> Indexes;
7965   if (parseValID(Fn) ||
7966       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7967       parseValID(Label) ||
7968       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7969       parseUseListOrderIndexes(Indexes))
7970     return true;
7971 
7972   // Check the function.
7973   GlobalValue *GV;
7974   if (Fn.Kind == ValID::t_GlobalName)
7975     GV = M->getNamedValue(Fn.StrVal);
7976   else if (Fn.Kind == ValID::t_GlobalID)
7977     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7978   else
7979     return error(Fn.Loc, "expected function name in uselistorder_bb");
7980   if (!GV)
7981     return error(Fn.Loc,
7982                  "invalid function forward reference in uselistorder_bb");
7983   auto *F = dyn_cast<Function>(GV);
7984   if (!F)
7985     return error(Fn.Loc, "expected function name in uselistorder_bb");
7986   if (F->isDeclaration())
7987     return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7988 
7989   // Check the basic block.
7990   if (Label.Kind == ValID::t_LocalID)
7991     return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7992   if (Label.Kind != ValID::t_LocalName)
7993     return error(Label.Loc, "expected basic block name in uselistorder_bb");
7994   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7995   if (!V)
7996     return error(Label.Loc, "invalid basic block in uselistorder_bb");
7997   if (!isa<BasicBlock>(V))
7998     return error(Label.Loc, "expected basic block in uselistorder_bb");
7999 
8000   return sortUseListOrder(V, Indexes, Loc);
8001 }
8002 
8003 /// ModuleEntry
8004 ///   ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8005 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8006 bool LLParser::parseModuleEntry(unsigned ID) {
8007   assert(Lex.getKind() == lltok::kw_module);
8008   Lex.Lex();
8009 
8010   std::string Path;
8011   if (parseToken(lltok::colon, "expected ':' here") ||
8012       parseToken(lltok::lparen, "expected '(' here") ||
8013       parseToken(lltok::kw_path, "expected 'path' here") ||
8014       parseToken(lltok::colon, "expected ':' here") ||
8015       parseStringConstant(Path) ||
8016       parseToken(lltok::comma, "expected ',' here") ||
8017       parseToken(lltok::kw_hash, "expected 'hash' here") ||
8018       parseToken(lltok::colon, "expected ':' here") ||
8019       parseToken(lltok::lparen, "expected '(' here"))
8020     return true;
8021 
8022   ModuleHash Hash;
8023   if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8024       parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8025       parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8026       parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8027       parseUInt32(Hash[4]))
8028     return true;
8029 
8030   if (parseToken(lltok::rparen, "expected ')' here") ||
8031       parseToken(lltok::rparen, "expected ')' here"))
8032     return true;
8033 
8034   auto ModuleEntry = Index->addModule(Path, ID, Hash);
8035   ModuleIdMap[ID] = ModuleEntry->first();
8036 
8037   return false;
8038 }
8039 
8040 /// TypeIdEntry
8041 ///   ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8042 bool LLParser::parseTypeIdEntry(unsigned ID) {
8043   assert(Lex.getKind() == lltok::kw_typeid);
8044   Lex.Lex();
8045 
8046   std::string Name;
8047   if (parseToken(lltok::colon, "expected ':' here") ||
8048       parseToken(lltok::lparen, "expected '(' here") ||
8049       parseToken(lltok::kw_name, "expected 'name' here") ||
8050       parseToken(lltok::colon, "expected ':' here") ||
8051       parseStringConstant(Name))
8052     return true;
8053 
8054   TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8055   if (parseToken(lltok::comma, "expected ',' here") ||
8056       parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8057     return true;
8058 
8059   // Check if this ID was forward referenced, and if so, update the
8060   // corresponding GUIDs.
8061   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8062   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8063     for (auto TIDRef : FwdRefTIDs->second) {
8064       assert(!*TIDRef.first &&
8065              "Forward referenced type id GUID expected to be 0");
8066       *TIDRef.first = GlobalValue::getGUID(Name);
8067     }
8068     ForwardRefTypeIds.erase(FwdRefTIDs);
8069   }
8070 
8071   return false;
8072 }
8073 
8074 /// TypeIdSummary
8075 ///   ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8076 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8077   if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8078       parseToken(lltok::colon, "expected ':' here") ||
8079       parseToken(lltok::lparen, "expected '(' here") ||
8080       parseTypeTestResolution(TIS.TTRes))
8081     return true;
8082 
8083   if (EatIfPresent(lltok::comma)) {
8084     // Expect optional wpdResolutions field
8085     if (parseOptionalWpdResolutions(TIS.WPDRes))
8086       return true;
8087   }
8088 
8089   if (parseToken(lltok::rparen, "expected ')' here"))
8090     return true;
8091 
8092   return false;
8093 }
8094 
8095 static ValueInfo EmptyVI =
8096     ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8097 
8098 /// TypeIdCompatibleVtableEntry
8099 ///   ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8100 ///   TypeIdCompatibleVtableInfo
8101 ///   ')'
8102 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8103   assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
8104   Lex.Lex();
8105 
8106   std::string Name;
8107   if (parseToken(lltok::colon, "expected ':' here") ||
8108       parseToken(lltok::lparen, "expected '(' here") ||
8109       parseToken(lltok::kw_name, "expected 'name' here") ||
8110       parseToken(lltok::colon, "expected ':' here") ||
8111       parseStringConstant(Name))
8112     return true;
8113 
8114   TypeIdCompatibleVtableInfo &TI =
8115       Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8116   if (parseToken(lltok::comma, "expected ',' here") ||
8117       parseToken(lltok::kw_summary, "expected 'summary' here") ||
8118       parseToken(lltok::colon, "expected ':' here") ||
8119       parseToken(lltok::lparen, "expected '(' here"))
8120     return true;
8121 
8122   IdToIndexMapType IdToIndexMap;
8123   // parse each call edge
8124   do {
8125     uint64_t Offset;
8126     if (parseToken(lltok::lparen, "expected '(' here") ||
8127         parseToken(lltok::kw_offset, "expected 'offset' here") ||
8128         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8129         parseToken(lltok::comma, "expected ',' here"))
8130       return true;
8131 
8132     LocTy Loc = Lex.getLoc();
8133     unsigned GVId;
8134     ValueInfo VI;
8135     if (parseGVReference(VI, GVId))
8136       return true;
8137 
8138     // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8139     // forward reference. We will save the location of the ValueInfo needing an
8140     // update, but can only do so once the std::vector is finalized.
8141     if (VI == EmptyVI)
8142       IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8143     TI.push_back({Offset, VI});
8144 
8145     if (parseToken(lltok::rparen, "expected ')' in call"))
8146       return true;
8147   } while (EatIfPresent(lltok::comma));
8148 
8149   // Now that the TI vector is finalized, it is safe to save the locations
8150   // of any forward GV references that need updating later.
8151   for (auto I : IdToIndexMap) {
8152     auto &Infos = ForwardRefValueInfos[I.first];
8153     for (auto P : I.second) {
8154       assert(TI[P.first].VTableVI == EmptyVI &&
8155              "Forward referenced ValueInfo expected to be empty");
8156       Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8157     }
8158   }
8159 
8160   if (parseToken(lltok::rparen, "expected ')' here") ||
8161       parseToken(lltok::rparen, "expected ')' here"))
8162     return true;
8163 
8164   // Check if this ID was forward referenced, and if so, update the
8165   // corresponding GUIDs.
8166   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8167   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8168     for (auto TIDRef : FwdRefTIDs->second) {
8169       assert(!*TIDRef.first &&
8170              "Forward referenced type id GUID expected to be 0");
8171       *TIDRef.first = GlobalValue::getGUID(Name);
8172     }
8173     ForwardRefTypeIds.erase(FwdRefTIDs);
8174   }
8175 
8176   return false;
8177 }
8178 
8179 /// TypeTestResolution
8180 ///   ::= 'typeTestRes' ':' '(' 'kind' ':'
8181 ///         ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8182 ///         'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8183 ///         [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8184 ///         [',' 'inlinesBits' ':' UInt64]? ')'
8185 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8186   if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8187       parseToken(lltok::colon, "expected ':' here") ||
8188       parseToken(lltok::lparen, "expected '(' here") ||
8189       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8190       parseToken(lltok::colon, "expected ':' here"))
8191     return true;
8192 
8193   switch (Lex.getKind()) {
8194   case lltok::kw_unknown:
8195     TTRes.TheKind = TypeTestResolution::Unknown;
8196     break;
8197   case lltok::kw_unsat:
8198     TTRes.TheKind = TypeTestResolution::Unsat;
8199     break;
8200   case lltok::kw_byteArray:
8201     TTRes.TheKind = TypeTestResolution::ByteArray;
8202     break;
8203   case lltok::kw_inline:
8204     TTRes.TheKind = TypeTestResolution::Inline;
8205     break;
8206   case lltok::kw_single:
8207     TTRes.TheKind = TypeTestResolution::Single;
8208     break;
8209   case lltok::kw_allOnes:
8210     TTRes.TheKind = TypeTestResolution::AllOnes;
8211     break;
8212   default:
8213     return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8214   }
8215   Lex.Lex();
8216 
8217   if (parseToken(lltok::comma, "expected ',' here") ||
8218       parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8219       parseToken(lltok::colon, "expected ':' here") ||
8220       parseUInt32(TTRes.SizeM1BitWidth))
8221     return true;
8222 
8223   // parse optional fields
8224   while (EatIfPresent(lltok::comma)) {
8225     switch (Lex.getKind()) {
8226     case lltok::kw_alignLog2:
8227       Lex.Lex();
8228       if (parseToken(lltok::colon, "expected ':'") ||
8229           parseUInt64(TTRes.AlignLog2))
8230         return true;
8231       break;
8232     case lltok::kw_sizeM1:
8233       Lex.Lex();
8234       if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8235         return true;
8236       break;
8237     case lltok::kw_bitMask: {
8238       unsigned Val;
8239       Lex.Lex();
8240       if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8241         return true;
8242       assert(Val <= 0xff);
8243       TTRes.BitMask = (uint8_t)Val;
8244       break;
8245     }
8246     case lltok::kw_inlineBits:
8247       Lex.Lex();
8248       if (parseToken(lltok::colon, "expected ':'") ||
8249           parseUInt64(TTRes.InlineBits))
8250         return true;
8251       break;
8252     default:
8253       return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8254     }
8255   }
8256 
8257   if (parseToken(lltok::rparen, "expected ')' here"))
8258     return true;
8259 
8260   return false;
8261 }
8262 
8263 /// OptionalWpdResolutions
8264 ///   ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8265 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8266 bool LLParser::parseOptionalWpdResolutions(
8267     std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8268   if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8269       parseToken(lltok::colon, "expected ':' here") ||
8270       parseToken(lltok::lparen, "expected '(' here"))
8271     return true;
8272 
8273   do {
8274     uint64_t Offset;
8275     WholeProgramDevirtResolution WPDRes;
8276     if (parseToken(lltok::lparen, "expected '(' here") ||
8277         parseToken(lltok::kw_offset, "expected 'offset' here") ||
8278         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8279         parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8280         parseToken(lltok::rparen, "expected ')' here"))
8281       return true;
8282     WPDResMap[Offset] = WPDRes;
8283   } while (EatIfPresent(lltok::comma));
8284 
8285   if (parseToken(lltok::rparen, "expected ')' here"))
8286     return true;
8287 
8288   return false;
8289 }
8290 
8291 /// WpdRes
8292 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8293 ///         [',' OptionalResByArg]? ')'
8294 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8295 ///         ',' 'singleImplName' ':' STRINGCONSTANT ','
8296 ///         [',' OptionalResByArg]? ')'
8297 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8298 ///         [',' OptionalResByArg]? ')'
8299 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8300   if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8301       parseToken(lltok::colon, "expected ':' here") ||
8302       parseToken(lltok::lparen, "expected '(' here") ||
8303       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8304       parseToken(lltok::colon, "expected ':' here"))
8305     return true;
8306 
8307   switch (Lex.getKind()) {
8308   case lltok::kw_indir:
8309     WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8310     break;
8311   case lltok::kw_singleImpl:
8312     WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8313     break;
8314   case lltok::kw_branchFunnel:
8315     WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8316     break;
8317   default:
8318     return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8319   }
8320   Lex.Lex();
8321 
8322   // parse optional fields
8323   while (EatIfPresent(lltok::comma)) {
8324     switch (Lex.getKind()) {
8325     case lltok::kw_singleImplName:
8326       Lex.Lex();
8327       if (parseToken(lltok::colon, "expected ':' here") ||
8328           parseStringConstant(WPDRes.SingleImplName))
8329         return true;
8330       break;
8331     case lltok::kw_resByArg:
8332       if (parseOptionalResByArg(WPDRes.ResByArg))
8333         return true;
8334       break;
8335     default:
8336       return error(Lex.getLoc(),
8337                    "expected optional WholeProgramDevirtResolution field");
8338     }
8339   }
8340 
8341   if (parseToken(lltok::rparen, "expected ')' here"))
8342     return true;
8343 
8344   return false;
8345 }
8346 
8347 /// OptionalResByArg
8348 ///   ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8349 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8350 ///                ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8351 ///                  'virtualConstProp' )
8352 ///                [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8353 ///                [',' 'bit' ':' UInt32]? ')'
8354 bool LLParser::parseOptionalResByArg(
8355     std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8356         &ResByArg) {
8357   if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8358       parseToken(lltok::colon, "expected ':' here") ||
8359       parseToken(lltok::lparen, "expected '(' here"))
8360     return true;
8361 
8362   do {
8363     std::vector<uint64_t> Args;
8364     if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8365         parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8366         parseToken(lltok::colon, "expected ':' here") ||
8367         parseToken(lltok::lparen, "expected '(' here") ||
8368         parseToken(lltok::kw_kind, "expected 'kind' here") ||
8369         parseToken(lltok::colon, "expected ':' here"))
8370       return true;
8371 
8372     WholeProgramDevirtResolution::ByArg ByArg;
8373     switch (Lex.getKind()) {
8374     case lltok::kw_indir:
8375       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8376       break;
8377     case lltok::kw_uniformRetVal:
8378       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8379       break;
8380     case lltok::kw_uniqueRetVal:
8381       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8382       break;
8383     case lltok::kw_virtualConstProp:
8384       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8385       break;
8386     default:
8387       return error(Lex.getLoc(),
8388                    "unexpected WholeProgramDevirtResolution::ByArg kind");
8389     }
8390     Lex.Lex();
8391 
8392     // parse optional fields
8393     while (EatIfPresent(lltok::comma)) {
8394       switch (Lex.getKind()) {
8395       case lltok::kw_info:
8396         Lex.Lex();
8397         if (parseToken(lltok::colon, "expected ':' here") ||
8398             parseUInt64(ByArg.Info))
8399           return true;
8400         break;
8401       case lltok::kw_byte:
8402         Lex.Lex();
8403         if (parseToken(lltok::colon, "expected ':' here") ||
8404             parseUInt32(ByArg.Byte))
8405           return true;
8406         break;
8407       case lltok::kw_bit:
8408         Lex.Lex();
8409         if (parseToken(lltok::colon, "expected ':' here") ||
8410             parseUInt32(ByArg.Bit))
8411           return true;
8412         break;
8413       default:
8414         return error(Lex.getLoc(),
8415                      "expected optional whole program devirt field");
8416       }
8417     }
8418 
8419     if (parseToken(lltok::rparen, "expected ')' here"))
8420       return true;
8421 
8422     ResByArg[Args] = ByArg;
8423   } while (EatIfPresent(lltok::comma));
8424 
8425   if (parseToken(lltok::rparen, "expected ')' here"))
8426     return true;
8427 
8428   return false;
8429 }
8430 
8431 /// OptionalResByArg
8432 ///   ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8433 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8434   if (parseToken(lltok::kw_args, "expected 'args' here") ||
8435       parseToken(lltok::colon, "expected ':' here") ||
8436       parseToken(lltok::lparen, "expected '(' here"))
8437     return true;
8438 
8439   do {
8440     uint64_t Val;
8441     if (parseUInt64(Val))
8442       return true;
8443     Args.push_back(Val);
8444   } while (EatIfPresent(lltok::comma));
8445 
8446   if (parseToken(lltok::rparen, "expected ')' here"))
8447     return true;
8448 
8449   return false;
8450 }
8451 
8452 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8453 
8454 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8455   bool ReadOnly = Fwd->isReadOnly();
8456   bool WriteOnly = Fwd->isWriteOnly();
8457   assert(!(ReadOnly && WriteOnly));
8458   *Fwd = Resolved;
8459   if (ReadOnly)
8460     Fwd->setReadOnly();
8461   if (WriteOnly)
8462     Fwd->setWriteOnly();
8463 }
8464 
8465 /// Stores the given Name/GUID and associated summary into the Index.
8466 /// Also updates any forward references to the associated entry ID.
8467 void LLParser::addGlobalValueToIndex(
8468     std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8469     unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8470   // First create the ValueInfo utilizing the Name or GUID.
8471   ValueInfo VI;
8472   if (GUID != 0) {
8473     assert(Name.empty());
8474     VI = Index->getOrInsertValueInfo(GUID);
8475   } else {
8476     assert(!Name.empty());
8477     if (M) {
8478       auto *GV = M->getNamedValue(Name);
8479       assert(GV);
8480       VI = Index->getOrInsertValueInfo(GV);
8481     } else {
8482       assert(
8483           (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8484           "Need a source_filename to compute GUID for local");
8485       GUID = GlobalValue::getGUID(
8486           GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8487       VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8488     }
8489   }
8490 
8491   // Resolve forward references from calls/refs
8492   auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8493   if (FwdRefVIs != ForwardRefValueInfos.end()) {
8494     for (auto VIRef : FwdRefVIs->second) {
8495       assert(VIRef.first->getRef() == FwdVIRef &&
8496              "Forward referenced ValueInfo expected to be empty");
8497       resolveFwdRef(VIRef.first, VI);
8498     }
8499     ForwardRefValueInfos.erase(FwdRefVIs);
8500   }
8501 
8502   // Resolve forward references from aliases
8503   auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8504   if (FwdRefAliasees != ForwardRefAliasees.end()) {
8505     for (auto AliaseeRef : FwdRefAliasees->second) {
8506       assert(!AliaseeRef.first->hasAliasee() &&
8507              "Forward referencing alias already has aliasee");
8508       assert(Summary && "Aliasee must be a definition");
8509       AliaseeRef.first->setAliasee(VI, Summary.get());
8510     }
8511     ForwardRefAliasees.erase(FwdRefAliasees);
8512   }
8513 
8514   // Add the summary if one was provided.
8515   if (Summary)
8516     Index->addGlobalValueSummary(VI, std::move(Summary));
8517 
8518   // Save the associated ValueInfo for use in later references by ID.
8519   if (ID == NumberedValueInfos.size())
8520     NumberedValueInfos.push_back(VI);
8521   else {
8522     // Handle non-continuous numbers (to make test simplification easier).
8523     if (ID > NumberedValueInfos.size())
8524       NumberedValueInfos.resize(ID + 1);
8525     NumberedValueInfos[ID] = VI;
8526   }
8527 }
8528 
8529 /// parseSummaryIndexFlags
8530 ///   ::= 'flags' ':' UInt64
8531 bool LLParser::parseSummaryIndexFlags() {
8532   assert(Lex.getKind() == lltok::kw_flags);
8533   Lex.Lex();
8534 
8535   if (parseToken(lltok::colon, "expected ':' here"))
8536     return true;
8537   uint64_t Flags;
8538   if (parseUInt64(Flags))
8539     return true;
8540   if (Index)
8541     Index->setFlags(Flags);
8542   return false;
8543 }
8544 
8545 /// parseBlockCount
8546 ///   ::= 'blockcount' ':' UInt64
8547 bool LLParser::parseBlockCount() {
8548   assert(Lex.getKind() == lltok::kw_blockcount);
8549   Lex.Lex();
8550 
8551   if (parseToken(lltok::colon, "expected ':' here"))
8552     return true;
8553   uint64_t BlockCount;
8554   if (parseUInt64(BlockCount))
8555     return true;
8556   if (Index)
8557     Index->setBlockCount(BlockCount);
8558   return false;
8559 }
8560 
8561 /// parseGVEntry
8562 ///   ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8563 ///         [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8564 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8565 bool LLParser::parseGVEntry(unsigned ID) {
8566   assert(Lex.getKind() == lltok::kw_gv);
8567   Lex.Lex();
8568 
8569   if (parseToken(lltok::colon, "expected ':' here") ||
8570       parseToken(lltok::lparen, "expected '(' here"))
8571     return true;
8572 
8573   std::string Name;
8574   GlobalValue::GUID GUID = 0;
8575   switch (Lex.getKind()) {
8576   case lltok::kw_name:
8577     Lex.Lex();
8578     if (parseToken(lltok::colon, "expected ':' here") ||
8579         parseStringConstant(Name))
8580       return true;
8581     // Can't create GUID/ValueInfo until we have the linkage.
8582     break;
8583   case lltok::kw_guid:
8584     Lex.Lex();
8585     if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8586       return true;
8587     break;
8588   default:
8589     return error(Lex.getLoc(), "expected name or guid tag");
8590   }
8591 
8592   if (!EatIfPresent(lltok::comma)) {
8593     // No summaries. Wrap up.
8594     if (parseToken(lltok::rparen, "expected ')' here"))
8595       return true;
8596     // This was created for a call to an external or indirect target.
8597     // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8598     // created for indirect calls with VP. A Name with no GUID came from
8599     // an external definition. We pass ExternalLinkage since that is only
8600     // used when the GUID must be computed from Name, and in that case
8601     // the symbol must have external linkage.
8602     addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8603                           nullptr);
8604     return false;
8605   }
8606 
8607   // Have a list of summaries
8608   if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8609       parseToken(lltok::colon, "expected ':' here") ||
8610       parseToken(lltok::lparen, "expected '(' here"))
8611     return true;
8612   do {
8613     switch (Lex.getKind()) {
8614     case lltok::kw_function:
8615       if (parseFunctionSummary(Name, GUID, ID))
8616         return true;
8617       break;
8618     case lltok::kw_variable:
8619       if (parseVariableSummary(Name, GUID, ID))
8620         return true;
8621       break;
8622     case lltok::kw_alias:
8623       if (parseAliasSummary(Name, GUID, ID))
8624         return true;
8625       break;
8626     default:
8627       return error(Lex.getLoc(), "expected summary type");
8628     }
8629   } while (EatIfPresent(lltok::comma));
8630 
8631   if (parseToken(lltok::rparen, "expected ')' here") ||
8632       parseToken(lltok::rparen, "expected ')' here"))
8633     return true;
8634 
8635   return false;
8636 }
8637 
8638 /// FunctionSummary
8639 ///   ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8640 ///         ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8641 ///         [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8642 ///         [',' OptionalRefs]? ')'
8643 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8644                                     unsigned ID) {
8645   assert(Lex.getKind() == lltok::kw_function);
8646   Lex.Lex();
8647 
8648   StringRef ModulePath;
8649   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8650       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8651       /*NotEligibleToImport=*/false,
8652       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8653   unsigned InstCount;
8654   std::vector<FunctionSummary::EdgeTy> Calls;
8655   FunctionSummary::TypeIdInfo TypeIdInfo;
8656   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8657   std::vector<ValueInfo> Refs;
8658   // Default is all-zeros (conservative values).
8659   FunctionSummary::FFlags FFlags = {};
8660   if (parseToken(lltok::colon, "expected ':' here") ||
8661       parseToken(lltok::lparen, "expected '(' here") ||
8662       parseModuleReference(ModulePath) ||
8663       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8664       parseToken(lltok::comma, "expected ',' here") ||
8665       parseToken(lltok::kw_insts, "expected 'insts' here") ||
8666       parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8667     return true;
8668 
8669   // parse optional fields
8670   while (EatIfPresent(lltok::comma)) {
8671     switch (Lex.getKind()) {
8672     case lltok::kw_funcFlags:
8673       if (parseOptionalFFlags(FFlags))
8674         return true;
8675       break;
8676     case lltok::kw_calls:
8677       if (parseOptionalCalls(Calls))
8678         return true;
8679       break;
8680     case lltok::kw_typeIdInfo:
8681       if (parseOptionalTypeIdInfo(TypeIdInfo))
8682         return true;
8683       break;
8684     case lltok::kw_refs:
8685       if (parseOptionalRefs(Refs))
8686         return true;
8687       break;
8688     case lltok::kw_params:
8689       if (parseOptionalParamAccesses(ParamAccesses))
8690         return true;
8691       break;
8692     default:
8693       return error(Lex.getLoc(), "expected optional function summary field");
8694     }
8695   }
8696 
8697   if (parseToken(lltok::rparen, "expected ')' here"))
8698     return true;
8699 
8700   auto FS = std::make_unique<FunctionSummary>(
8701       GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8702       std::move(Calls), std::move(TypeIdInfo.TypeTests),
8703       std::move(TypeIdInfo.TypeTestAssumeVCalls),
8704       std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8705       std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8706       std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8707       std::move(ParamAccesses));
8708 
8709   FS->setModulePath(ModulePath);
8710 
8711   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8712                         ID, std::move(FS));
8713 
8714   return false;
8715 }
8716 
8717 /// VariableSummary
8718 ///   ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8719 ///         [',' OptionalRefs]? ')'
8720 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8721                                     unsigned ID) {
8722   assert(Lex.getKind() == lltok::kw_variable);
8723   Lex.Lex();
8724 
8725   StringRef ModulePath;
8726   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8727       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8728       /*NotEligibleToImport=*/false,
8729       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8730   GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8731                                         /* WriteOnly */ false,
8732                                         /* Constant */ false,
8733                                         GlobalObject::VCallVisibilityPublic);
8734   std::vector<ValueInfo> Refs;
8735   VTableFuncList VTableFuncs;
8736   if (parseToken(lltok::colon, "expected ':' here") ||
8737       parseToken(lltok::lparen, "expected '(' here") ||
8738       parseModuleReference(ModulePath) ||
8739       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8740       parseToken(lltok::comma, "expected ',' here") ||
8741       parseGVarFlags(GVarFlags))
8742     return true;
8743 
8744   // parse optional fields
8745   while (EatIfPresent(lltok::comma)) {
8746     switch (Lex.getKind()) {
8747     case lltok::kw_vTableFuncs:
8748       if (parseOptionalVTableFuncs(VTableFuncs))
8749         return true;
8750       break;
8751     case lltok::kw_refs:
8752       if (parseOptionalRefs(Refs))
8753         return true;
8754       break;
8755     default:
8756       return error(Lex.getLoc(), "expected optional variable summary field");
8757     }
8758   }
8759 
8760   if (parseToken(lltok::rparen, "expected ')' here"))
8761     return true;
8762 
8763   auto GS =
8764       std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8765 
8766   GS->setModulePath(ModulePath);
8767   GS->setVTableFuncs(std::move(VTableFuncs));
8768 
8769   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8770                         ID, std::move(GS));
8771 
8772   return false;
8773 }
8774 
8775 /// AliasSummary
8776 ///   ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8777 ///         'aliasee' ':' GVReference ')'
8778 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8779                                  unsigned ID) {
8780   assert(Lex.getKind() == lltok::kw_alias);
8781   LocTy Loc = Lex.getLoc();
8782   Lex.Lex();
8783 
8784   StringRef ModulePath;
8785   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8786       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8787       /*NotEligibleToImport=*/false,
8788       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8789   if (parseToken(lltok::colon, "expected ':' here") ||
8790       parseToken(lltok::lparen, "expected '(' here") ||
8791       parseModuleReference(ModulePath) ||
8792       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8793       parseToken(lltok::comma, "expected ',' here") ||
8794       parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8795       parseToken(lltok::colon, "expected ':' here"))
8796     return true;
8797 
8798   ValueInfo AliaseeVI;
8799   unsigned GVId;
8800   if (parseGVReference(AliaseeVI, GVId))
8801     return true;
8802 
8803   if (parseToken(lltok::rparen, "expected ')' here"))
8804     return true;
8805 
8806   auto AS = std::make_unique<AliasSummary>(GVFlags);
8807 
8808   AS->setModulePath(ModulePath);
8809 
8810   // Record forward reference if the aliasee is not parsed yet.
8811   if (AliaseeVI.getRef() == FwdVIRef) {
8812     ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8813   } else {
8814     auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8815     assert(Summary && "Aliasee must be a definition");
8816     AS->setAliasee(AliaseeVI, Summary);
8817   }
8818 
8819   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8820                         ID, std::move(AS));
8821 
8822   return false;
8823 }
8824 
8825 /// Flag
8826 ///   ::= [0|1]
8827 bool LLParser::parseFlag(unsigned &Val) {
8828   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8829     return tokError("expected integer");
8830   Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8831   Lex.Lex();
8832   return false;
8833 }
8834 
8835 /// OptionalFFlags
8836 ///   := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8837 ///        [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8838 ///        [',' 'returnDoesNotAlias' ':' Flag]? ')'
8839 ///        [',' 'noInline' ':' Flag]? ')'
8840 ///        [',' 'alwaysInline' ':' Flag]? ')'
8841 
8842 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8843   assert(Lex.getKind() == lltok::kw_funcFlags);
8844   Lex.Lex();
8845 
8846   if (parseToken(lltok::colon, "expected ':' in funcFlags") |
8847       parseToken(lltok::lparen, "expected '(' in funcFlags"))
8848     return true;
8849 
8850   do {
8851     unsigned Val = 0;
8852     switch (Lex.getKind()) {
8853     case lltok::kw_readNone:
8854       Lex.Lex();
8855       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8856         return true;
8857       FFlags.ReadNone = Val;
8858       break;
8859     case lltok::kw_readOnly:
8860       Lex.Lex();
8861       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8862         return true;
8863       FFlags.ReadOnly = Val;
8864       break;
8865     case lltok::kw_noRecurse:
8866       Lex.Lex();
8867       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8868         return true;
8869       FFlags.NoRecurse = Val;
8870       break;
8871     case lltok::kw_returnDoesNotAlias:
8872       Lex.Lex();
8873       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8874         return true;
8875       FFlags.ReturnDoesNotAlias = Val;
8876       break;
8877     case lltok::kw_noInline:
8878       Lex.Lex();
8879       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8880         return true;
8881       FFlags.NoInline = Val;
8882       break;
8883     case lltok::kw_alwaysInline:
8884       Lex.Lex();
8885       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8886         return true;
8887       FFlags.AlwaysInline = Val;
8888       break;
8889     default:
8890       return error(Lex.getLoc(), "expected function flag type");
8891     }
8892   } while (EatIfPresent(lltok::comma));
8893 
8894   if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8895     return true;
8896 
8897   return false;
8898 }
8899 
8900 /// OptionalCalls
8901 ///   := 'calls' ':' '(' Call [',' Call]* ')'
8902 /// Call ::= '(' 'callee' ':' GVReference
8903 ///            [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8904 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8905   assert(Lex.getKind() == lltok::kw_calls);
8906   Lex.Lex();
8907 
8908   if (parseToken(lltok::colon, "expected ':' in calls") |
8909       parseToken(lltok::lparen, "expected '(' in calls"))
8910     return true;
8911 
8912   IdToIndexMapType IdToIndexMap;
8913   // parse each call edge
8914   do {
8915     ValueInfo VI;
8916     if (parseToken(lltok::lparen, "expected '(' in call") ||
8917         parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8918         parseToken(lltok::colon, "expected ':'"))
8919       return true;
8920 
8921     LocTy Loc = Lex.getLoc();
8922     unsigned GVId;
8923     if (parseGVReference(VI, GVId))
8924       return true;
8925 
8926     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8927     unsigned RelBF = 0;
8928     if (EatIfPresent(lltok::comma)) {
8929       // Expect either hotness or relbf
8930       if (EatIfPresent(lltok::kw_hotness)) {
8931         if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8932           return true;
8933       } else {
8934         if (parseToken(lltok::kw_relbf, "expected relbf") ||
8935             parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8936           return true;
8937       }
8938     }
8939     // Keep track of the Call array index needing a forward reference.
8940     // We will save the location of the ValueInfo needing an update, but
8941     // can only do so once the std::vector is finalized.
8942     if (VI.getRef() == FwdVIRef)
8943       IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8944     Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8945 
8946     if (parseToken(lltok::rparen, "expected ')' in call"))
8947       return true;
8948   } while (EatIfPresent(lltok::comma));
8949 
8950   // Now that the Calls vector is finalized, it is safe to save the locations
8951   // of any forward GV references that need updating later.
8952   for (auto I : IdToIndexMap) {
8953     auto &Infos = ForwardRefValueInfos[I.first];
8954     for (auto P : I.second) {
8955       assert(Calls[P.first].first.getRef() == FwdVIRef &&
8956              "Forward referenced ValueInfo expected to be empty");
8957       Infos.emplace_back(&Calls[P.first].first, P.second);
8958     }
8959   }
8960 
8961   if (parseToken(lltok::rparen, "expected ')' in calls"))
8962     return true;
8963 
8964   return false;
8965 }
8966 
8967 /// Hotness
8968 ///   := ('unknown'|'cold'|'none'|'hot'|'critical')
8969 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8970   switch (Lex.getKind()) {
8971   case lltok::kw_unknown:
8972     Hotness = CalleeInfo::HotnessType::Unknown;
8973     break;
8974   case lltok::kw_cold:
8975     Hotness = CalleeInfo::HotnessType::Cold;
8976     break;
8977   case lltok::kw_none:
8978     Hotness = CalleeInfo::HotnessType::None;
8979     break;
8980   case lltok::kw_hot:
8981     Hotness = CalleeInfo::HotnessType::Hot;
8982     break;
8983   case lltok::kw_critical:
8984     Hotness = CalleeInfo::HotnessType::Critical;
8985     break;
8986   default:
8987     return error(Lex.getLoc(), "invalid call edge hotness");
8988   }
8989   Lex.Lex();
8990   return false;
8991 }
8992 
8993 /// OptionalVTableFuncs
8994 ///   := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8995 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8996 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8997   assert(Lex.getKind() == lltok::kw_vTableFuncs);
8998   Lex.Lex();
8999 
9000   if (parseToken(lltok::colon, "expected ':' in vTableFuncs") |
9001       parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9002     return true;
9003 
9004   IdToIndexMapType IdToIndexMap;
9005   // parse each virtual function pair
9006   do {
9007     ValueInfo VI;
9008     if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9009         parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9010         parseToken(lltok::colon, "expected ':'"))
9011       return true;
9012 
9013     LocTy Loc = Lex.getLoc();
9014     unsigned GVId;
9015     if (parseGVReference(VI, GVId))
9016       return true;
9017 
9018     uint64_t Offset;
9019     if (parseToken(lltok::comma, "expected comma") ||
9020         parseToken(lltok::kw_offset, "expected offset") ||
9021         parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9022       return true;
9023 
9024     // Keep track of the VTableFuncs array index needing a forward reference.
9025     // We will save the location of the ValueInfo needing an update, but
9026     // can only do so once the std::vector is finalized.
9027     if (VI == EmptyVI)
9028       IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9029     VTableFuncs.push_back({VI, Offset});
9030 
9031     if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9032       return true;
9033   } while (EatIfPresent(lltok::comma));
9034 
9035   // Now that the VTableFuncs vector is finalized, it is safe to save the
9036   // locations of any forward GV references that need updating later.
9037   for (auto I : IdToIndexMap) {
9038     auto &Infos = ForwardRefValueInfos[I.first];
9039     for (auto P : I.second) {
9040       assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9041              "Forward referenced ValueInfo expected to be empty");
9042       Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9043     }
9044   }
9045 
9046   if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9047     return true;
9048 
9049   return false;
9050 }
9051 
9052 /// ParamNo := 'param' ':' UInt64
9053 bool LLParser::parseParamNo(uint64_t &ParamNo) {
9054   if (parseToken(lltok::kw_param, "expected 'param' here") ||
9055       parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9056     return true;
9057   return false;
9058 }
9059 
9060 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9061 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9062   APSInt Lower;
9063   APSInt Upper;
9064   auto ParseAPSInt = [&](APSInt &Val) {
9065     if (Lex.getKind() != lltok::APSInt)
9066       return tokError("expected integer");
9067     Val = Lex.getAPSIntVal();
9068     Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9069     Val.setIsSigned(true);
9070     Lex.Lex();
9071     return false;
9072   };
9073   if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9074       parseToken(lltok::colon, "expected ':' here") ||
9075       parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9076       parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9077       parseToken(lltok::rsquare, "expected ']' here"))
9078     return true;
9079 
9080   ++Upper;
9081   Range =
9082       (Lower == Upper && !Lower.isMaxValue())
9083           ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9084           : ConstantRange(Lower, Upper);
9085 
9086   return false;
9087 }
9088 
9089 /// ParamAccessCall
9090 ///   := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9091 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9092                                     IdLocListType &IdLocList) {
9093   if (parseToken(lltok::lparen, "expected '(' here") ||
9094       parseToken(lltok::kw_callee, "expected 'callee' here") ||
9095       parseToken(lltok::colon, "expected ':' here"))
9096     return true;
9097 
9098   unsigned GVId;
9099   ValueInfo VI;
9100   LocTy Loc = Lex.getLoc();
9101   if (parseGVReference(VI, GVId))
9102     return true;
9103 
9104   Call.Callee = VI;
9105   IdLocList.emplace_back(GVId, Loc);
9106 
9107   if (parseToken(lltok::comma, "expected ',' here") ||
9108       parseParamNo(Call.ParamNo) ||
9109       parseToken(lltok::comma, "expected ',' here") ||
9110       parseParamAccessOffset(Call.Offsets))
9111     return true;
9112 
9113   if (parseToken(lltok::rparen, "expected ')' here"))
9114     return true;
9115 
9116   return false;
9117 }
9118 
9119 /// ParamAccess
9120 ///   := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9121 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9122 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
9123                                 IdLocListType &IdLocList) {
9124   if (parseToken(lltok::lparen, "expected '(' here") ||
9125       parseParamNo(Param.ParamNo) ||
9126       parseToken(lltok::comma, "expected ',' here") ||
9127       parseParamAccessOffset(Param.Use))
9128     return true;
9129 
9130   if (EatIfPresent(lltok::comma)) {
9131     if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
9132         parseToken(lltok::colon, "expected ':' here") ||
9133         parseToken(lltok::lparen, "expected '(' here"))
9134       return true;
9135     do {
9136       FunctionSummary::ParamAccess::Call Call;
9137       if (parseParamAccessCall(Call, IdLocList))
9138         return true;
9139       Param.Calls.push_back(Call);
9140     } while (EatIfPresent(lltok::comma));
9141 
9142     if (parseToken(lltok::rparen, "expected ')' here"))
9143       return true;
9144   }
9145 
9146   if (parseToken(lltok::rparen, "expected ')' here"))
9147     return true;
9148 
9149   return false;
9150 }
9151 
9152 /// OptionalParamAccesses
9153 ///   := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9154 bool LLParser::parseOptionalParamAccesses(
9155     std::vector<FunctionSummary::ParamAccess> &Params) {
9156   assert(Lex.getKind() == lltok::kw_params);
9157   Lex.Lex();
9158 
9159   if (parseToken(lltok::colon, "expected ':' here") ||
9160       parseToken(lltok::lparen, "expected '(' here"))
9161     return true;
9162 
9163   IdLocListType VContexts;
9164   size_t CallsNum = 0;
9165   do {
9166     FunctionSummary::ParamAccess ParamAccess;
9167     if (parseParamAccess(ParamAccess, VContexts))
9168       return true;
9169     CallsNum += ParamAccess.Calls.size();
9170     assert(VContexts.size() == CallsNum);
9171     Params.emplace_back(std::move(ParamAccess));
9172   } while (EatIfPresent(lltok::comma));
9173 
9174   if (parseToken(lltok::rparen, "expected ')' here"))
9175     return true;
9176 
9177   // Now that the Params is finalized, it is safe to save the locations
9178   // of any forward GV references that need updating later.
9179   IdLocListType::const_iterator ItContext = VContexts.begin();
9180   for (auto &PA : Params) {
9181     for (auto &C : PA.Calls) {
9182       if (C.Callee.getRef() == FwdVIRef)
9183         ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9184                                                             ItContext->second);
9185       ++ItContext;
9186     }
9187   }
9188   assert(ItContext == VContexts.end());
9189 
9190   return false;
9191 }
9192 
9193 /// OptionalRefs
9194 ///   := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9195 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9196   assert(Lex.getKind() == lltok::kw_refs);
9197   Lex.Lex();
9198 
9199   if (parseToken(lltok::colon, "expected ':' in refs") ||
9200       parseToken(lltok::lparen, "expected '(' in refs"))
9201     return true;
9202 
9203   struct ValueContext {
9204     ValueInfo VI;
9205     unsigned GVId;
9206     LocTy Loc;
9207   };
9208   std::vector<ValueContext> VContexts;
9209   // parse each ref edge
9210   do {
9211     ValueContext VC;
9212     VC.Loc = Lex.getLoc();
9213     if (parseGVReference(VC.VI, VC.GVId))
9214       return true;
9215     VContexts.push_back(VC);
9216   } while (EatIfPresent(lltok::comma));
9217 
9218   // Sort value contexts so that ones with writeonly
9219   // and readonly ValueInfo  are at the end of VContexts vector.
9220   // See FunctionSummary::specialRefCounts()
9221   llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9222     return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9223   });
9224 
9225   IdToIndexMapType IdToIndexMap;
9226   for (auto &VC : VContexts) {
9227     // Keep track of the Refs array index needing a forward reference.
9228     // We will save the location of the ValueInfo needing an update, but
9229     // can only do so once the std::vector is finalized.
9230     if (VC.VI.getRef() == FwdVIRef)
9231       IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9232     Refs.push_back(VC.VI);
9233   }
9234 
9235   // Now that the Refs vector is finalized, it is safe to save the locations
9236   // of any forward GV references that need updating later.
9237   for (auto I : IdToIndexMap) {
9238     auto &Infos = ForwardRefValueInfos[I.first];
9239     for (auto P : I.second) {
9240       assert(Refs[P.first].getRef() == FwdVIRef &&
9241              "Forward referenced ValueInfo expected to be empty");
9242       Infos.emplace_back(&Refs[P.first], P.second);
9243     }
9244   }
9245 
9246   if (parseToken(lltok::rparen, "expected ')' in refs"))
9247     return true;
9248 
9249   return false;
9250 }
9251 
9252 /// OptionalTypeIdInfo
9253 ///   := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9254 ///         [',' TypeCheckedLoadVCalls]?  [',' TypeTestAssumeConstVCalls]?
9255 ///         [',' TypeCheckedLoadConstVCalls]? ')'
9256 bool LLParser::parseOptionalTypeIdInfo(
9257     FunctionSummary::TypeIdInfo &TypeIdInfo) {
9258   assert(Lex.getKind() == lltok::kw_typeIdInfo);
9259   Lex.Lex();
9260 
9261   if (parseToken(lltok::colon, "expected ':' here") ||
9262       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9263     return true;
9264 
9265   do {
9266     switch (Lex.getKind()) {
9267     case lltok::kw_typeTests:
9268       if (parseTypeTests(TypeIdInfo.TypeTests))
9269         return true;
9270       break;
9271     case lltok::kw_typeTestAssumeVCalls:
9272       if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9273                            TypeIdInfo.TypeTestAssumeVCalls))
9274         return true;
9275       break;
9276     case lltok::kw_typeCheckedLoadVCalls:
9277       if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9278                            TypeIdInfo.TypeCheckedLoadVCalls))
9279         return true;
9280       break;
9281     case lltok::kw_typeTestAssumeConstVCalls:
9282       if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9283                               TypeIdInfo.TypeTestAssumeConstVCalls))
9284         return true;
9285       break;
9286     case lltok::kw_typeCheckedLoadConstVCalls:
9287       if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9288                               TypeIdInfo.TypeCheckedLoadConstVCalls))
9289         return true;
9290       break;
9291     default:
9292       return error(Lex.getLoc(), "invalid typeIdInfo list type");
9293     }
9294   } while (EatIfPresent(lltok::comma));
9295 
9296   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9297     return true;
9298 
9299   return false;
9300 }
9301 
9302 /// TypeTests
9303 ///   ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9304 ///         [',' (SummaryID | UInt64)]* ')'
9305 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9306   assert(Lex.getKind() == lltok::kw_typeTests);
9307   Lex.Lex();
9308 
9309   if (parseToken(lltok::colon, "expected ':' here") ||
9310       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9311     return true;
9312 
9313   IdToIndexMapType IdToIndexMap;
9314   do {
9315     GlobalValue::GUID GUID = 0;
9316     if (Lex.getKind() == lltok::SummaryID) {
9317       unsigned ID = Lex.getUIntVal();
9318       LocTy Loc = Lex.getLoc();
9319       // Keep track of the TypeTests array index needing a forward reference.
9320       // We will save the location of the GUID needing an update, but
9321       // can only do so once the std::vector is finalized.
9322       IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9323       Lex.Lex();
9324     } else if (parseUInt64(GUID))
9325       return true;
9326     TypeTests.push_back(GUID);
9327   } while (EatIfPresent(lltok::comma));
9328 
9329   // Now that the TypeTests vector is finalized, it is safe to save the
9330   // locations of any forward GV references that need updating later.
9331   for (auto I : IdToIndexMap) {
9332     auto &Ids = ForwardRefTypeIds[I.first];
9333     for (auto P : I.second) {
9334       assert(TypeTests[P.first] == 0 &&
9335              "Forward referenced type id GUID expected to be 0");
9336       Ids.emplace_back(&TypeTests[P.first], P.second);
9337     }
9338   }
9339 
9340   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9341     return true;
9342 
9343   return false;
9344 }
9345 
9346 /// VFuncIdList
9347 ///   ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9348 bool LLParser::parseVFuncIdList(
9349     lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9350   assert(Lex.getKind() == Kind);
9351   Lex.Lex();
9352 
9353   if (parseToken(lltok::colon, "expected ':' here") ||
9354       parseToken(lltok::lparen, "expected '(' here"))
9355     return true;
9356 
9357   IdToIndexMapType IdToIndexMap;
9358   do {
9359     FunctionSummary::VFuncId VFuncId;
9360     if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9361       return true;
9362     VFuncIdList.push_back(VFuncId);
9363   } while (EatIfPresent(lltok::comma));
9364 
9365   if (parseToken(lltok::rparen, "expected ')' here"))
9366     return true;
9367 
9368   // Now that the VFuncIdList vector is finalized, it is safe to save the
9369   // locations of any forward GV references that need updating later.
9370   for (auto I : IdToIndexMap) {
9371     auto &Ids = ForwardRefTypeIds[I.first];
9372     for (auto P : I.second) {
9373       assert(VFuncIdList[P.first].GUID == 0 &&
9374              "Forward referenced type id GUID expected to be 0");
9375       Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9376     }
9377   }
9378 
9379   return false;
9380 }
9381 
9382 /// ConstVCallList
9383 ///   ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9384 bool LLParser::parseConstVCallList(
9385     lltok::Kind Kind,
9386     std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9387   assert(Lex.getKind() == Kind);
9388   Lex.Lex();
9389 
9390   if (parseToken(lltok::colon, "expected ':' here") ||
9391       parseToken(lltok::lparen, "expected '(' here"))
9392     return true;
9393 
9394   IdToIndexMapType IdToIndexMap;
9395   do {
9396     FunctionSummary::ConstVCall ConstVCall;
9397     if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9398       return true;
9399     ConstVCallList.push_back(ConstVCall);
9400   } while (EatIfPresent(lltok::comma));
9401 
9402   if (parseToken(lltok::rparen, "expected ')' here"))
9403     return true;
9404 
9405   // Now that the ConstVCallList vector is finalized, it is safe to save the
9406   // locations of any forward GV references that need updating later.
9407   for (auto I : IdToIndexMap) {
9408     auto &Ids = ForwardRefTypeIds[I.first];
9409     for (auto P : I.second) {
9410       assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9411              "Forward referenced type id GUID expected to be 0");
9412       Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9413     }
9414   }
9415 
9416   return false;
9417 }
9418 
9419 /// ConstVCall
9420 ///   ::= '(' VFuncId ',' Args ')'
9421 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9422                                IdToIndexMapType &IdToIndexMap, unsigned Index) {
9423   if (parseToken(lltok::lparen, "expected '(' here") ||
9424       parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9425     return true;
9426 
9427   if (EatIfPresent(lltok::comma))
9428     if (parseArgs(ConstVCall.Args))
9429       return true;
9430 
9431   if (parseToken(lltok::rparen, "expected ')' here"))
9432     return true;
9433 
9434   return false;
9435 }
9436 
9437 /// VFuncId
9438 ///   ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9439 ///         'offset' ':' UInt64 ')'
9440 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9441                             IdToIndexMapType &IdToIndexMap, unsigned Index) {
9442   assert(Lex.getKind() == lltok::kw_vFuncId);
9443   Lex.Lex();
9444 
9445   if (parseToken(lltok::colon, "expected ':' here") ||
9446       parseToken(lltok::lparen, "expected '(' here"))
9447     return true;
9448 
9449   if (Lex.getKind() == lltok::SummaryID) {
9450     VFuncId.GUID = 0;
9451     unsigned ID = Lex.getUIntVal();
9452     LocTy Loc = Lex.getLoc();
9453     // Keep track of the array index needing a forward reference.
9454     // We will save the location of the GUID needing an update, but
9455     // can only do so once the caller's std::vector is finalized.
9456     IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9457     Lex.Lex();
9458   } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9459              parseToken(lltok::colon, "expected ':' here") ||
9460              parseUInt64(VFuncId.GUID))
9461     return true;
9462 
9463   if (parseToken(lltok::comma, "expected ',' here") ||
9464       parseToken(lltok::kw_offset, "expected 'offset' here") ||
9465       parseToken(lltok::colon, "expected ':' here") ||
9466       parseUInt64(VFuncId.Offset) ||
9467       parseToken(lltok::rparen, "expected ')' here"))
9468     return true;
9469 
9470   return false;
9471 }
9472 
9473 /// GVFlags
9474 ///   ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9475 ///         'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9476 ///         'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9477 ///         'canAutoHide' ':' Flag ',' ')'
9478 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9479   assert(Lex.getKind() == lltok::kw_flags);
9480   Lex.Lex();
9481 
9482   if (parseToken(lltok::colon, "expected ':' here") ||
9483       parseToken(lltok::lparen, "expected '(' here"))
9484     return true;
9485 
9486   do {
9487     unsigned Flag = 0;
9488     switch (Lex.getKind()) {
9489     case lltok::kw_linkage:
9490       Lex.Lex();
9491       if (parseToken(lltok::colon, "expected ':'"))
9492         return true;
9493       bool HasLinkage;
9494       GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9495       assert(HasLinkage && "Linkage not optional in summary entry");
9496       Lex.Lex();
9497       break;
9498     case lltok::kw_visibility:
9499       Lex.Lex();
9500       if (parseToken(lltok::colon, "expected ':'"))
9501         return true;
9502       parseOptionalVisibility(Flag);
9503       GVFlags.Visibility = Flag;
9504       break;
9505     case lltok::kw_notEligibleToImport:
9506       Lex.Lex();
9507       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9508         return true;
9509       GVFlags.NotEligibleToImport = Flag;
9510       break;
9511     case lltok::kw_live:
9512       Lex.Lex();
9513       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9514         return true;
9515       GVFlags.Live = Flag;
9516       break;
9517     case lltok::kw_dsoLocal:
9518       Lex.Lex();
9519       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9520         return true;
9521       GVFlags.DSOLocal = Flag;
9522       break;
9523     case lltok::kw_canAutoHide:
9524       Lex.Lex();
9525       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9526         return true;
9527       GVFlags.CanAutoHide = Flag;
9528       break;
9529     default:
9530       return error(Lex.getLoc(), "expected gv flag type");
9531     }
9532   } while (EatIfPresent(lltok::comma));
9533 
9534   if (parseToken(lltok::rparen, "expected ')' here"))
9535     return true;
9536 
9537   return false;
9538 }
9539 
9540 /// GVarFlags
9541 ///   ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9542 ///                      ',' 'writeonly' ':' Flag
9543 ///                      ',' 'constant' ':' Flag ')'
9544 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9545   assert(Lex.getKind() == lltok::kw_varFlags);
9546   Lex.Lex();
9547 
9548   if (parseToken(lltok::colon, "expected ':' here") ||
9549       parseToken(lltok::lparen, "expected '(' here"))
9550     return true;
9551 
9552   auto ParseRest = [this](unsigned int &Val) {
9553     Lex.Lex();
9554     if (parseToken(lltok::colon, "expected ':'"))
9555       return true;
9556     return parseFlag(Val);
9557   };
9558 
9559   do {
9560     unsigned Flag = 0;
9561     switch (Lex.getKind()) {
9562     case lltok::kw_readonly:
9563       if (ParseRest(Flag))
9564         return true;
9565       GVarFlags.MaybeReadOnly = Flag;
9566       break;
9567     case lltok::kw_writeonly:
9568       if (ParseRest(Flag))
9569         return true;
9570       GVarFlags.MaybeWriteOnly = Flag;
9571       break;
9572     case lltok::kw_constant:
9573       if (ParseRest(Flag))
9574         return true;
9575       GVarFlags.Constant = Flag;
9576       break;
9577     case lltok::kw_vcall_visibility:
9578       if (ParseRest(Flag))
9579         return true;
9580       GVarFlags.VCallVisibility = Flag;
9581       break;
9582     default:
9583       return error(Lex.getLoc(), "expected gvar flag type");
9584     }
9585   } while (EatIfPresent(lltok::comma));
9586   return parseToken(lltok::rparen, "expected ')' here");
9587 }
9588 
9589 /// ModuleReference
9590 ///   ::= 'module' ':' UInt
9591 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9592   // parse module id.
9593   if (parseToken(lltok::kw_module, "expected 'module' here") ||
9594       parseToken(lltok::colon, "expected ':' here") ||
9595       parseToken(lltok::SummaryID, "expected module ID"))
9596     return true;
9597 
9598   unsigned ModuleID = Lex.getUIntVal();
9599   auto I = ModuleIdMap.find(ModuleID);
9600   // We should have already parsed all module IDs
9601   assert(I != ModuleIdMap.end());
9602   ModulePath = I->second;
9603   return false;
9604 }
9605 
9606 /// GVReference
9607 ///   ::= SummaryID
9608 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9609   bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9610   if (!ReadOnly)
9611     WriteOnly = EatIfPresent(lltok::kw_writeonly);
9612   if (parseToken(lltok::SummaryID, "expected GV ID"))
9613     return true;
9614 
9615   GVId = Lex.getUIntVal();
9616   // Check if we already have a VI for this GV
9617   if (GVId < NumberedValueInfos.size()) {
9618     assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9619     VI = NumberedValueInfos[GVId];
9620   } else
9621     // We will create a forward reference to the stored location.
9622     VI = ValueInfo(false, FwdVIRef);
9623 
9624   if (ReadOnly)
9625     VI.setReadOnly();
9626   if (WriteOnly)
9627     VI.setWriteOnly();
9628   return false;
9629 }
9630