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