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