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