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     return error(ID.Loc, "insertvalue constexprs are no longer supported");
3479   case lltok::kw_udiv:
3480     return error(ID.Loc, "udiv constexprs are no longer supported");
3481   case lltok::kw_sdiv:
3482     return error(ID.Loc, "sdiv constexprs are no longer supported");
3483   case lltok::kw_urem:
3484     return error(ID.Loc, "urem constexprs are no longer supported");
3485   case lltok::kw_srem:
3486     return error(ID.Loc, "srem constexprs are no longer supported");
3487   case lltok::kw_icmp:
3488   case lltok::kw_fcmp: {
3489     unsigned PredVal, Opc = Lex.getUIntVal();
3490     Constant *Val0, *Val1;
3491     Lex.Lex();
3492     if (parseCmpPredicate(PredVal, Opc) ||
3493         parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3494         parseGlobalTypeAndValue(Val0) ||
3495         parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3496         parseGlobalTypeAndValue(Val1) ||
3497         parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3498       return true;
3499 
3500     if (Val0->getType() != Val1->getType())
3501       return error(ID.Loc, "compare operands must have the same type");
3502 
3503     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3504 
3505     if (Opc == Instruction::FCmp) {
3506       if (!Val0->getType()->isFPOrFPVectorTy())
3507         return error(ID.Loc, "fcmp requires floating point operands");
3508       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3509     } else {
3510       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3511       if (!Val0->getType()->isIntOrIntVectorTy() &&
3512           !Val0->getType()->isPtrOrPtrVectorTy())
3513         return error(ID.Loc, "icmp requires pointer or integer operands");
3514       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3515     }
3516     ID.Kind = ValID::t_Constant;
3517     return false;
3518   }
3519 
3520   // Unary Operators.
3521   case lltok::kw_fneg: {
3522     unsigned Opc = Lex.getUIntVal();
3523     Constant *Val;
3524     Lex.Lex();
3525     if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3526         parseGlobalTypeAndValue(Val) ||
3527         parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3528       return true;
3529 
3530     // Check that the type is valid for the operator.
3531     switch (Opc) {
3532     case Instruction::FNeg:
3533       if (!Val->getType()->isFPOrFPVectorTy())
3534         return error(ID.Loc, "constexpr requires fp operands");
3535       break;
3536     default: llvm_unreachable("Unknown unary operator!");
3537     }
3538     unsigned Flags = 0;
3539     Constant *C = ConstantExpr::get(Opc, Val, Flags);
3540     ID.ConstantVal = C;
3541     ID.Kind = ValID::t_Constant;
3542     return false;
3543   }
3544   // Binary Operators.
3545   case lltok::kw_add:
3546   case lltok::kw_fadd:
3547   case lltok::kw_sub:
3548   case lltok::kw_fsub:
3549   case lltok::kw_mul:
3550   case lltok::kw_fmul:
3551   case lltok::kw_fdiv:
3552   case lltok::kw_frem:
3553   case lltok::kw_shl:
3554   case lltok::kw_lshr:
3555   case lltok::kw_ashr: {
3556     bool NUW = false;
3557     bool NSW = false;
3558     bool Exact = false;
3559     unsigned Opc = Lex.getUIntVal();
3560     Constant *Val0, *Val1;
3561     Lex.Lex();
3562     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3563         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3564       if (EatIfPresent(lltok::kw_nuw))
3565         NUW = true;
3566       if (EatIfPresent(lltok::kw_nsw)) {
3567         NSW = true;
3568         if (EatIfPresent(lltok::kw_nuw))
3569           NUW = true;
3570       }
3571     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3572                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3573       if (EatIfPresent(lltok::kw_exact))
3574         Exact = true;
3575     }
3576     if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3577         parseGlobalTypeAndValue(Val0) ||
3578         parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3579         parseGlobalTypeAndValue(Val1) ||
3580         parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3581       return true;
3582     if (Val0->getType() != Val1->getType())
3583       return error(ID.Loc, "operands of constexpr must have same type");
3584     // Check that the type is valid for the operator.
3585     switch (Opc) {
3586     case Instruction::Add:
3587     case Instruction::Sub:
3588     case Instruction::Mul:
3589     case Instruction::UDiv:
3590     case Instruction::SDiv:
3591     case Instruction::URem:
3592     case Instruction::SRem:
3593     case Instruction::Shl:
3594     case Instruction::AShr:
3595     case Instruction::LShr:
3596       if (!Val0->getType()->isIntOrIntVectorTy())
3597         return error(ID.Loc, "constexpr requires integer operands");
3598       break;
3599     case Instruction::FAdd:
3600     case Instruction::FSub:
3601     case Instruction::FMul:
3602     case Instruction::FDiv:
3603     case Instruction::FRem:
3604       if (!Val0->getType()->isFPOrFPVectorTy())
3605         return error(ID.Loc, "constexpr requires fp operands");
3606       break;
3607     default: llvm_unreachable("Unknown binary operator!");
3608     }
3609     unsigned Flags = 0;
3610     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3611     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3612     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3613     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3614     ID.ConstantVal = C;
3615     ID.Kind = ValID::t_Constant;
3616     return false;
3617   }
3618 
3619   // Logical Operations
3620   case lltok::kw_and:
3621   case lltok::kw_or:
3622   case lltok::kw_xor: {
3623     unsigned Opc = Lex.getUIntVal();
3624     Constant *Val0, *Val1;
3625     Lex.Lex();
3626     if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3627         parseGlobalTypeAndValue(Val0) ||
3628         parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3629         parseGlobalTypeAndValue(Val1) ||
3630         parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3631       return true;
3632     if (Val0->getType() != Val1->getType())
3633       return error(ID.Loc, "operands of constexpr must have same type");
3634     if (!Val0->getType()->isIntOrIntVectorTy())
3635       return error(ID.Loc,
3636                    "constexpr requires integer or integer vector operands");
3637     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3638     ID.Kind = ValID::t_Constant;
3639     return false;
3640   }
3641 
3642   case lltok::kw_getelementptr:
3643   case lltok::kw_shufflevector:
3644   case lltok::kw_insertelement:
3645   case lltok::kw_extractelement:
3646   case lltok::kw_select: {
3647     unsigned Opc = Lex.getUIntVal();
3648     SmallVector<Constant*, 16> Elts;
3649     bool InBounds = false;
3650     Type *Ty;
3651     Lex.Lex();
3652 
3653     if (Opc == Instruction::GetElementPtr)
3654       InBounds = EatIfPresent(lltok::kw_inbounds);
3655 
3656     if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3657       return true;
3658 
3659     LocTy ExplicitTypeLoc = Lex.getLoc();
3660     if (Opc == Instruction::GetElementPtr) {
3661       if (parseType(Ty) ||
3662           parseToken(lltok::comma, "expected comma after getelementptr's type"))
3663         return true;
3664     }
3665 
3666     Optional<unsigned> InRangeOp;
3667     if (parseGlobalValueVector(
3668             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3669         parseToken(lltok::rparen, "expected ')' in constantexpr"))
3670       return true;
3671 
3672     if (Opc == Instruction::GetElementPtr) {
3673       if (Elts.size() == 0 ||
3674           !Elts[0]->getType()->isPtrOrPtrVectorTy())
3675         return error(ID.Loc, "base of getelementptr must be a pointer");
3676 
3677       Type *BaseType = Elts[0]->getType();
3678       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3679       if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
3680         return error(
3681             ExplicitTypeLoc,
3682             typeComparisonErrorMessage(
3683                 "explicit pointee type doesn't match operand's pointee type",
3684                 Ty, BasePointerType->getNonOpaquePointerElementType()));
3685       }
3686 
3687       unsigned GEPWidth =
3688           BaseType->isVectorTy()
3689               ? cast<FixedVectorType>(BaseType)->getNumElements()
3690               : 0;
3691 
3692       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3693       for (Constant *Val : Indices) {
3694         Type *ValTy = Val->getType();
3695         if (!ValTy->isIntOrIntVectorTy())
3696           return error(ID.Loc, "getelementptr index must be an integer");
3697         if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3698           unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3699           if (GEPWidth && (ValNumEl != GEPWidth))
3700             return error(
3701                 ID.Loc,
3702                 "getelementptr vector index has a wrong number of elements");
3703           // GEPWidth may have been unknown because the base is a scalar,
3704           // but it is known now.
3705           GEPWidth = ValNumEl;
3706         }
3707       }
3708 
3709       SmallPtrSet<Type*, 4> Visited;
3710       if (!Indices.empty() && !Ty->isSized(&Visited))
3711         return error(ID.Loc, "base element of getelementptr must be sized");
3712 
3713       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3714         return error(ID.Loc, "invalid getelementptr indices");
3715 
3716       if (InRangeOp) {
3717         if (*InRangeOp == 0)
3718           return error(ID.Loc,
3719                        "inrange keyword may not appear on pointer operand");
3720         --*InRangeOp;
3721       }
3722 
3723       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3724                                                       InBounds, InRangeOp);
3725     } else if (Opc == Instruction::Select) {
3726       if (Elts.size() != 3)
3727         return error(ID.Loc, "expected three operands to select");
3728       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3729                                                               Elts[2]))
3730         return error(ID.Loc, Reason);
3731       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3732     } else if (Opc == Instruction::ShuffleVector) {
3733       if (Elts.size() != 3)
3734         return error(ID.Loc, "expected three operands to shufflevector");
3735       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3736         return error(ID.Loc, "invalid operands to shufflevector");
3737       SmallVector<int, 16> Mask;
3738       ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3739       ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3740     } else if (Opc == Instruction::ExtractElement) {
3741       if (Elts.size() != 2)
3742         return error(ID.Loc, "expected two operands to extractelement");
3743       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3744         return error(ID.Loc, "invalid extractelement operands");
3745       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3746     } else {
3747       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3748       if (Elts.size() != 3)
3749         return error(ID.Loc, "expected three operands to insertelement");
3750       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3751         return error(ID.Loc, "invalid insertelement operands");
3752       ID.ConstantVal =
3753                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3754     }
3755 
3756     ID.Kind = ValID::t_Constant;
3757     return false;
3758   }
3759   }
3760 
3761   Lex.Lex();
3762   return false;
3763 }
3764 
3765 /// parseGlobalValue - parse a global value with the specified type.
3766 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3767   C = nullptr;
3768   ValID ID;
3769   Value *V = nullptr;
3770   bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
3771                 convertValIDToValue(Ty, ID, V, nullptr);
3772   if (V && !(C = dyn_cast<Constant>(V)))
3773     return error(ID.Loc, "global values must be constants");
3774   return Parsed;
3775 }
3776 
3777 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3778   Type *Ty = nullptr;
3779   return parseType(Ty) || parseGlobalValue(Ty, V);
3780 }
3781 
3782 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3783   C = nullptr;
3784 
3785   LocTy KwLoc = Lex.getLoc();
3786   if (!EatIfPresent(lltok::kw_comdat))
3787     return false;
3788 
3789   if (EatIfPresent(lltok::lparen)) {
3790     if (Lex.getKind() != lltok::ComdatVar)
3791       return tokError("expected comdat variable");
3792     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3793     Lex.Lex();
3794     if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3795       return true;
3796   } else {
3797     if (GlobalName.empty())
3798       return tokError("comdat cannot be unnamed");
3799     C = getComdat(std::string(GlobalName), KwLoc);
3800   }
3801 
3802   return false;
3803 }
3804 
3805 /// parseGlobalValueVector
3806 ///   ::= /*empty*/
3807 ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3808 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3809                                       Optional<unsigned> *InRangeOp) {
3810   // Empty list.
3811   if (Lex.getKind() == lltok::rbrace ||
3812       Lex.getKind() == lltok::rsquare ||
3813       Lex.getKind() == lltok::greater ||
3814       Lex.getKind() == lltok::rparen)
3815     return false;
3816 
3817   do {
3818     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3819       *InRangeOp = Elts.size();
3820 
3821     Constant *C;
3822     if (parseGlobalTypeAndValue(C))
3823       return true;
3824     Elts.push_back(C);
3825   } while (EatIfPresent(lltok::comma));
3826 
3827   return false;
3828 }
3829 
3830 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3831   SmallVector<Metadata *, 16> Elts;
3832   if (parseMDNodeVector(Elts))
3833     return true;
3834 
3835   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3836   return false;
3837 }
3838 
3839 /// MDNode:
3840 ///  ::= !{ ... }
3841 ///  ::= !7
3842 ///  ::= !DILocation(...)
3843 bool LLParser::parseMDNode(MDNode *&N) {
3844   if (Lex.getKind() == lltok::MetadataVar)
3845     return parseSpecializedMDNode(N);
3846 
3847   return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3848 }
3849 
3850 bool LLParser::parseMDNodeTail(MDNode *&N) {
3851   // !{ ... }
3852   if (Lex.getKind() == lltok::lbrace)
3853     return parseMDTuple(N);
3854 
3855   // !42
3856   return parseMDNodeID(N);
3857 }
3858 
3859 namespace {
3860 
3861 /// Structure to represent an optional metadata field.
3862 template <class FieldTy> struct MDFieldImpl {
3863   typedef MDFieldImpl ImplTy;
3864   FieldTy Val;
3865   bool Seen;
3866 
3867   void assign(FieldTy Val) {
3868     Seen = true;
3869     this->Val = std::move(Val);
3870   }
3871 
3872   explicit MDFieldImpl(FieldTy Default)
3873       : Val(std::move(Default)), Seen(false) {}
3874 };
3875 
3876 /// Structure to represent an optional metadata field that
3877 /// can be of either type (A or B) and encapsulates the
3878 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3879 /// to reimplement the specifics for representing each Field.
3880 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3881   typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3882   FieldTypeA A;
3883   FieldTypeB B;
3884   bool Seen;
3885 
3886   enum {
3887     IsInvalid = 0,
3888     IsTypeA = 1,
3889     IsTypeB = 2
3890   } WhatIs;
3891 
3892   void assign(FieldTypeA A) {
3893     Seen = true;
3894     this->A = std::move(A);
3895     WhatIs = IsTypeA;
3896   }
3897 
3898   void assign(FieldTypeB B) {
3899     Seen = true;
3900     this->B = std::move(B);
3901     WhatIs = IsTypeB;
3902   }
3903 
3904   explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3905       : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3906         WhatIs(IsInvalid) {}
3907 };
3908 
3909 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3910   uint64_t Max;
3911 
3912   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3913       : ImplTy(Default), Max(Max) {}
3914 };
3915 
3916 struct LineField : public MDUnsignedField {
3917   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3918 };
3919 
3920 struct ColumnField : public MDUnsignedField {
3921   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3922 };
3923 
3924 struct DwarfTagField : public MDUnsignedField {
3925   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3926   DwarfTagField(dwarf::Tag DefaultTag)
3927       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3928 };
3929 
3930 struct DwarfMacinfoTypeField : public MDUnsignedField {
3931   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3932   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3933     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3934 };
3935 
3936 struct DwarfAttEncodingField : public MDUnsignedField {
3937   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3938 };
3939 
3940 struct DwarfVirtualityField : public MDUnsignedField {
3941   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3942 };
3943 
3944 struct DwarfLangField : public MDUnsignedField {
3945   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3946 };
3947 
3948 struct DwarfCCField : public MDUnsignedField {
3949   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3950 };
3951 
3952 struct EmissionKindField : public MDUnsignedField {
3953   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3954 };
3955 
3956 struct NameTableKindField : public MDUnsignedField {
3957   NameTableKindField()
3958       : MDUnsignedField(
3959             0, (unsigned)
3960                    DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3961 };
3962 
3963 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3964   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3965 };
3966 
3967 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3968   DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3969 };
3970 
3971 struct MDAPSIntField : public MDFieldImpl<APSInt> {
3972   MDAPSIntField() : ImplTy(APSInt()) {}
3973 };
3974 
3975 struct MDSignedField : public MDFieldImpl<int64_t> {
3976   int64_t Min = INT64_MIN;
3977   int64_t Max = INT64_MAX;
3978 
3979   MDSignedField(int64_t Default = 0)
3980       : ImplTy(Default) {}
3981   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3982       : ImplTy(Default), Min(Min), Max(Max) {}
3983 };
3984 
3985 struct MDBoolField : public MDFieldImpl<bool> {
3986   MDBoolField(bool Default = false) : ImplTy(Default) {}
3987 };
3988 
3989 struct MDField : public MDFieldImpl<Metadata *> {
3990   bool AllowNull;
3991 
3992   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3993 };
3994 
3995 struct MDStringField : public MDFieldImpl<MDString *> {
3996   bool AllowEmpty;
3997   MDStringField(bool AllowEmpty = true)
3998       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3999 };
4000 
4001 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4002   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4003 };
4004 
4005 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4006   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4007 };
4008 
4009 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4010   MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4011       : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4012 
4013   MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4014                     bool AllowNull = true)
4015       : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4016 
4017   bool isMDSignedField() const { return WhatIs == IsTypeA; }
4018   bool isMDField() const { return WhatIs == IsTypeB; }
4019   int64_t getMDSignedValue() const {
4020     assert(isMDSignedField() && "Wrong field type");
4021     return A.Val;
4022   }
4023   Metadata *getMDFieldValue() const {
4024     assert(isMDField() && "Wrong field type");
4025     return B.Val;
4026   }
4027 };
4028 
4029 } // end anonymous namespace
4030 
4031 namespace llvm {
4032 
4033 template <>
4034 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4035   if (Lex.getKind() != lltok::APSInt)
4036     return tokError("expected integer");
4037 
4038   Result.assign(Lex.getAPSIntVal());
4039   Lex.Lex();
4040   return false;
4041 }
4042 
4043 template <>
4044 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4045                             MDUnsignedField &Result) {
4046   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4047     return tokError("expected unsigned integer");
4048 
4049   auto &U = Lex.getAPSIntVal();
4050   if (U.ugt(Result.Max))
4051     return tokError("value for '" + Name + "' too large, limit is " +
4052                     Twine(Result.Max));
4053   Result.assign(U.getZExtValue());
4054   assert(Result.Val <= Result.Max && "Expected value in range");
4055   Lex.Lex();
4056   return false;
4057 }
4058 
4059 template <>
4060 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4061   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4062 }
4063 template <>
4064 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4065   return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4066 }
4067 
4068 template <>
4069 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4070   if (Lex.getKind() == lltok::APSInt)
4071     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4072 
4073   if (Lex.getKind() != lltok::DwarfTag)
4074     return tokError("expected DWARF tag");
4075 
4076   unsigned Tag = dwarf::getTag(Lex.getStrVal());
4077   if (Tag == dwarf::DW_TAG_invalid)
4078     return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4079   assert(Tag <= Result.Max && "Expected valid DWARF tag");
4080 
4081   Result.assign(Tag);
4082   Lex.Lex();
4083   return false;
4084 }
4085 
4086 template <>
4087 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4088                             DwarfMacinfoTypeField &Result) {
4089   if (Lex.getKind() == lltok::APSInt)
4090     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4091 
4092   if (Lex.getKind() != lltok::DwarfMacinfo)
4093     return tokError("expected DWARF macinfo type");
4094 
4095   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4096   if (Macinfo == dwarf::DW_MACINFO_invalid)
4097     return tokError("invalid DWARF macinfo type" + Twine(" '") +
4098                     Lex.getStrVal() + "'");
4099   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4100 
4101   Result.assign(Macinfo);
4102   Lex.Lex();
4103   return false;
4104 }
4105 
4106 template <>
4107 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4108                             DwarfVirtualityField &Result) {
4109   if (Lex.getKind() == lltok::APSInt)
4110     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4111 
4112   if (Lex.getKind() != lltok::DwarfVirtuality)
4113     return tokError("expected DWARF virtuality code");
4114 
4115   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4116   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4117     return tokError("invalid DWARF virtuality code" + Twine(" '") +
4118                     Lex.getStrVal() + "'");
4119   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4120   Result.assign(Virtuality);
4121   Lex.Lex();
4122   return false;
4123 }
4124 
4125 template <>
4126 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4127   if (Lex.getKind() == lltok::APSInt)
4128     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4129 
4130   if (Lex.getKind() != lltok::DwarfLang)
4131     return tokError("expected DWARF language");
4132 
4133   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4134   if (!Lang)
4135     return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4136                     "'");
4137   assert(Lang <= Result.Max && "Expected valid DWARF language");
4138   Result.assign(Lang);
4139   Lex.Lex();
4140   return false;
4141 }
4142 
4143 template <>
4144 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4145   if (Lex.getKind() == lltok::APSInt)
4146     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4147 
4148   if (Lex.getKind() != lltok::DwarfCC)
4149     return tokError("expected DWARF calling convention");
4150 
4151   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4152   if (!CC)
4153     return tokError("invalid DWARF calling convention" + Twine(" '") +
4154                     Lex.getStrVal() + "'");
4155   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4156   Result.assign(CC);
4157   Lex.Lex();
4158   return false;
4159 }
4160 
4161 template <>
4162 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4163                             EmissionKindField &Result) {
4164   if (Lex.getKind() == lltok::APSInt)
4165     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4166 
4167   if (Lex.getKind() != lltok::EmissionKind)
4168     return tokError("expected emission kind");
4169 
4170   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4171   if (!Kind)
4172     return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4173                     "'");
4174   assert(*Kind <= Result.Max && "Expected valid emission kind");
4175   Result.assign(*Kind);
4176   Lex.Lex();
4177   return false;
4178 }
4179 
4180 template <>
4181 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4182                             NameTableKindField &Result) {
4183   if (Lex.getKind() == lltok::APSInt)
4184     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4185 
4186   if (Lex.getKind() != lltok::NameTableKind)
4187     return tokError("expected nameTable kind");
4188 
4189   auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4190   if (!Kind)
4191     return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4192                     "'");
4193   assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4194   Result.assign((unsigned)*Kind);
4195   Lex.Lex();
4196   return false;
4197 }
4198 
4199 template <>
4200 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4201                             DwarfAttEncodingField &Result) {
4202   if (Lex.getKind() == lltok::APSInt)
4203     return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4204 
4205   if (Lex.getKind() != lltok::DwarfAttEncoding)
4206     return tokError("expected DWARF type attribute encoding");
4207 
4208   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4209   if (!Encoding)
4210     return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4211                     Lex.getStrVal() + "'");
4212   assert(Encoding <= Result.Max && "Expected valid DWARF language");
4213   Result.assign(Encoding);
4214   Lex.Lex();
4215   return false;
4216 }
4217 
4218 /// DIFlagField
4219 ///  ::= uint32
4220 ///  ::= DIFlagVector
4221 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4222 template <>
4223 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4224 
4225   // parser for a single flag.
4226   auto parseFlag = [&](DINode::DIFlags &Val) {
4227     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4228       uint32_t TempVal = static_cast<uint32_t>(Val);
4229       bool Res = parseUInt32(TempVal);
4230       Val = static_cast<DINode::DIFlags>(TempVal);
4231       return Res;
4232     }
4233 
4234     if (Lex.getKind() != lltok::DIFlag)
4235       return tokError("expected debug info flag");
4236 
4237     Val = DINode::getFlag(Lex.getStrVal());
4238     if (!Val)
4239       return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4240                       "'");
4241     Lex.Lex();
4242     return false;
4243   };
4244 
4245   // parse the flags and combine them together.
4246   DINode::DIFlags Combined = DINode::FlagZero;
4247   do {
4248     DINode::DIFlags Val;
4249     if (parseFlag(Val))
4250       return true;
4251     Combined |= Val;
4252   } while (EatIfPresent(lltok::bar));
4253 
4254   Result.assign(Combined);
4255   return false;
4256 }
4257 
4258 /// DISPFlagField
4259 ///  ::= uint32
4260 ///  ::= DISPFlagVector
4261 ///  ::= DISPFlagVector '|' DISPFlag* '|' uint32
4262 template <>
4263 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4264 
4265   // parser for a single flag.
4266   auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4267     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4268       uint32_t TempVal = static_cast<uint32_t>(Val);
4269       bool Res = parseUInt32(TempVal);
4270       Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4271       return Res;
4272     }
4273 
4274     if (Lex.getKind() != lltok::DISPFlag)
4275       return tokError("expected debug info flag");
4276 
4277     Val = DISubprogram::getFlag(Lex.getStrVal());
4278     if (!Val)
4279       return tokError(Twine("invalid subprogram debug info flag '") +
4280                       Lex.getStrVal() + "'");
4281     Lex.Lex();
4282     return false;
4283   };
4284 
4285   // parse the flags and combine them together.
4286   DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4287   do {
4288     DISubprogram::DISPFlags Val;
4289     if (parseFlag(Val))
4290       return true;
4291     Combined |= Val;
4292   } while (EatIfPresent(lltok::bar));
4293 
4294   Result.assign(Combined);
4295   return false;
4296 }
4297 
4298 template <>
4299 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4300   if (Lex.getKind() != lltok::APSInt)
4301     return tokError("expected signed integer");
4302 
4303   auto &S = Lex.getAPSIntVal();
4304   if (S < Result.Min)
4305     return tokError("value for '" + Name + "' too small, limit is " +
4306                     Twine(Result.Min));
4307   if (S > Result.Max)
4308     return tokError("value for '" + Name + "' too large, limit is " +
4309                     Twine(Result.Max));
4310   Result.assign(S.getExtValue());
4311   assert(Result.Val >= Result.Min && "Expected value in range");
4312   assert(Result.Val <= Result.Max && "Expected value in range");
4313   Lex.Lex();
4314   return false;
4315 }
4316 
4317 template <>
4318 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4319   switch (Lex.getKind()) {
4320   default:
4321     return tokError("expected 'true' or 'false'");
4322   case lltok::kw_true:
4323     Result.assign(true);
4324     break;
4325   case lltok::kw_false:
4326     Result.assign(false);
4327     break;
4328   }
4329   Lex.Lex();
4330   return false;
4331 }
4332 
4333 template <>
4334 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4335   if (Lex.getKind() == lltok::kw_null) {
4336     if (!Result.AllowNull)
4337       return tokError("'" + Name + "' cannot be null");
4338     Lex.Lex();
4339     Result.assign(nullptr);
4340     return false;
4341   }
4342 
4343   Metadata *MD;
4344   if (parseMetadata(MD, nullptr))
4345     return true;
4346 
4347   Result.assign(MD);
4348   return false;
4349 }
4350 
4351 template <>
4352 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4353                             MDSignedOrMDField &Result) {
4354   // Try to parse a signed int.
4355   if (Lex.getKind() == lltok::APSInt) {
4356     MDSignedField Res = Result.A;
4357     if (!parseMDField(Loc, Name, Res)) {
4358       Result.assign(Res);
4359       return false;
4360     }
4361     return true;
4362   }
4363 
4364   // Otherwise, try to parse as an MDField.
4365   MDField Res = Result.B;
4366   if (!parseMDField(Loc, Name, Res)) {
4367     Result.assign(Res);
4368     return false;
4369   }
4370 
4371   return true;
4372 }
4373 
4374 template <>
4375 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4376   LocTy ValueLoc = Lex.getLoc();
4377   std::string S;
4378   if (parseStringConstant(S))
4379     return true;
4380 
4381   if (!Result.AllowEmpty && S.empty())
4382     return error(ValueLoc, "'" + Name + "' cannot be empty");
4383 
4384   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4385   return false;
4386 }
4387 
4388 template <>
4389 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4390   SmallVector<Metadata *, 4> MDs;
4391   if (parseMDNodeVector(MDs))
4392     return true;
4393 
4394   Result.assign(std::move(MDs));
4395   return false;
4396 }
4397 
4398 template <>
4399 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4400                             ChecksumKindField &Result) {
4401   Optional<DIFile::ChecksumKind> CSKind =
4402       DIFile::getChecksumKind(Lex.getStrVal());
4403 
4404   if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4405     return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4406                     "'");
4407 
4408   Result.assign(*CSKind);
4409   Lex.Lex();
4410   return false;
4411 }
4412 
4413 } // end namespace llvm
4414 
4415 template <class ParserTy>
4416 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4417   do {
4418     if (Lex.getKind() != lltok::LabelStr)
4419       return tokError("expected field label here");
4420 
4421     if (ParseField())
4422       return true;
4423   } while (EatIfPresent(lltok::comma));
4424 
4425   return false;
4426 }
4427 
4428 template <class ParserTy>
4429 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4430   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4431   Lex.Lex();
4432 
4433   if (parseToken(lltok::lparen, "expected '(' here"))
4434     return true;
4435   if (Lex.getKind() != lltok::rparen)
4436     if (parseMDFieldsImplBody(ParseField))
4437       return true;
4438 
4439   ClosingLoc = Lex.getLoc();
4440   return parseToken(lltok::rparen, "expected ')' here");
4441 }
4442 
4443 template <class FieldTy>
4444 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4445   if (Result.Seen)
4446     return tokError("field '" + Name + "' cannot be specified more than once");
4447 
4448   LocTy Loc = Lex.getLoc();
4449   Lex.Lex();
4450   return parseMDField(Loc, Name, Result);
4451 }
4452 
4453 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4454   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4455 
4456 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
4457   if (Lex.getStrVal() == #CLASS)                                               \
4458     return parse##CLASS(N, IsDistinct);
4459 #include "llvm/IR/Metadata.def"
4460 
4461   return tokError("expected metadata type");
4462 }
4463 
4464 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4465 #define NOP_FIELD(NAME, TYPE, INIT)
4466 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
4467   if (!NAME.Seen)                                                              \
4468     return error(ClosingLoc, "missing required field '" #NAME "'");
4469 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
4470   if (Lex.getStrVal() == #NAME)                                                \
4471     return parseMDField(#NAME, NAME);
4472 #define PARSE_MD_FIELDS()                                                      \
4473   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
4474   do {                                                                         \
4475     LocTy ClosingLoc;                                                          \
4476     if (parseMDFieldsImpl(                                                     \
4477             [&]() -> bool {                                                    \
4478               VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                  \
4479               return tokError(Twine("invalid field '") + Lex.getStrVal() +     \
4480                               "'");                                            \
4481             },                                                                 \
4482             ClosingLoc))                                                       \
4483       return true;                                                             \
4484     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
4485   } while (false)
4486 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
4487   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4488 
4489 /// parseDILocationFields:
4490 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4491 ///   isImplicitCode: true)
4492 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4493 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4494   OPTIONAL(line, LineField, );                                                 \
4495   OPTIONAL(column, ColumnField, );                                             \
4496   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4497   OPTIONAL(inlinedAt, MDField, );                                              \
4498   OPTIONAL(isImplicitCode, MDBoolField, (false));
4499   PARSE_MD_FIELDS();
4500 #undef VISIT_MD_FIELDS
4501 
4502   Result =
4503       GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4504                                    inlinedAt.Val, isImplicitCode.Val));
4505   return false;
4506 }
4507 
4508 /// parseGenericDINode:
4509 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4510 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4511 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4512   REQUIRED(tag, DwarfTagField, );                                              \
4513   OPTIONAL(header, MDStringField, );                                           \
4514   OPTIONAL(operands, MDFieldList, );
4515   PARSE_MD_FIELDS();
4516 #undef VISIT_MD_FIELDS
4517 
4518   Result = GET_OR_DISTINCT(GenericDINode,
4519                            (Context, tag.Val, header.Val, operands.Val));
4520   return false;
4521 }
4522 
4523 /// parseDISubrange:
4524 ///   ::= !DISubrange(count: 30, lowerBound: 2)
4525 ///   ::= !DISubrange(count: !node, lowerBound: 2)
4526 ///   ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4527 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4528 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4529   OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false));              \
4530   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4531   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4532   OPTIONAL(stride, MDSignedOrMDField, );
4533   PARSE_MD_FIELDS();
4534 #undef VISIT_MD_FIELDS
4535 
4536   Metadata *Count = nullptr;
4537   Metadata *LowerBound = nullptr;
4538   Metadata *UpperBound = nullptr;
4539   Metadata *Stride = nullptr;
4540 
4541   auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4542     if (Bound.isMDSignedField())
4543       return ConstantAsMetadata::get(ConstantInt::getSigned(
4544           Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4545     if (Bound.isMDField())
4546       return Bound.getMDFieldValue();
4547     return nullptr;
4548   };
4549 
4550   Count = convToMetadata(count);
4551   LowerBound = convToMetadata(lowerBound);
4552   UpperBound = convToMetadata(upperBound);
4553   Stride = convToMetadata(stride);
4554 
4555   Result = GET_OR_DISTINCT(DISubrange,
4556                            (Context, Count, LowerBound, UpperBound, Stride));
4557 
4558   return false;
4559 }
4560 
4561 /// parseDIGenericSubrange:
4562 ///   ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4563 ///   !node3)
4564 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4565 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4566   OPTIONAL(count, MDSignedOrMDField, );                                        \
4567   OPTIONAL(lowerBound, MDSignedOrMDField, );                                   \
4568   OPTIONAL(upperBound, MDSignedOrMDField, );                                   \
4569   OPTIONAL(stride, MDSignedOrMDField, );
4570   PARSE_MD_FIELDS();
4571 #undef VISIT_MD_FIELDS
4572 
4573   auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4574     if (Bound.isMDSignedField())
4575       return DIExpression::get(
4576           Context, {dwarf::DW_OP_consts,
4577                     static_cast<uint64_t>(Bound.getMDSignedValue())});
4578     if (Bound.isMDField())
4579       return Bound.getMDFieldValue();
4580     return nullptr;
4581   };
4582 
4583   Metadata *Count = ConvToMetadata(count);
4584   Metadata *LowerBound = ConvToMetadata(lowerBound);
4585   Metadata *UpperBound = ConvToMetadata(upperBound);
4586   Metadata *Stride = ConvToMetadata(stride);
4587 
4588   Result = GET_OR_DISTINCT(DIGenericSubrange,
4589                            (Context, Count, LowerBound, UpperBound, Stride));
4590 
4591   return false;
4592 }
4593 
4594 /// parseDIEnumerator:
4595 ///   ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4596 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4597 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4598   REQUIRED(name, MDStringField, );                                             \
4599   REQUIRED(value, MDAPSIntField, );                                            \
4600   OPTIONAL(isUnsigned, MDBoolField, (false));
4601   PARSE_MD_FIELDS();
4602 #undef VISIT_MD_FIELDS
4603 
4604   if (isUnsigned.Val && value.Val.isNegative())
4605     return tokError("unsigned enumerator with negative value");
4606 
4607   APSInt Value(value.Val);
4608   // Add a leading zero so that unsigned values with the msb set are not
4609   // mistaken for negative values when used for signed enumerators.
4610   if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4611     Value = Value.zext(Value.getBitWidth() + 1);
4612 
4613   Result =
4614       GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4615 
4616   return false;
4617 }
4618 
4619 /// parseDIBasicType:
4620 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4621 ///                    encoding: DW_ATE_encoding, flags: 0)
4622 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4623 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4624   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
4625   OPTIONAL(name, MDStringField, );                                             \
4626   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4627   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4628   OPTIONAL(encoding, DwarfAttEncodingField, );                                 \
4629   OPTIONAL(flags, DIFlagField, );
4630   PARSE_MD_FIELDS();
4631 #undef VISIT_MD_FIELDS
4632 
4633   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4634                                          align.Val, encoding.Val, flags.Val));
4635   return false;
4636 }
4637 
4638 /// parseDIStringType:
4639 ///   ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4640 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4641 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4642   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type));                   \
4643   OPTIONAL(name, MDStringField, );                                             \
4644   OPTIONAL(stringLength, MDField, );                                           \
4645   OPTIONAL(stringLengthExpression, MDField, );                                 \
4646   OPTIONAL(stringLocationExpression, MDField, );                               \
4647   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4648   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4649   OPTIONAL(encoding, DwarfAttEncodingField, );
4650   PARSE_MD_FIELDS();
4651 #undef VISIT_MD_FIELDS
4652 
4653   Result = GET_OR_DISTINCT(
4654       DIStringType,
4655       (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
4656        stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
4657   return false;
4658 }
4659 
4660 /// parseDIDerivedType:
4661 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4662 ///                      line: 7, scope: !1, baseType: !2, size: 32,
4663 ///                      align: 32, offset: 0, flags: 0, extraData: !3,
4664 ///                      dwarfAddressSpace: 3)
4665 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4666 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4667   REQUIRED(tag, DwarfTagField, );                                              \
4668   OPTIONAL(name, MDStringField, );                                             \
4669   OPTIONAL(file, MDField, );                                                   \
4670   OPTIONAL(line, LineField, );                                                 \
4671   OPTIONAL(scope, MDField, );                                                  \
4672   REQUIRED(baseType, MDField, );                                               \
4673   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4674   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4675   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4676   OPTIONAL(flags, DIFlagField, );                                              \
4677   OPTIONAL(extraData, MDField, );                                              \
4678   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));      \
4679   OPTIONAL(annotations, MDField, );
4680   PARSE_MD_FIELDS();
4681 #undef VISIT_MD_FIELDS
4682 
4683   Optional<unsigned> DWARFAddressSpace;
4684   if (dwarfAddressSpace.Val != UINT32_MAX)
4685     DWARFAddressSpace = dwarfAddressSpace.Val;
4686 
4687   Result = GET_OR_DISTINCT(DIDerivedType,
4688                            (Context, tag.Val, name.Val, file.Val, line.Val,
4689                             scope.Val, baseType.Val, size.Val, align.Val,
4690                             offset.Val, DWARFAddressSpace, flags.Val,
4691                             extraData.Val, annotations.Val));
4692   return false;
4693 }
4694 
4695 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4696 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4697   REQUIRED(tag, DwarfTagField, );                                              \
4698   OPTIONAL(name, MDStringField, );                                             \
4699   OPTIONAL(file, MDField, );                                                   \
4700   OPTIONAL(line, LineField, );                                                 \
4701   OPTIONAL(scope, MDField, );                                                  \
4702   OPTIONAL(baseType, MDField, );                                               \
4703   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
4704   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
4705   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
4706   OPTIONAL(flags, DIFlagField, );                                              \
4707   OPTIONAL(elements, MDField, );                                               \
4708   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
4709   OPTIONAL(vtableHolder, MDField, );                                           \
4710   OPTIONAL(templateParams, MDField, );                                         \
4711   OPTIONAL(identifier, MDStringField, );                                       \
4712   OPTIONAL(discriminator, MDField, );                                          \
4713   OPTIONAL(dataLocation, MDField, );                                           \
4714   OPTIONAL(associated, MDField, );                                             \
4715   OPTIONAL(allocated, MDField, );                                              \
4716   OPTIONAL(rank, MDSignedOrMDField, );                                         \
4717   OPTIONAL(annotations, MDField, );
4718   PARSE_MD_FIELDS();
4719 #undef VISIT_MD_FIELDS
4720 
4721   Metadata *Rank = nullptr;
4722   if (rank.isMDSignedField())
4723     Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4724         Type::getInt64Ty(Context), rank.getMDSignedValue()));
4725   else if (rank.isMDField())
4726     Rank = rank.getMDFieldValue();
4727 
4728   // If this has an identifier try to build an ODR type.
4729   if (identifier.Val)
4730     if (auto *CT = DICompositeType::buildODRType(
4731             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4732             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4733             elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4734             discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4735             Rank, annotations.Val)) {
4736       Result = CT;
4737       return false;
4738     }
4739 
4740   // Create a new node, and save it in the context if it belongs in the type
4741   // map.
4742   Result = GET_OR_DISTINCT(
4743       DICompositeType,
4744       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4745        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4746        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4747        discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
4748        annotations.Val));
4749   return false;
4750 }
4751 
4752 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4753 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4754   OPTIONAL(flags, DIFlagField, );                                              \
4755   OPTIONAL(cc, DwarfCCField, );                                                \
4756   REQUIRED(types, MDField, );
4757   PARSE_MD_FIELDS();
4758 #undef VISIT_MD_FIELDS
4759 
4760   Result = GET_OR_DISTINCT(DISubroutineType,
4761                            (Context, flags.Val, cc.Val, types.Val));
4762   return false;
4763 }
4764 
4765 /// parseDIFileType:
4766 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4767 ///                   checksumkind: CSK_MD5,
4768 ///                   checksum: "000102030405060708090a0b0c0d0e0f",
4769 ///                   source: "source file contents")
4770 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4771   // The default constructed value for checksumkind is required, but will never
4772   // be used, as the parser checks if the field was actually Seen before using
4773   // the Val.
4774 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4775   REQUIRED(filename, MDStringField, );                                         \
4776   REQUIRED(directory, MDStringField, );                                        \
4777   OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5));                \
4778   OPTIONAL(checksum, MDStringField, );                                         \
4779   OPTIONAL(source, MDStringField, );
4780   PARSE_MD_FIELDS();
4781 #undef VISIT_MD_FIELDS
4782 
4783   Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4784   if (checksumkind.Seen && checksum.Seen)
4785     OptChecksum.emplace(checksumkind.Val, checksum.Val);
4786   else if (checksumkind.Seen || checksum.Seen)
4787     return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4788 
4789   Optional<MDString *> OptSource;
4790   if (source.Seen)
4791     OptSource = source.Val;
4792   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4793                                     OptChecksum, OptSource));
4794   return false;
4795 }
4796 
4797 /// parseDICompileUnit:
4798 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4799 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
4800 ///                      splitDebugFilename: "abc.debug",
4801 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4802 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4803 ///                      sysroot: "/", sdk: "MacOSX.sdk")
4804 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4805   if (!IsDistinct)
4806     return Lex.Error("missing 'distinct', required for !DICompileUnit");
4807 
4808 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4809   REQUIRED(language, DwarfLangField, );                                        \
4810   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
4811   OPTIONAL(producer, MDStringField, );                                         \
4812   OPTIONAL(isOptimized, MDBoolField, );                                        \
4813   OPTIONAL(flags, MDStringField, );                                            \
4814   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
4815   OPTIONAL(splitDebugFilename, MDStringField, );                               \
4816   OPTIONAL(emissionKind, EmissionKindField, );                                 \
4817   OPTIONAL(enums, MDField, );                                                  \
4818   OPTIONAL(retainedTypes, MDField, );                                          \
4819   OPTIONAL(globals, MDField, );                                                \
4820   OPTIONAL(imports, MDField, );                                                \
4821   OPTIONAL(macros, MDField, );                                                 \
4822   OPTIONAL(dwoId, MDUnsignedField, );                                          \
4823   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
4824   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);                       \
4825   OPTIONAL(nameTableKind, NameTableKindField, );                               \
4826   OPTIONAL(rangesBaseAddress, MDBoolField, = false);                           \
4827   OPTIONAL(sysroot, MDStringField, );                                          \
4828   OPTIONAL(sdk, MDStringField, );
4829   PARSE_MD_FIELDS();
4830 #undef VISIT_MD_FIELDS
4831 
4832   Result = DICompileUnit::getDistinct(
4833       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4834       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4835       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4836       splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4837       rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4838   return false;
4839 }
4840 
4841 /// parseDISubprogram:
4842 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4843 ///                     file: !1, line: 7, type: !2, isLocal: false,
4844 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
4845 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
4846 ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
4847 ///                     spFlags: 10, isOptimized: false, templateParams: !4,
4848 ///                     declaration: !5, retainedNodes: !6, thrownTypes: !7,
4849 ///                     annotations: !8)
4850 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4851   auto Loc = Lex.getLoc();
4852 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4853   OPTIONAL(scope, MDField, );                                                  \
4854   OPTIONAL(name, MDStringField, );                                             \
4855   OPTIONAL(linkageName, MDStringField, );                                      \
4856   OPTIONAL(file, MDField, );                                                   \
4857   OPTIONAL(line, LineField, );                                                 \
4858   OPTIONAL(type, MDField, );                                                   \
4859   OPTIONAL(isLocal, MDBoolField, );                                            \
4860   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4861   OPTIONAL(scopeLine, LineField, );                                            \
4862   OPTIONAL(containingType, MDField, );                                         \
4863   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
4864   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
4865   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
4866   OPTIONAL(flags, DIFlagField, );                                              \
4867   OPTIONAL(spFlags, DISPFlagField, );                                          \
4868   OPTIONAL(isOptimized, MDBoolField, );                                        \
4869   OPTIONAL(unit, MDField, );                                                   \
4870   OPTIONAL(templateParams, MDField, );                                         \
4871   OPTIONAL(declaration, MDField, );                                            \
4872   OPTIONAL(retainedNodes, MDField, );                                          \
4873   OPTIONAL(thrownTypes, MDField, );                                            \
4874   OPTIONAL(annotations, MDField, );                                            \
4875   OPTIONAL(targetFuncName, MDStringField, );
4876   PARSE_MD_FIELDS();
4877 #undef VISIT_MD_FIELDS
4878 
4879   // An explicit spFlags field takes precedence over individual fields in
4880   // older IR versions.
4881   DISubprogram::DISPFlags SPFlags =
4882       spFlags.Seen ? spFlags.Val
4883                    : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4884                                              isOptimized.Val, virtuality.Val);
4885   if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4886     return Lex.Error(
4887         Loc,
4888         "missing 'distinct', required for !DISubprogram that is a Definition");
4889   Result = GET_OR_DISTINCT(
4890       DISubprogram,
4891       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4892        type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4893        thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4894        declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
4895        targetFuncName.Val));
4896   return false;
4897 }
4898 
4899 /// parseDILexicalBlock:
4900 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4901 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4902 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4903   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4904   OPTIONAL(file, MDField, );                                                   \
4905   OPTIONAL(line, LineField, );                                                 \
4906   OPTIONAL(column, ColumnField, );
4907   PARSE_MD_FIELDS();
4908 #undef VISIT_MD_FIELDS
4909 
4910   Result = GET_OR_DISTINCT(
4911       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4912   return false;
4913 }
4914 
4915 /// parseDILexicalBlockFile:
4916 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4917 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4918 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4919   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4920   OPTIONAL(file, MDField, );                                                   \
4921   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4922   PARSE_MD_FIELDS();
4923 #undef VISIT_MD_FIELDS
4924 
4925   Result = GET_OR_DISTINCT(DILexicalBlockFile,
4926                            (Context, scope.Val, file.Val, discriminator.Val));
4927   return false;
4928 }
4929 
4930 /// parseDICommonBlock:
4931 ///   ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4932 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4933 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4934   REQUIRED(scope, MDField, );                                                  \
4935   OPTIONAL(declaration, MDField, );                                            \
4936   OPTIONAL(name, MDStringField, );                                             \
4937   OPTIONAL(file, MDField, );                                                   \
4938   OPTIONAL(line, LineField, );
4939   PARSE_MD_FIELDS();
4940 #undef VISIT_MD_FIELDS
4941 
4942   Result = GET_OR_DISTINCT(DICommonBlock,
4943                            (Context, scope.Val, declaration.Val, name.Val,
4944                             file.Val, line.Val));
4945   return false;
4946 }
4947 
4948 /// parseDINamespace:
4949 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4950 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
4951 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4952   REQUIRED(scope, MDField, );                                                  \
4953   OPTIONAL(name, MDStringField, );                                             \
4954   OPTIONAL(exportSymbols, MDBoolField, );
4955   PARSE_MD_FIELDS();
4956 #undef VISIT_MD_FIELDS
4957 
4958   Result = GET_OR_DISTINCT(DINamespace,
4959                            (Context, scope.Val, name.Val, exportSymbols.Val));
4960   return false;
4961 }
4962 
4963 /// parseDIMacro:
4964 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
4965 ///   "SomeValue")
4966 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
4967 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4968   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
4969   OPTIONAL(line, LineField, );                                                 \
4970   REQUIRED(name, MDStringField, );                                             \
4971   OPTIONAL(value, MDStringField, );
4972   PARSE_MD_FIELDS();
4973 #undef VISIT_MD_FIELDS
4974 
4975   Result = GET_OR_DISTINCT(DIMacro,
4976                            (Context, type.Val, line.Val, name.Val, value.Val));
4977   return false;
4978 }
4979 
4980 /// parseDIMacroFile:
4981 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4982 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4983 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4984   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
4985   OPTIONAL(line, LineField, );                                                 \
4986   REQUIRED(file, MDField, );                                                   \
4987   OPTIONAL(nodes, MDField, );
4988   PARSE_MD_FIELDS();
4989 #undef VISIT_MD_FIELDS
4990 
4991   Result = GET_OR_DISTINCT(DIMacroFile,
4992                            (Context, type.Val, line.Val, file.Val, nodes.Val));
4993   return false;
4994 }
4995 
4996 /// parseDIModule:
4997 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
4998 ///   "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
4999 ///   file: !1, line: 4, isDecl: false)
5000 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5001 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5002   REQUIRED(scope, MDField, );                                                  \
5003   REQUIRED(name, MDStringField, );                                             \
5004   OPTIONAL(configMacros, MDStringField, );                                     \
5005   OPTIONAL(includePath, MDStringField, );                                      \
5006   OPTIONAL(apinotes, MDStringField, );                                         \
5007   OPTIONAL(file, MDField, );                                                   \
5008   OPTIONAL(line, LineField, );                                                 \
5009   OPTIONAL(isDecl, MDBoolField, );
5010   PARSE_MD_FIELDS();
5011 #undef VISIT_MD_FIELDS
5012 
5013   Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5014                                       configMacros.Val, includePath.Val,
5015                                       apinotes.Val, line.Val, isDecl.Val));
5016   return false;
5017 }
5018 
5019 /// parseDITemplateTypeParameter:
5020 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5021 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5022 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5023   OPTIONAL(name, MDStringField, );                                             \
5024   REQUIRED(type, MDField, );                                                   \
5025   OPTIONAL(defaulted, MDBoolField, );
5026   PARSE_MD_FIELDS();
5027 #undef VISIT_MD_FIELDS
5028 
5029   Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5030                            (Context, name.Val, type.Val, defaulted.Val));
5031   return false;
5032 }
5033 
5034 /// parseDITemplateValueParameter:
5035 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5036 ///                                 name: "V", type: !1, defaulted: false,
5037 ///                                 value: i32 7)
5038 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5039 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5040   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
5041   OPTIONAL(name, MDStringField, );                                             \
5042   OPTIONAL(type, MDField, );                                                   \
5043   OPTIONAL(defaulted, MDBoolField, );                                          \
5044   REQUIRED(value, MDField, );
5045 
5046   PARSE_MD_FIELDS();
5047 #undef VISIT_MD_FIELDS
5048 
5049   Result = GET_OR_DISTINCT(
5050       DITemplateValueParameter,
5051       (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5052   return false;
5053 }
5054 
5055 /// parseDIGlobalVariable:
5056 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5057 ///                         file: !1, line: 7, type: !2, isLocal: false,
5058 ///                         isDefinition: true, templateParams: !3,
5059 ///                         declaration: !4, align: 8)
5060 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5061 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5062   OPTIONAL(name, MDStringField, (/* AllowEmpty */ false));                     \
5063   OPTIONAL(scope, MDField, );                                                  \
5064   OPTIONAL(linkageName, MDStringField, );                                      \
5065   OPTIONAL(file, MDField, );                                                   \
5066   OPTIONAL(line, LineField, );                                                 \
5067   OPTIONAL(type, MDField, );                                                   \
5068   OPTIONAL(isLocal, MDBoolField, );                                            \
5069   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
5070   OPTIONAL(templateParams, MDField, );                                         \
5071   OPTIONAL(declaration, MDField, );                                            \
5072   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5073   OPTIONAL(annotations, MDField, );
5074   PARSE_MD_FIELDS();
5075 #undef VISIT_MD_FIELDS
5076 
5077   Result =
5078       GET_OR_DISTINCT(DIGlobalVariable,
5079                       (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5080                        line.Val, type.Val, isLocal.Val, isDefinition.Val,
5081                        declaration.Val, templateParams.Val, align.Val,
5082                        annotations.Val));
5083   return false;
5084 }
5085 
5086 /// parseDILocalVariable:
5087 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5088 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5089 ///                        align: 8)
5090 ///   ::= !DILocalVariable(scope: !0, name: "foo",
5091 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
5092 ///                        align: 8)
5093 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5094 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5095   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5096   OPTIONAL(name, MDStringField, );                                             \
5097   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
5098   OPTIONAL(file, MDField, );                                                   \
5099   OPTIONAL(line, LineField, );                                                 \
5100   OPTIONAL(type, MDField, );                                                   \
5101   OPTIONAL(flags, DIFlagField, );                                              \
5102   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
5103   OPTIONAL(annotations, MDField, );
5104   PARSE_MD_FIELDS();
5105 #undef VISIT_MD_FIELDS
5106 
5107   Result = GET_OR_DISTINCT(DILocalVariable,
5108                            (Context, scope.Val, name.Val, file.Val, line.Val,
5109                             type.Val, arg.Val, flags.Val, align.Val,
5110                             annotations.Val));
5111   return false;
5112 }
5113 
5114 /// parseDILabel:
5115 ///   ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5116 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5117 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5118   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
5119   REQUIRED(name, MDStringField, );                                             \
5120   REQUIRED(file, MDField, );                                                   \
5121   REQUIRED(line, LineField, );
5122   PARSE_MD_FIELDS();
5123 #undef VISIT_MD_FIELDS
5124 
5125   Result = GET_OR_DISTINCT(DILabel,
5126                            (Context, scope.Val, name.Val, file.Val, line.Val));
5127   return false;
5128 }
5129 
5130 /// parseDIExpression:
5131 ///   ::= !DIExpression(0, 7, -1)
5132 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5133   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5134   Lex.Lex();
5135 
5136   if (parseToken(lltok::lparen, "expected '(' here"))
5137     return true;
5138 
5139   SmallVector<uint64_t, 8> Elements;
5140   if (Lex.getKind() != lltok::rparen)
5141     do {
5142       if (Lex.getKind() == lltok::DwarfOp) {
5143         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5144           Lex.Lex();
5145           Elements.push_back(Op);
5146           continue;
5147         }
5148         return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5149       }
5150 
5151       if (Lex.getKind() == lltok::DwarfAttEncoding) {
5152         if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5153           Lex.Lex();
5154           Elements.push_back(Op);
5155           continue;
5156         }
5157         return tokError(Twine("invalid DWARF attribute encoding '") +
5158                         Lex.getStrVal() + "'");
5159       }
5160 
5161       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5162         return tokError("expected unsigned integer");
5163 
5164       auto &U = Lex.getAPSIntVal();
5165       if (U.ugt(UINT64_MAX))
5166         return tokError("element too large, limit is " + Twine(UINT64_MAX));
5167       Elements.push_back(U.getZExtValue());
5168       Lex.Lex();
5169     } while (EatIfPresent(lltok::comma));
5170 
5171   if (parseToken(lltok::rparen, "expected ')' here"))
5172     return true;
5173 
5174   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5175   return false;
5176 }
5177 
5178 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5179   return parseDIArgList(Result, IsDistinct, nullptr);
5180 }
5181 /// ParseDIArgList:
5182 ///   ::= !DIArgList(i32 7, i64 %0)
5183 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5184                               PerFunctionState *PFS) {
5185   assert(PFS && "Expected valid function state");
5186   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5187   Lex.Lex();
5188 
5189   if (parseToken(lltok::lparen, "expected '(' here"))
5190     return true;
5191 
5192   SmallVector<ValueAsMetadata *, 4> Args;
5193   if (Lex.getKind() != lltok::rparen)
5194     do {
5195       Metadata *MD;
5196       if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5197         return true;
5198       Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5199     } while (EatIfPresent(lltok::comma));
5200 
5201   if (parseToken(lltok::rparen, "expected ')' here"))
5202     return true;
5203 
5204   Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5205   return false;
5206 }
5207 
5208 /// parseDIGlobalVariableExpression:
5209 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5210 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5211                                                bool IsDistinct) {
5212 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5213   REQUIRED(var, MDField, );                                                    \
5214   REQUIRED(expr, MDField, );
5215   PARSE_MD_FIELDS();
5216 #undef VISIT_MD_FIELDS
5217 
5218   Result =
5219       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5220   return false;
5221 }
5222 
5223 /// parseDIObjCProperty:
5224 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5225 ///                       getter: "getFoo", attributes: 7, type: !2)
5226 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5227 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5228   OPTIONAL(name, MDStringField, );                                             \
5229   OPTIONAL(file, MDField, );                                                   \
5230   OPTIONAL(line, LineField, );                                                 \
5231   OPTIONAL(setter, MDStringField, );                                           \
5232   OPTIONAL(getter, MDStringField, );                                           \
5233   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
5234   OPTIONAL(type, MDField, );
5235   PARSE_MD_FIELDS();
5236 #undef VISIT_MD_FIELDS
5237 
5238   Result = GET_OR_DISTINCT(DIObjCProperty,
5239                            (Context, name.Val, file.Val, line.Val, setter.Val,
5240                             getter.Val, attributes.Val, type.Val));
5241   return false;
5242 }
5243 
5244 /// parseDIImportedEntity:
5245 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5246 ///                         line: 7, name: "foo", elements: !2)
5247 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5248 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
5249   REQUIRED(tag, DwarfTagField, );                                              \
5250   REQUIRED(scope, MDField, );                                                  \
5251   OPTIONAL(entity, MDField, );                                                 \
5252   OPTIONAL(file, MDField, );                                                   \
5253   OPTIONAL(line, LineField, );                                                 \
5254   OPTIONAL(name, MDStringField, );                                             \
5255   OPTIONAL(elements, MDField, );
5256   PARSE_MD_FIELDS();
5257 #undef VISIT_MD_FIELDS
5258 
5259   Result = GET_OR_DISTINCT(DIImportedEntity,
5260                            (Context, tag.Val, scope.Val, entity.Val, file.Val,
5261                             line.Val, name.Val, elements.Val));
5262   return false;
5263 }
5264 
5265 #undef PARSE_MD_FIELD
5266 #undef NOP_FIELD
5267 #undef REQUIRE_FIELD
5268 #undef DECLARE_FIELD
5269 
5270 /// parseMetadataAsValue
5271 ///  ::= metadata i32 %local
5272 ///  ::= metadata i32 @global
5273 ///  ::= metadata i32 7
5274 ///  ::= metadata !0
5275 ///  ::= metadata !{...}
5276 ///  ::= metadata !"string"
5277 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5278   // Note: the type 'metadata' has already been parsed.
5279   Metadata *MD;
5280   if (parseMetadata(MD, &PFS))
5281     return true;
5282 
5283   V = MetadataAsValue::get(Context, MD);
5284   return false;
5285 }
5286 
5287 /// parseValueAsMetadata
5288 ///  ::= i32 %local
5289 ///  ::= i32 @global
5290 ///  ::= i32 7
5291 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5292                                     PerFunctionState *PFS) {
5293   Type *Ty;
5294   LocTy Loc;
5295   if (parseType(Ty, TypeMsg, Loc))
5296     return true;
5297   if (Ty->isMetadataTy())
5298     return error(Loc, "invalid metadata-value-metadata roundtrip");
5299 
5300   Value *V;
5301   if (parseValue(Ty, V, PFS))
5302     return true;
5303 
5304   MD = ValueAsMetadata::get(V);
5305   return false;
5306 }
5307 
5308 /// parseMetadata
5309 ///  ::= i32 %local
5310 ///  ::= i32 @global
5311 ///  ::= i32 7
5312 ///  ::= !42
5313 ///  ::= !{...}
5314 ///  ::= !"string"
5315 ///  ::= !DILocation(...)
5316 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5317   if (Lex.getKind() == lltok::MetadataVar) {
5318     MDNode *N;
5319     // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5320     // so parsing this requires a Function State.
5321     if (Lex.getStrVal() == "DIArgList") {
5322       if (parseDIArgList(N, false, PFS))
5323         return true;
5324     } else if (parseSpecializedMDNode(N)) {
5325       return true;
5326     }
5327     MD = N;
5328     return false;
5329   }
5330 
5331   // ValueAsMetadata:
5332   // <type> <value>
5333   if (Lex.getKind() != lltok::exclaim)
5334     return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5335 
5336   // '!'.
5337   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5338   Lex.Lex();
5339 
5340   // MDString:
5341   //   ::= '!' STRINGCONSTANT
5342   if (Lex.getKind() == lltok::StringConstant) {
5343     MDString *S;
5344     if (parseMDString(S))
5345       return true;
5346     MD = S;
5347     return false;
5348   }
5349 
5350   // MDNode:
5351   // !{ ... }
5352   // !7
5353   MDNode *N;
5354   if (parseMDNodeTail(N))
5355     return true;
5356   MD = N;
5357   return false;
5358 }
5359 
5360 //===----------------------------------------------------------------------===//
5361 // Function Parsing.
5362 //===----------------------------------------------------------------------===//
5363 
5364 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5365                                    PerFunctionState *PFS) {
5366   if (Ty->isFunctionTy())
5367     return error(ID.Loc, "functions are not values, refer to them as pointers");
5368 
5369   switch (ID.Kind) {
5370   case ValID::t_LocalID:
5371     if (!PFS)
5372       return error(ID.Loc, "invalid use of function-local name");
5373     V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
5374     return V == nullptr;
5375   case ValID::t_LocalName:
5376     if (!PFS)
5377       return error(ID.Loc, "invalid use of function-local name");
5378     V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
5379     return V == nullptr;
5380   case ValID::t_InlineAsm: {
5381     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5382       return error(ID.Loc, "invalid type for inline asm constraint string");
5383     V = InlineAsm::get(
5384         ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5385         InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5386     return false;
5387   }
5388   case ValID::t_GlobalName:
5389     V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
5390     if (V && ID.NoCFI)
5391       V = NoCFIValue::get(cast<GlobalValue>(V));
5392     return V == nullptr;
5393   case ValID::t_GlobalID:
5394     V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
5395     if (V && ID.NoCFI)
5396       V = NoCFIValue::get(cast<GlobalValue>(V));
5397     return V == nullptr;
5398   case ValID::t_APSInt:
5399     if (!Ty->isIntegerTy())
5400       return error(ID.Loc, "integer constant must have integer type");
5401     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5402     V = ConstantInt::get(Context, ID.APSIntVal);
5403     return false;
5404   case ValID::t_APFloat:
5405     if (!Ty->isFloatingPointTy() ||
5406         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5407       return error(ID.Loc, "floating point constant invalid for type");
5408 
5409     // The lexer has no type info, so builds all half, bfloat, float, and double
5410     // FP constants as double.  Fix this here.  Long double does not need this.
5411     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5412       // Check for signaling before potentially converting and losing that info.
5413       bool IsSNAN = ID.APFloatVal.isSignaling();
5414       bool Ignored;
5415       if (Ty->isHalfTy())
5416         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5417                               &Ignored);
5418       else if (Ty->isBFloatTy())
5419         ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5420                               &Ignored);
5421       else if (Ty->isFloatTy())
5422         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5423                               &Ignored);
5424       if (IsSNAN) {
5425         // The convert call above may quiet an SNaN, so manufacture another
5426         // SNaN. The bitcast works because the payload (significand) parameter
5427         // is truncated to fit.
5428         APInt Payload = ID.APFloatVal.bitcastToAPInt();
5429         ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5430                                          ID.APFloatVal.isNegative(), &Payload);
5431       }
5432     }
5433     V = ConstantFP::get(Context, ID.APFloatVal);
5434 
5435     if (V->getType() != Ty)
5436       return error(ID.Loc, "floating point constant does not have type '" +
5437                                getTypeString(Ty) + "'");
5438 
5439     return false;
5440   case ValID::t_Null:
5441     if (!Ty->isPointerTy())
5442       return error(ID.Loc, "null must be a pointer type");
5443     V = ConstantPointerNull::get(cast<PointerType>(Ty));
5444     return false;
5445   case ValID::t_Undef:
5446     // FIXME: LabelTy should not be a first-class type.
5447     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5448       return error(ID.Loc, "invalid type for undef constant");
5449     V = UndefValue::get(Ty);
5450     return false;
5451   case ValID::t_EmptyArray:
5452     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5453       return error(ID.Loc, "invalid empty array initializer");
5454     V = UndefValue::get(Ty);
5455     return false;
5456   case ValID::t_Zero:
5457     // FIXME: LabelTy should not be a first-class type.
5458     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5459       return error(ID.Loc, "invalid type for null constant");
5460     V = Constant::getNullValue(Ty);
5461     return false;
5462   case ValID::t_None:
5463     if (!Ty->isTokenTy())
5464       return error(ID.Loc, "invalid type for none constant");
5465     V = Constant::getNullValue(Ty);
5466     return false;
5467   case ValID::t_Poison:
5468     // FIXME: LabelTy should not be a first-class type.
5469     if (!Ty->isFirstClassType() || Ty->isLabelTy())
5470       return error(ID.Loc, "invalid type for poison constant");
5471     V = PoisonValue::get(Ty);
5472     return false;
5473   case ValID::t_Constant:
5474     if (ID.ConstantVal->getType() != Ty)
5475       return error(ID.Loc, "constant expression type mismatch: got type '" +
5476                                getTypeString(ID.ConstantVal->getType()) +
5477                                "' but expected '" + getTypeString(Ty) + "'");
5478     V = ID.ConstantVal;
5479     return false;
5480   case ValID::t_ConstantStruct:
5481   case ValID::t_PackedConstantStruct:
5482     if (StructType *ST = dyn_cast<StructType>(Ty)) {
5483       if (ST->getNumElements() != ID.UIntVal)
5484         return error(ID.Loc,
5485                      "initializer with struct type has wrong # elements");
5486       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5487         return error(ID.Loc, "packed'ness of initializer and type don't match");
5488 
5489       // Verify that the elements are compatible with the structtype.
5490       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5491         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5492           return error(
5493               ID.Loc,
5494               "element " + Twine(i) +
5495                   " of struct initializer doesn't match struct element type");
5496 
5497       V = ConstantStruct::get(
5498           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5499     } else
5500       return error(ID.Loc, "constant expression type mismatch");
5501     return false;
5502   }
5503   llvm_unreachable("Invalid ValID");
5504 }
5505 
5506 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5507   C = nullptr;
5508   ValID ID;
5509   auto Loc = Lex.getLoc();
5510   if (parseValID(ID, /*PFS=*/nullptr))
5511     return true;
5512   switch (ID.Kind) {
5513   case ValID::t_APSInt:
5514   case ValID::t_APFloat:
5515   case ValID::t_Undef:
5516   case ValID::t_Constant:
5517   case ValID::t_ConstantStruct:
5518   case ValID::t_PackedConstantStruct: {
5519     Value *V;
5520     if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
5521       return true;
5522     assert(isa<Constant>(V) && "Expected a constant value");
5523     C = cast<Constant>(V);
5524     return false;
5525   }
5526   case ValID::t_Null:
5527     C = Constant::getNullValue(Ty);
5528     return false;
5529   default:
5530     return error(Loc, "expected a constant value");
5531   }
5532 }
5533 
5534 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5535   V = nullptr;
5536   ValID ID;
5537   return parseValID(ID, PFS, Ty) ||
5538          convertValIDToValue(Ty, ID, V, PFS);
5539 }
5540 
5541 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5542   Type *Ty = nullptr;
5543   return parseType(Ty) || parseValue(Ty, V, PFS);
5544 }
5545 
5546 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5547                                       PerFunctionState &PFS) {
5548   Value *V;
5549   Loc = Lex.getLoc();
5550   if (parseTypeAndValue(V, PFS))
5551     return true;
5552   if (!isa<BasicBlock>(V))
5553     return error(Loc, "expected a basic block");
5554   BB = cast<BasicBlock>(V);
5555   return false;
5556 }
5557 
5558 /// FunctionHeader
5559 ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5560 ///       OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5561 ///       '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5562 ///       OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5563 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5564   // parse the linkage.
5565   LocTy LinkageLoc = Lex.getLoc();
5566   unsigned Linkage;
5567   unsigned Visibility;
5568   unsigned DLLStorageClass;
5569   bool DSOLocal;
5570   AttrBuilder RetAttrs(M->getContext());
5571   unsigned CC;
5572   bool HasLinkage;
5573   Type *RetType = nullptr;
5574   LocTy RetTypeLoc = Lex.getLoc();
5575   if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5576                            DSOLocal) ||
5577       parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5578       parseType(RetType, RetTypeLoc, true /*void allowed*/))
5579     return true;
5580 
5581   // Verify that the linkage is ok.
5582   switch ((GlobalValue::LinkageTypes)Linkage) {
5583   case GlobalValue::ExternalLinkage:
5584     break; // always ok.
5585   case GlobalValue::ExternalWeakLinkage:
5586     if (IsDefine)
5587       return error(LinkageLoc, "invalid linkage for function definition");
5588     break;
5589   case GlobalValue::PrivateLinkage:
5590   case GlobalValue::InternalLinkage:
5591   case GlobalValue::AvailableExternallyLinkage:
5592   case GlobalValue::LinkOnceAnyLinkage:
5593   case GlobalValue::LinkOnceODRLinkage:
5594   case GlobalValue::WeakAnyLinkage:
5595   case GlobalValue::WeakODRLinkage:
5596     if (!IsDefine)
5597       return error(LinkageLoc, "invalid linkage for function declaration");
5598     break;
5599   case GlobalValue::AppendingLinkage:
5600   case GlobalValue::CommonLinkage:
5601     return error(LinkageLoc, "invalid function linkage type");
5602   }
5603 
5604   if (!isValidVisibilityForLinkage(Visibility, Linkage))
5605     return error(LinkageLoc,
5606                  "symbol with local linkage must have default visibility");
5607 
5608   if (!FunctionType::isValidReturnType(RetType))
5609     return error(RetTypeLoc, "invalid function return type");
5610 
5611   LocTy NameLoc = Lex.getLoc();
5612 
5613   std::string FunctionName;
5614   if (Lex.getKind() == lltok::GlobalVar) {
5615     FunctionName = Lex.getStrVal();
5616   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
5617     unsigned NameID = Lex.getUIntVal();
5618 
5619     if (NameID != NumberedVals.size())
5620       return tokError("function expected to be numbered '%" +
5621                       Twine(NumberedVals.size()) + "'");
5622   } else {
5623     return tokError("expected function name");
5624   }
5625 
5626   Lex.Lex();
5627 
5628   if (Lex.getKind() != lltok::lparen)
5629     return tokError("expected '(' in function argument list");
5630 
5631   SmallVector<ArgInfo, 8> ArgList;
5632   bool IsVarArg;
5633   AttrBuilder FuncAttrs(M->getContext());
5634   std::vector<unsigned> FwdRefAttrGrps;
5635   LocTy BuiltinLoc;
5636   std::string Section;
5637   std::string Partition;
5638   MaybeAlign Alignment;
5639   std::string GC;
5640   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5641   unsigned AddrSpace = 0;
5642   Constant *Prefix = nullptr;
5643   Constant *Prologue = nullptr;
5644   Constant *PersonalityFn = nullptr;
5645   Comdat *C;
5646 
5647   if (parseArgumentList(ArgList, IsVarArg) ||
5648       parseOptionalUnnamedAddr(UnnamedAddr) ||
5649       parseOptionalProgramAddrSpace(AddrSpace) ||
5650       parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5651                                  BuiltinLoc) ||
5652       (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5653       (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5654       parseOptionalComdat(FunctionName, C) ||
5655       parseOptionalAlignment(Alignment) ||
5656       (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5657       (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5658       (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5659       (EatIfPresent(lltok::kw_personality) &&
5660        parseGlobalTypeAndValue(PersonalityFn)))
5661     return true;
5662 
5663   if (FuncAttrs.contains(Attribute::Builtin))
5664     return error(BuiltinLoc, "'builtin' attribute not valid on function");
5665 
5666   // If the alignment was parsed as an attribute, move to the alignment field.
5667   if (FuncAttrs.hasAlignmentAttr()) {
5668     Alignment = FuncAttrs.getAlignment();
5669     FuncAttrs.removeAttribute(Attribute::Alignment);
5670   }
5671 
5672   // Okay, if we got here, the function is syntactically valid.  Convert types
5673   // and do semantic checks.
5674   std::vector<Type*> ParamTypeList;
5675   SmallVector<AttributeSet, 8> Attrs;
5676 
5677   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5678     ParamTypeList.push_back(ArgList[i].Ty);
5679     Attrs.push_back(ArgList[i].Attrs);
5680   }
5681 
5682   AttributeList PAL =
5683       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5684                          AttributeSet::get(Context, RetAttrs), Attrs);
5685 
5686   if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
5687     return error(RetTypeLoc, "functions with 'sret' argument must return void");
5688 
5689   FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5690   PointerType *PFT = PointerType::get(FT, AddrSpace);
5691 
5692   Fn = nullptr;
5693   GlobalValue *FwdFn = nullptr;
5694   if (!FunctionName.empty()) {
5695     // If this was a definition of a forward reference, remove the definition
5696     // from the forward reference table and fill in the forward ref.
5697     auto FRVI = ForwardRefVals.find(FunctionName);
5698     if (FRVI != ForwardRefVals.end()) {
5699       FwdFn = FRVI->second.first;
5700       if (!FwdFn->getType()->isOpaque() &&
5701           !FwdFn->getType()->getNonOpaquePointerElementType()->isFunctionTy())
5702         return error(FRVI->second.second, "invalid forward reference to "
5703                                           "function as global value!");
5704       if (FwdFn->getType() != PFT)
5705         return error(FRVI->second.second,
5706                      "invalid forward reference to "
5707                      "function '" +
5708                          FunctionName +
5709                          "' with wrong type: "
5710                          "expected '" +
5711                          getTypeString(PFT) + "' but was '" +
5712                          getTypeString(FwdFn->getType()) + "'");
5713       ForwardRefVals.erase(FRVI);
5714     } else if ((Fn = M->getFunction(FunctionName))) {
5715       // Reject redefinitions.
5716       return error(NameLoc,
5717                    "invalid redefinition of function '" + FunctionName + "'");
5718     } else if (M->getNamedValue(FunctionName)) {
5719       return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5720     }
5721 
5722   } else {
5723     // If this is a definition of a forward referenced function, make sure the
5724     // types agree.
5725     auto I = ForwardRefValIDs.find(NumberedVals.size());
5726     if (I != ForwardRefValIDs.end()) {
5727       FwdFn = I->second.first;
5728       if (FwdFn->getType() != PFT)
5729         return error(NameLoc, "type of definition and forward reference of '@" +
5730                                   Twine(NumberedVals.size()) +
5731                                   "' disagree: "
5732                                   "expected '" +
5733                                   getTypeString(PFT) + "' but was '" +
5734                                   getTypeString(FwdFn->getType()) + "'");
5735       ForwardRefValIDs.erase(I);
5736     }
5737   }
5738 
5739   Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5740                         FunctionName, M);
5741 
5742   assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5743 
5744   if (FunctionName.empty())
5745     NumberedVals.push_back(Fn);
5746 
5747   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5748   maybeSetDSOLocal(DSOLocal, *Fn);
5749   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5750   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5751   Fn->setCallingConv(CC);
5752   Fn->setAttributes(PAL);
5753   Fn->setUnnamedAddr(UnnamedAddr);
5754   Fn->setAlignment(MaybeAlign(Alignment));
5755   Fn->setSection(Section);
5756   Fn->setPartition(Partition);
5757   Fn->setComdat(C);
5758   Fn->setPersonalityFn(PersonalityFn);
5759   if (!GC.empty()) Fn->setGC(GC);
5760   Fn->setPrefixData(Prefix);
5761   Fn->setPrologueData(Prologue);
5762   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5763 
5764   // Add all of the arguments we parsed to the function.
5765   Function::arg_iterator ArgIt = Fn->arg_begin();
5766   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5767     // If the argument has a name, insert it into the argument symbol table.
5768     if (ArgList[i].Name.empty()) continue;
5769 
5770     // Set the name, if it conflicted, it will be auto-renamed.
5771     ArgIt->setName(ArgList[i].Name);
5772 
5773     if (ArgIt->getName() != ArgList[i].Name)
5774       return error(ArgList[i].Loc,
5775                    "redefinition of argument '%" + ArgList[i].Name + "'");
5776   }
5777 
5778   if (FwdFn) {
5779     FwdFn->replaceAllUsesWith(Fn);
5780     FwdFn->eraseFromParent();
5781   }
5782 
5783   if (IsDefine)
5784     return false;
5785 
5786   // Check the declaration has no block address forward references.
5787   ValID ID;
5788   if (FunctionName.empty()) {
5789     ID.Kind = ValID::t_GlobalID;
5790     ID.UIntVal = NumberedVals.size() - 1;
5791   } else {
5792     ID.Kind = ValID::t_GlobalName;
5793     ID.StrVal = FunctionName;
5794   }
5795   auto Blocks = ForwardRefBlockAddresses.find(ID);
5796   if (Blocks != ForwardRefBlockAddresses.end())
5797     return error(Blocks->first.Loc,
5798                  "cannot take blockaddress inside a declaration");
5799   return false;
5800 }
5801 
5802 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5803   ValID ID;
5804   if (FunctionNumber == -1) {
5805     ID.Kind = ValID::t_GlobalName;
5806     ID.StrVal = std::string(F.getName());
5807   } else {
5808     ID.Kind = ValID::t_GlobalID;
5809     ID.UIntVal = FunctionNumber;
5810   }
5811 
5812   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5813   if (Blocks == P.ForwardRefBlockAddresses.end())
5814     return false;
5815 
5816   for (const auto &I : Blocks->second) {
5817     const ValID &BBID = I.first;
5818     GlobalValue *GV = I.second;
5819 
5820     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5821            "Expected local id or name");
5822     BasicBlock *BB;
5823     if (BBID.Kind == ValID::t_LocalName)
5824       BB = getBB(BBID.StrVal, BBID.Loc);
5825     else
5826       BB = getBB(BBID.UIntVal, BBID.Loc);
5827     if (!BB)
5828       return P.error(BBID.Loc, "referenced value is not a basic block");
5829 
5830     Value *ResolvedVal = BlockAddress::get(&F, BB);
5831     ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
5832                                            ResolvedVal);
5833     if (!ResolvedVal)
5834       return true;
5835     GV->replaceAllUsesWith(ResolvedVal);
5836     GV->eraseFromParent();
5837   }
5838 
5839   P.ForwardRefBlockAddresses.erase(Blocks);
5840   return false;
5841 }
5842 
5843 /// parseFunctionBody
5844 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
5845 bool LLParser::parseFunctionBody(Function &Fn) {
5846   if (Lex.getKind() != lltok::lbrace)
5847     return tokError("expected '{' in function body");
5848   Lex.Lex();  // eat the {.
5849 
5850   int FunctionNumber = -1;
5851   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5852 
5853   PerFunctionState PFS(*this, Fn, FunctionNumber);
5854 
5855   // Resolve block addresses and allow basic blocks to be forward-declared
5856   // within this function.
5857   if (PFS.resolveForwardRefBlockAddresses())
5858     return true;
5859   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5860 
5861   // We need at least one basic block.
5862   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5863     return tokError("function body requires at least one basic block");
5864 
5865   while (Lex.getKind() != lltok::rbrace &&
5866          Lex.getKind() != lltok::kw_uselistorder)
5867     if (parseBasicBlock(PFS))
5868       return true;
5869 
5870   while (Lex.getKind() != lltok::rbrace)
5871     if (parseUseListOrder(&PFS))
5872       return true;
5873 
5874   // Eat the }.
5875   Lex.Lex();
5876 
5877   // Verify function is ok.
5878   return PFS.finishFunction();
5879 }
5880 
5881 /// parseBasicBlock
5882 ///   ::= (LabelStr|LabelID)? Instruction*
5883 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
5884   // If this basic block starts out with a name, remember it.
5885   std::string Name;
5886   int NameID = -1;
5887   LocTy NameLoc = Lex.getLoc();
5888   if (Lex.getKind() == lltok::LabelStr) {
5889     Name = Lex.getStrVal();
5890     Lex.Lex();
5891   } else if (Lex.getKind() == lltok::LabelID) {
5892     NameID = Lex.getUIntVal();
5893     Lex.Lex();
5894   }
5895 
5896   BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
5897   if (!BB)
5898     return true;
5899 
5900   std::string NameStr;
5901 
5902   // parse the instructions in this block until we get a terminator.
5903   Instruction *Inst;
5904   do {
5905     // This instruction may have three possibilities for a name: a) none
5906     // specified, b) name specified "%foo =", c) number specified: "%4 =".
5907     LocTy NameLoc = Lex.getLoc();
5908     int NameID = -1;
5909     NameStr = "";
5910 
5911     if (Lex.getKind() == lltok::LocalVarID) {
5912       NameID = Lex.getUIntVal();
5913       Lex.Lex();
5914       if (parseToken(lltok::equal, "expected '=' after instruction id"))
5915         return true;
5916     } else if (Lex.getKind() == lltok::LocalVar) {
5917       NameStr = Lex.getStrVal();
5918       Lex.Lex();
5919       if (parseToken(lltok::equal, "expected '=' after instruction name"))
5920         return true;
5921     }
5922 
5923     switch (parseInstruction(Inst, BB, PFS)) {
5924     default:
5925       llvm_unreachable("Unknown parseInstruction result!");
5926     case InstError: return true;
5927     case InstNormal:
5928       BB->getInstList().push_back(Inst);
5929 
5930       // With a normal result, we check to see if the instruction is followed by
5931       // a comma and metadata.
5932       if (EatIfPresent(lltok::comma))
5933         if (parseInstructionMetadata(*Inst))
5934           return true;
5935       break;
5936     case InstExtraComma:
5937       BB->getInstList().push_back(Inst);
5938 
5939       // If the instruction parser ate an extra comma at the end of it, it
5940       // *must* be followed by metadata.
5941       if (parseInstructionMetadata(*Inst))
5942         return true;
5943       break;
5944     }
5945 
5946     // Set the name on the instruction.
5947     if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
5948       return true;
5949   } while (!Inst->isTerminator());
5950 
5951   return false;
5952 }
5953 
5954 //===----------------------------------------------------------------------===//
5955 // Instruction Parsing.
5956 //===----------------------------------------------------------------------===//
5957 
5958 /// parseInstruction - parse one of the many different instructions.
5959 ///
5960 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
5961                                PerFunctionState &PFS) {
5962   lltok::Kind Token = Lex.getKind();
5963   if (Token == lltok::Eof)
5964     return tokError("found end of file when expecting more instructions");
5965   LocTy Loc = Lex.getLoc();
5966   unsigned KeywordVal = Lex.getUIntVal();
5967   Lex.Lex();  // Eat the keyword.
5968 
5969   switch (Token) {
5970   default:
5971     return error(Loc, "expected instruction opcode");
5972   // Terminator Instructions.
5973   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5974   case lltok::kw_ret:
5975     return parseRet(Inst, BB, PFS);
5976   case lltok::kw_br:
5977     return parseBr(Inst, PFS);
5978   case lltok::kw_switch:
5979     return parseSwitch(Inst, PFS);
5980   case lltok::kw_indirectbr:
5981     return parseIndirectBr(Inst, PFS);
5982   case lltok::kw_invoke:
5983     return parseInvoke(Inst, PFS);
5984   case lltok::kw_resume:
5985     return parseResume(Inst, PFS);
5986   case lltok::kw_cleanupret:
5987     return parseCleanupRet(Inst, PFS);
5988   case lltok::kw_catchret:
5989     return parseCatchRet(Inst, PFS);
5990   case lltok::kw_catchswitch:
5991     return parseCatchSwitch(Inst, PFS);
5992   case lltok::kw_catchpad:
5993     return parseCatchPad(Inst, PFS);
5994   case lltok::kw_cleanuppad:
5995     return parseCleanupPad(Inst, PFS);
5996   case lltok::kw_callbr:
5997     return parseCallBr(Inst, PFS);
5998   // Unary Operators.
5999   case lltok::kw_fneg: {
6000     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6001     int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6002     if (Res != 0)
6003       return Res;
6004     if (FMF.any())
6005       Inst->setFastMathFlags(FMF);
6006     return false;
6007   }
6008   // Binary Operators.
6009   case lltok::kw_add:
6010   case lltok::kw_sub:
6011   case lltok::kw_mul:
6012   case lltok::kw_shl: {
6013     bool NUW = EatIfPresent(lltok::kw_nuw);
6014     bool NSW = EatIfPresent(lltok::kw_nsw);
6015     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6016 
6017     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6018       return true;
6019 
6020     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6021     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6022     return false;
6023   }
6024   case lltok::kw_fadd:
6025   case lltok::kw_fsub:
6026   case lltok::kw_fmul:
6027   case lltok::kw_fdiv:
6028   case lltok::kw_frem: {
6029     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6030     int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6031     if (Res != 0)
6032       return Res;
6033     if (FMF.any())
6034       Inst->setFastMathFlags(FMF);
6035     return 0;
6036   }
6037 
6038   case lltok::kw_sdiv:
6039   case lltok::kw_udiv:
6040   case lltok::kw_lshr:
6041   case lltok::kw_ashr: {
6042     bool Exact = EatIfPresent(lltok::kw_exact);
6043 
6044     if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6045       return true;
6046     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6047     return false;
6048   }
6049 
6050   case lltok::kw_urem:
6051   case lltok::kw_srem:
6052     return parseArithmetic(Inst, PFS, KeywordVal,
6053                            /*IsFP*/ false);
6054   case lltok::kw_and:
6055   case lltok::kw_or:
6056   case lltok::kw_xor:
6057     return parseLogical(Inst, PFS, KeywordVal);
6058   case lltok::kw_icmp:
6059     return parseCompare(Inst, PFS, KeywordVal);
6060   case lltok::kw_fcmp: {
6061     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6062     int Res = parseCompare(Inst, PFS, KeywordVal);
6063     if (Res != 0)
6064       return Res;
6065     if (FMF.any())
6066       Inst->setFastMathFlags(FMF);
6067     return 0;
6068   }
6069 
6070   // Casts.
6071   case lltok::kw_trunc:
6072   case lltok::kw_zext:
6073   case lltok::kw_sext:
6074   case lltok::kw_fptrunc:
6075   case lltok::kw_fpext:
6076   case lltok::kw_bitcast:
6077   case lltok::kw_addrspacecast:
6078   case lltok::kw_uitofp:
6079   case lltok::kw_sitofp:
6080   case lltok::kw_fptoui:
6081   case lltok::kw_fptosi:
6082   case lltok::kw_inttoptr:
6083   case lltok::kw_ptrtoint:
6084     return parseCast(Inst, PFS, KeywordVal);
6085   // Other.
6086   case lltok::kw_select: {
6087     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6088     int Res = parseSelect(Inst, PFS);
6089     if (Res != 0)
6090       return Res;
6091     if (FMF.any()) {
6092       if (!isa<FPMathOperator>(Inst))
6093         return error(Loc, "fast-math-flags specified for select without "
6094                           "floating-point scalar or vector return type");
6095       Inst->setFastMathFlags(FMF);
6096     }
6097     return 0;
6098   }
6099   case lltok::kw_va_arg:
6100     return parseVAArg(Inst, PFS);
6101   case lltok::kw_extractelement:
6102     return parseExtractElement(Inst, PFS);
6103   case lltok::kw_insertelement:
6104     return parseInsertElement(Inst, PFS);
6105   case lltok::kw_shufflevector:
6106     return parseShuffleVector(Inst, PFS);
6107   case lltok::kw_phi: {
6108     FastMathFlags FMF = EatFastMathFlagsIfPresent();
6109     int Res = parsePHI(Inst, PFS);
6110     if (Res != 0)
6111       return Res;
6112     if (FMF.any()) {
6113       if (!isa<FPMathOperator>(Inst))
6114         return error(Loc, "fast-math-flags specified for phi without "
6115                           "floating-point scalar or vector return type");
6116       Inst->setFastMathFlags(FMF);
6117     }
6118     return 0;
6119   }
6120   case lltok::kw_landingpad:
6121     return parseLandingPad(Inst, PFS);
6122   case lltok::kw_freeze:
6123     return parseFreeze(Inst, PFS);
6124   // Call.
6125   case lltok::kw_call:
6126     return parseCall(Inst, PFS, CallInst::TCK_None);
6127   case lltok::kw_tail:
6128     return parseCall(Inst, PFS, CallInst::TCK_Tail);
6129   case lltok::kw_musttail:
6130     return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6131   case lltok::kw_notail:
6132     return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6133   // Memory.
6134   case lltok::kw_alloca:
6135     return parseAlloc(Inst, PFS);
6136   case lltok::kw_load:
6137     return parseLoad(Inst, PFS);
6138   case lltok::kw_store:
6139     return parseStore(Inst, PFS);
6140   case lltok::kw_cmpxchg:
6141     return parseCmpXchg(Inst, PFS);
6142   case lltok::kw_atomicrmw:
6143     return parseAtomicRMW(Inst, PFS);
6144   case lltok::kw_fence:
6145     return parseFence(Inst, PFS);
6146   case lltok::kw_getelementptr:
6147     return parseGetElementPtr(Inst, PFS);
6148   case lltok::kw_extractvalue:
6149     return parseExtractValue(Inst, PFS);
6150   case lltok::kw_insertvalue:
6151     return parseInsertValue(Inst, PFS);
6152   }
6153 }
6154 
6155 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6156 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6157   if (Opc == Instruction::FCmp) {
6158     switch (Lex.getKind()) {
6159     default:
6160       return tokError("expected fcmp predicate (e.g. 'oeq')");
6161     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6162     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6163     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6164     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6165     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6166     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6167     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6168     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6169     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6170     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6171     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6172     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6173     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6174     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6175     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6176     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6177     }
6178   } else {
6179     switch (Lex.getKind()) {
6180     default:
6181       return tokError("expected icmp predicate (e.g. 'eq')");
6182     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
6183     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
6184     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6185     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6186     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6187     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6188     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6189     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6190     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6191     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6192     }
6193   }
6194   Lex.Lex();
6195   return false;
6196 }
6197 
6198 //===----------------------------------------------------------------------===//
6199 // Terminator Instructions.
6200 //===----------------------------------------------------------------------===//
6201 
6202 /// parseRet - parse a return instruction.
6203 ///   ::= 'ret' void (',' !dbg, !1)*
6204 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
6205 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6206                         PerFunctionState &PFS) {
6207   SMLoc TypeLoc = Lex.getLoc();
6208   Type *Ty = nullptr;
6209   if (parseType(Ty, true /*void allowed*/))
6210     return true;
6211 
6212   Type *ResType = PFS.getFunction().getReturnType();
6213 
6214   if (Ty->isVoidTy()) {
6215     if (!ResType->isVoidTy())
6216       return error(TypeLoc, "value doesn't match function result type '" +
6217                                 getTypeString(ResType) + "'");
6218 
6219     Inst = ReturnInst::Create(Context);
6220     return false;
6221   }
6222 
6223   Value *RV;
6224   if (parseValue(Ty, RV, PFS))
6225     return true;
6226 
6227   if (ResType != RV->getType())
6228     return error(TypeLoc, "value doesn't match function result type '" +
6229                               getTypeString(ResType) + "'");
6230 
6231   Inst = ReturnInst::Create(Context, RV);
6232   return false;
6233 }
6234 
6235 /// parseBr
6236 ///   ::= 'br' TypeAndValue
6237 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6238 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6239   LocTy Loc, Loc2;
6240   Value *Op0;
6241   BasicBlock *Op1, *Op2;
6242   if (parseTypeAndValue(Op0, Loc, PFS))
6243     return true;
6244 
6245   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6246     Inst = BranchInst::Create(BB);
6247     return false;
6248   }
6249 
6250   if (Op0->getType() != Type::getInt1Ty(Context))
6251     return error(Loc, "branch condition must have 'i1' type");
6252 
6253   if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6254       parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6255       parseToken(lltok::comma, "expected ',' after true destination") ||
6256       parseTypeAndBasicBlock(Op2, Loc2, PFS))
6257     return true;
6258 
6259   Inst = BranchInst::Create(Op1, Op2, Op0);
6260   return false;
6261 }
6262 
6263 /// parseSwitch
6264 ///  Instruction
6265 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6266 ///  JumpTable
6267 ///    ::= (TypeAndValue ',' TypeAndValue)*
6268 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6269   LocTy CondLoc, BBLoc;
6270   Value *Cond;
6271   BasicBlock *DefaultBB;
6272   if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6273       parseToken(lltok::comma, "expected ',' after switch condition") ||
6274       parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6275       parseToken(lltok::lsquare, "expected '[' with switch table"))
6276     return true;
6277 
6278   if (!Cond->getType()->isIntegerTy())
6279     return error(CondLoc, "switch condition must have integer type");
6280 
6281   // parse the jump table pairs.
6282   SmallPtrSet<Value*, 32> SeenCases;
6283   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6284   while (Lex.getKind() != lltok::rsquare) {
6285     Value *Constant;
6286     BasicBlock *DestBB;
6287 
6288     if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6289         parseToken(lltok::comma, "expected ',' after case value") ||
6290         parseTypeAndBasicBlock(DestBB, PFS))
6291       return true;
6292 
6293     if (!SeenCases.insert(Constant).second)
6294       return error(CondLoc, "duplicate case value in switch");
6295     if (!isa<ConstantInt>(Constant))
6296       return error(CondLoc, "case value is not a constant integer");
6297 
6298     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6299   }
6300 
6301   Lex.Lex();  // Eat the ']'.
6302 
6303   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6304   for (unsigned i = 0, e = Table.size(); i != e; ++i)
6305     SI->addCase(Table[i].first, Table[i].second);
6306   Inst = SI;
6307   return false;
6308 }
6309 
6310 /// parseIndirectBr
6311 ///  Instruction
6312 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6313 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6314   LocTy AddrLoc;
6315   Value *Address;
6316   if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6317       parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6318       parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6319     return true;
6320 
6321   if (!Address->getType()->isPointerTy())
6322     return error(AddrLoc, "indirectbr address must have pointer type");
6323 
6324   // parse the destination list.
6325   SmallVector<BasicBlock*, 16> DestList;
6326 
6327   if (Lex.getKind() != lltok::rsquare) {
6328     BasicBlock *DestBB;
6329     if (parseTypeAndBasicBlock(DestBB, PFS))
6330       return true;
6331     DestList.push_back(DestBB);
6332 
6333     while (EatIfPresent(lltok::comma)) {
6334       if (parseTypeAndBasicBlock(DestBB, PFS))
6335         return true;
6336       DestList.push_back(DestBB);
6337     }
6338   }
6339 
6340   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6341     return true;
6342 
6343   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6344   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6345     IBI->addDestination(DestList[i]);
6346   Inst = IBI;
6347   return false;
6348 }
6349 
6350 /// parseInvoke
6351 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6352 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6353 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6354   LocTy CallLoc = Lex.getLoc();
6355   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6356   std::vector<unsigned> FwdRefAttrGrps;
6357   LocTy NoBuiltinLoc;
6358   unsigned CC;
6359   unsigned InvokeAddrSpace;
6360   Type *RetType = nullptr;
6361   LocTy RetTypeLoc;
6362   ValID CalleeID;
6363   SmallVector<ParamInfo, 16> ArgList;
6364   SmallVector<OperandBundleDef, 2> BundleList;
6365 
6366   BasicBlock *NormalBB, *UnwindBB;
6367   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6368       parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6369       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6370       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6371       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6372                                  NoBuiltinLoc) ||
6373       parseOptionalOperandBundles(BundleList, PFS) ||
6374       parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6375       parseTypeAndBasicBlock(NormalBB, PFS) ||
6376       parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6377       parseTypeAndBasicBlock(UnwindBB, PFS))
6378     return true;
6379 
6380   // If RetType is a non-function pointer type, then this is the short syntax
6381   // for the call, which means that RetType is just the return type.  Infer the
6382   // rest of the function argument types from the arguments that are present.
6383   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6384   if (!Ty) {
6385     // Pull out the types of all of the arguments...
6386     std::vector<Type*> ParamTypes;
6387     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6388       ParamTypes.push_back(ArgList[i].V->getType());
6389 
6390     if (!FunctionType::isValidReturnType(RetType))
6391       return error(RetTypeLoc, "Invalid result type for LLVM function");
6392 
6393     Ty = FunctionType::get(RetType, ParamTypes, false);
6394   }
6395 
6396   CalleeID.FTy = Ty;
6397 
6398   // Look up the callee.
6399   Value *Callee;
6400   if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6401                           Callee, &PFS))
6402     return true;
6403 
6404   // Set up the Attribute for the function.
6405   SmallVector<Value *, 8> Args;
6406   SmallVector<AttributeSet, 8> ArgAttrs;
6407 
6408   // Loop through FunctionType's arguments and ensure they are specified
6409   // correctly.  Also, gather any parameter attributes.
6410   FunctionType::param_iterator I = Ty->param_begin();
6411   FunctionType::param_iterator E = Ty->param_end();
6412   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6413     Type *ExpectedTy = nullptr;
6414     if (I != E) {
6415       ExpectedTy = *I++;
6416     } else if (!Ty->isVarArg()) {
6417       return error(ArgList[i].Loc, "too many arguments specified");
6418     }
6419 
6420     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6421       return error(ArgList[i].Loc, "argument is not of expected type '" +
6422                                        getTypeString(ExpectedTy) + "'");
6423     Args.push_back(ArgList[i].V);
6424     ArgAttrs.push_back(ArgList[i].Attrs);
6425   }
6426 
6427   if (I != E)
6428     return error(CallLoc, "not enough parameters specified for call");
6429 
6430   if (FnAttrs.hasAlignmentAttr())
6431     return error(CallLoc, "invoke instructions may not have an alignment");
6432 
6433   // Finish off the Attribute and check them
6434   AttributeList PAL =
6435       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6436                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6437 
6438   InvokeInst *II =
6439       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6440   II->setCallingConv(CC);
6441   II->setAttributes(PAL);
6442   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6443   Inst = II;
6444   return false;
6445 }
6446 
6447 /// parseResume
6448 ///   ::= 'resume' TypeAndValue
6449 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6450   Value *Exn; LocTy ExnLoc;
6451   if (parseTypeAndValue(Exn, ExnLoc, PFS))
6452     return true;
6453 
6454   ResumeInst *RI = ResumeInst::Create(Exn);
6455   Inst = RI;
6456   return false;
6457 }
6458 
6459 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6460                                   PerFunctionState &PFS) {
6461   if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6462     return true;
6463 
6464   while (Lex.getKind() != lltok::rsquare) {
6465     // If this isn't the first argument, we need a comma.
6466     if (!Args.empty() &&
6467         parseToken(lltok::comma, "expected ',' in argument list"))
6468       return true;
6469 
6470     // parse the argument.
6471     LocTy ArgLoc;
6472     Type *ArgTy = nullptr;
6473     if (parseType(ArgTy, ArgLoc))
6474       return true;
6475 
6476     Value *V;
6477     if (ArgTy->isMetadataTy()) {
6478       if (parseMetadataAsValue(V, PFS))
6479         return true;
6480     } else {
6481       if (parseValue(ArgTy, V, PFS))
6482         return true;
6483     }
6484     Args.push_back(V);
6485   }
6486 
6487   Lex.Lex();  // Lex the ']'.
6488   return false;
6489 }
6490 
6491 /// parseCleanupRet
6492 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6493 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6494   Value *CleanupPad = nullptr;
6495 
6496   if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6497     return true;
6498 
6499   if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6500     return true;
6501 
6502   if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6503     return true;
6504 
6505   BasicBlock *UnwindBB = nullptr;
6506   if (Lex.getKind() == lltok::kw_to) {
6507     Lex.Lex();
6508     if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6509       return true;
6510   } else {
6511     if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6512       return true;
6513     }
6514   }
6515 
6516   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6517   return false;
6518 }
6519 
6520 /// parseCatchRet
6521 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
6522 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6523   Value *CatchPad = nullptr;
6524 
6525   if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6526     return true;
6527 
6528   if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6529     return true;
6530 
6531   BasicBlock *BB;
6532   if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6533       parseTypeAndBasicBlock(BB, PFS))
6534     return true;
6535 
6536   Inst = CatchReturnInst::Create(CatchPad, BB);
6537   return false;
6538 }
6539 
6540 /// parseCatchSwitch
6541 ///   ::= 'catchswitch' within Parent
6542 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6543   Value *ParentPad;
6544 
6545   if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6546     return true;
6547 
6548   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6549       Lex.getKind() != lltok::LocalVarID)
6550     return tokError("expected scope value for catchswitch");
6551 
6552   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6553     return true;
6554 
6555   if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6556     return true;
6557 
6558   SmallVector<BasicBlock *, 32> Table;
6559   do {
6560     BasicBlock *DestBB;
6561     if (parseTypeAndBasicBlock(DestBB, PFS))
6562       return true;
6563     Table.push_back(DestBB);
6564   } while (EatIfPresent(lltok::comma));
6565 
6566   if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6567     return true;
6568 
6569   if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6570     return true;
6571 
6572   BasicBlock *UnwindBB = nullptr;
6573   if (EatIfPresent(lltok::kw_to)) {
6574     if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6575       return true;
6576   } else {
6577     if (parseTypeAndBasicBlock(UnwindBB, PFS))
6578       return true;
6579   }
6580 
6581   auto *CatchSwitch =
6582       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6583   for (BasicBlock *DestBB : Table)
6584     CatchSwitch->addHandler(DestBB);
6585   Inst = CatchSwitch;
6586   return false;
6587 }
6588 
6589 /// parseCatchPad
6590 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6591 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6592   Value *CatchSwitch = nullptr;
6593 
6594   if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6595     return true;
6596 
6597   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6598     return tokError("expected scope value for catchpad");
6599 
6600   if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6601     return true;
6602 
6603   SmallVector<Value *, 8> Args;
6604   if (parseExceptionArgs(Args, PFS))
6605     return true;
6606 
6607   Inst = CatchPadInst::Create(CatchSwitch, Args);
6608   return false;
6609 }
6610 
6611 /// parseCleanupPad
6612 ///   ::= 'cleanuppad' within Parent ParamList
6613 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6614   Value *ParentPad = nullptr;
6615 
6616   if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6617     return true;
6618 
6619   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6620       Lex.getKind() != lltok::LocalVarID)
6621     return tokError("expected scope value for cleanuppad");
6622 
6623   if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6624     return true;
6625 
6626   SmallVector<Value *, 8> Args;
6627   if (parseExceptionArgs(Args, PFS))
6628     return true;
6629 
6630   Inst = CleanupPadInst::Create(ParentPad, Args);
6631   return false;
6632 }
6633 
6634 //===----------------------------------------------------------------------===//
6635 // Unary Operators.
6636 //===----------------------------------------------------------------------===//
6637 
6638 /// parseUnaryOp
6639 ///  ::= UnaryOp TypeAndValue ',' Value
6640 ///
6641 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6642 /// operand is allowed.
6643 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6644                             unsigned Opc, bool IsFP) {
6645   LocTy Loc; Value *LHS;
6646   if (parseTypeAndValue(LHS, Loc, PFS))
6647     return true;
6648 
6649   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6650                     : LHS->getType()->isIntOrIntVectorTy();
6651 
6652   if (!Valid)
6653     return error(Loc, "invalid operand type for instruction");
6654 
6655   Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6656   return false;
6657 }
6658 
6659 /// parseCallBr
6660 ///   ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6661 ///       OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6662 ///       '[' LabelList ']'
6663 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6664   LocTy CallLoc = Lex.getLoc();
6665   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6666   std::vector<unsigned> FwdRefAttrGrps;
6667   LocTy NoBuiltinLoc;
6668   unsigned CC;
6669   Type *RetType = nullptr;
6670   LocTy RetTypeLoc;
6671   ValID CalleeID;
6672   SmallVector<ParamInfo, 16> ArgList;
6673   SmallVector<OperandBundleDef, 2> BundleList;
6674 
6675   BasicBlock *DefaultDest;
6676   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6677       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6678       parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6679       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6680                                  NoBuiltinLoc) ||
6681       parseOptionalOperandBundles(BundleList, PFS) ||
6682       parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6683       parseTypeAndBasicBlock(DefaultDest, PFS) ||
6684       parseToken(lltok::lsquare, "expected '[' in callbr"))
6685     return true;
6686 
6687   // parse the destination list.
6688   SmallVector<BasicBlock *, 16> IndirectDests;
6689 
6690   if (Lex.getKind() != lltok::rsquare) {
6691     BasicBlock *DestBB;
6692     if (parseTypeAndBasicBlock(DestBB, PFS))
6693       return true;
6694     IndirectDests.push_back(DestBB);
6695 
6696     while (EatIfPresent(lltok::comma)) {
6697       if (parseTypeAndBasicBlock(DestBB, PFS))
6698         return true;
6699       IndirectDests.push_back(DestBB);
6700     }
6701   }
6702 
6703   if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6704     return true;
6705 
6706   // If RetType is a non-function pointer type, then this is the short syntax
6707   // for the call, which means that RetType is just the return type.  Infer the
6708   // rest of the function argument types from the arguments that are present.
6709   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6710   if (!Ty) {
6711     // Pull out the types of all of the arguments...
6712     std::vector<Type *> ParamTypes;
6713     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6714       ParamTypes.push_back(ArgList[i].V->getType());
6715 
6716     if (!FunctionType::isValidReturnType(RetType))
6717       return error(RetTypeLoc, "Invalid result type for LLVM function");
6718 
6719     Ty = FunctionType::get(RetType, ParamTypes, false);
6720   }
6721 
6722   CalleeID.FTy = Ty;
6723 
6724   // Look up the callee.
6725   Value *Callee;
6726   if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6727     return true;
6728 
6729   // Set up the Attribute for the function.
6730   SmallVector<Value *, 8> Args;
6731   SmallVector<AttributeSet, 8> ArgAttrs;
6732 
6733   // Loop through FunctionType's arguments and ensure they are specified
6734   // correctly.  Also, gather any parameter attributes.
6735   FunctionType::param_iterator I = Ty->param_begin();
6736   FunctionType::param_iterator E = Ty->param_end();
6737   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6738     Type *ExpectedTy = nullptr;
6739     if (I != E) {
6740       ExpectedTy = *I++;
6741     } else if (!Ty->isVarArg()) {
6742       return error(ArgList[i].Loc, "too many arguments specified");
6743     }
6744 
6745     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6746       return error(ArgList[i].Loc, "argument is not of expected type '" +
6747                                        getTypeString(ExpectedTy) + "'");
6748     Args.push_back(ArgList[i].V);
6749     ArgAttrs.push_back(ArgList[i].Attrs);
6750   }
6751 
6752   if (I != E)
6753     return error(CallLoc, "not enough parameters specified for call");
6754 
6755   if (FnAttrs.hasAlignmentAttr())
6756     return error(CallLoc, "callbr instructions may not have an alignment");
6757 
6758   // Finish off the Attribute and check them
6759   AttributeList PAL =
6760       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6761                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
6762 
6763   CallBrInst *CBI =
6764       CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6765                          BundleList);
6766   CBI->setCallingConv(CC);
6767   CBI->setAttributes(PAL);
6768   ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6769   Inst = CBI;
6770   return false;
6771 }
6772 
6773 //===----------------------------------------------------------------------===//
6774 // Binary Operators.
6775 //===----------------------------------------------------------------------===//
6776 
6777 /// parseArithmetic
6778 ///  ::= ArithmeticOps TypeAndValue ',' Value
6779 ///
6780 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6781 /// operand is allowed.
6782 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6783                                unsigned Opc, bool IsFP) {
6784   LocTy Loc; Value *LHS, *RHS;
6785   if (parseTypeAndValue(LHS, Loc, PFS) ||
6786       parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6787       parseValue(LHS->getType(), RHS, PFS))
6788     return true;
6789 
6790   bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6791                     : LHS->getType()->isIntOrIntVectorTy();
6792 
6793   if (!Valid)
6794     return error(Loc, "invalid operand type for instruction");
6795 
6796   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6797   return false;
6798 }
6799 
6800 /// parseLogical
6801 ///  ::= ArithmeticOps TypeAndValue ',' Value {
6802 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6803                             unsigned Opc) {
6804   LocTy Loc; Value *LHS, *RHS;
6805   if (parseTypeAndValue(LHS, Loc, PFS) ||
6806       parseToken(lltok::comma, "expected ',' in logical operation") ||
6807       parseValue(LHS->getType(), RHS, PFS))
6808     return true;
6809 
6810   if (!LHS->getType()->isIntOrIntVectorTy())
6811     return error(Loc,
6812                  "instruction requires integer or integer vector operands");
6813 
6814   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6815   return false;
6816 }
6817 
6818 /// parseCompare
6819 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
6820 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
6821 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
6822                             unsigned Opc) {
6823   // parse the integer/fp comparison predicate.
6824   LocTy Loc;
6825   unsigned Pred;
6826   Value *LHS, *RHS;
6827   if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
6828       parseToken(lltok::comma, "expected ',' after compare value") ||
6829       parseValue(LHS->getType(), RHS, PFS))
6830     return true;
6831 
6832   if (Opc == Instruction::FCmp) {
6833     if (!LHS->getType()->isFPOrFPVectorTy())
6834       return error(Loc, "fcmp requires floating point operands");
6835     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6836   } else {
6837     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6838     if (!LHS->getType()->isIntOrIntVectorTy() &&
6839         !LHS->getType()->isPtrOrPtrVectorTy())
6840       return error(Loc, "icmp requires integer operands");
6841     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6842   }
6843   return false;
6844 }
6845 
6846 //===----------------------------------------------------------------------===//
6847 // Other Instructions.
6848 //===----------------------------------------------------------------------===//
6849 
6850 /// parseCast
6851 ///   ::= CastOpc TypeAndValue 'to' Type
6852 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
6853                          unsigned Opc) {
6854   LocTy Loc;
6855   Value *Op;
6856   Type *DestTy = nullptr;
6857   if (parseTypeAndValue(Op, Loc, PFS) ||
6858       parseToken(lltok::kw_to, "expected 'to' after cast value") ||
6859       parseType(DestTy))
6860     return true;
6861 
6862   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6863     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6864     return error(Loc, "invalid cast opcode for cast from '" +
6865                           getTypeString(Op->getType()) + "' to '" +
6866                           getTypeString(DestTy) + "'");
6867   }
6868   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6869   return false;
6870 }
6871 
6872 /// parseSelect
6873 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6874 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6875   LocTy Loc;
6876   Value *Op0, *Op1, *Op2;
6877   if (parseTypeAndValue(Op0, Loc, PFS) ||
6878       parseToken(lltok::comma, "expected ',' after select condition") ||
6879       parseTypeAndValue(Op1, PFS) ||
6880       parseToken(lltok::comma, "expected ',' after select value") ||
6881       parseTypeAndValue(Op2, PFS))
6882     return true;
6883 
6884   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6885     return error(Loc, Reason);
6886 
6887   Inst = SelectInst::Create(Op0, Op1, Op2);
6888   return false;
6889 }
6890 
6891 /// parseVAArg
6892 ///   ::= 'va_arg' TypeAndValue ',' Type
6893 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
6894   Value *Op;
6895   Type *EltTy = nullptr;
6896   LocTy TypeLoc;
6897   if (parseTypeAndValue(Op, PFS) ||
6898       parseToken(lltok::comma, "expected ',' after vaarg operand") ||
6899       parseType(EltTy, TypeLoc))
6900     return true;
6901 
6902   if (!EltTy->isFirstClassType())
6903     return error(TypeLoc, "va_arg requires operand with first class type");
6904 
6905   Inst = new VAArgInst(Op, EltTy);
6906   return false;
6907 }
6908 
6909 /// parseExtractElement
6910 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
6911 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6912   LocTy Loc;
6913   Value *Op0, *Op1;
6914   if (parseTypeAndValue(Op0, Loc, PFS) ||
6915       parseToken(lltok::comma, "expected ',' after extract value") ||
6916       parseTypeAndValue(Op1, PFS))
6917     return true;
6918 
6919   if (!ExtractElementInst::isValidOperands(Op0, Op1))
6920     return error(Loc, "invalid extractelement operands");
6921 
6922   Inst = ExtractElementInst::Create(Op0, Op1);
6923   return false;
6924 }
6925 
6926 /// parseInsertElement
6927 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6928 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6929   LocTy Loc;
6930   Value *Op0, *Op1, *Op2;
6931   if (parseTypeAndValue(Op0, Loc, PFS) ||
6932       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6933       parseTypeAndValue(Op1, PFS) ||
6934       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6935       parseTypeAndValue(Op2, PFS))
6936     return true;
6937 
6938   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6939     return error(Loc, "invalid insertelement operands");
6940 
6941   Inst = InsertElementInst::Create(Op0, Op1, Op2);
6942   return false;
6943 }
6944 
6945 /// parseShuffleVector
6946 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6947 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6948   LocTy Loc;
6949   Value *Op0, *Op1, *Op2;
6950   if (parseTypeAndValue(Op0, Loc, PFS) ||
6951       parseToken(lltok::comma, "expected ',' after shuffle mask") ||
6952       parseTypeAndValue(Op1, PFS) ||
6953       parseToken(lltok::comma, "expected ',' after shuffle value") ||
6954       parseTypeAndValue(Op2, PFS))
6955     return true;
6956 
6957   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6958     return error(Loc, "invalid shufflevector operands");
6959 
6960   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6961   return false;
6962 }
6963 
6964 /// parsePHI
6965 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6966 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6967   Type *Ty = nullptr;  LocTy TypeLoc;
6968   Value *Op0, *Op1;
6969 
6970   if (parseType(Ty, TypeLoc) ||
6971       parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6972       parseValue(Ty, Op0, PFS) ||
6973       parseToken(lltok::comma, "expected ',' after insertelement value") ||
6974       parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6975       parseToken(lltok::rsquare, "expected ']' in phi value list"))
6976     return true;
6977 
6978   bool AteExtraComma = false;
6979   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6980 
6981   while (true) {
6982     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6983 
6984     if (!EatIfPresent(lltok::comma))
6985       break;
6986 
6987     if (Lex.getKind() == lltok::MetadataVar) {
6988       AteExtraComma = true;
6989       break;
6990     }
6991 
6992     if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6993         parseValue(Ty, Op0, PFS) ||
6994         parseToken(lltok::comma, "expected ',' after insertelement value") ||
6995         parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6996         parseToken(lltok::rsquare, "expected ']' in phi value list"))
6997       return true;
6998   }
6999 
7000   if (!Ty->isFirstClassType())
7001     return error(TypeLoc, "phi node must have first class type");
7002 
7003   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7004   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7005     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7006   Inst = PN;
7007   return AteExtraComma ? InstExtraComma : InstNormal;
7008 }
7009 
7010 /// parseLandingPad
7011 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7012 /// Clause
7013 ///   ::= 'catch' TypeAndValue
7014 ///   ::= 'filter'
7015 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7016 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7017   Type *Ty = nullptr; LocTy TyLoc;
7018 
7019   if (parseType(Ty, TyLoc))
7020     return true;
7021 
7022   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7023   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7024 
7025   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7026     LandingPadInst::ClauseType CT;
7027     if (EatIfPresent(lltok::kw_catch))
7028       CT = LandingPadInst::Catch;
7029     else if (EatIfPresent(lltok::kw_filter))
7030       CT = LandingPadInst::Filter;
7031     else
7032       return tokError("expected 'catch' or 'filter' clause type");
7033 
7034     Value *V;
7035     LocTy VLoc;
7036     if (parseTypeAndValue(V, VLoc, PFS))
7037       return true;
7038 
7039     // A 'catch' type expects a non-array constant. A filter clause expects an
7040     // array constant.
7041     if (CT == LandingPadInst::Catch) {
7042       if (isa<ArrayType>(V->getType()))
7043         error(VLoc, "'catch' clause has an invalid type");
7044     } else {
7045       if (!isa<ArrayType>(V->getType()))
7046         error(VLoc, "'filter' clause has an invalid type");
7047     }
7048 
7049     Constant *CV = dyn_cast<Constant>(V);
7050     if (!CV)
7051       return error(VLoc, "clause argument must be a constant");
7052     LP->addClause(CV);
7053   }
7054 
7055   Inst = LP.release();
7056   return false;
7057 }
7058 
7059 /// parseFreeze
7060 ///   ::= 'freeze' Type Value
7061 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7062   LocTy Loc;
7063   Value *Op;
7064   if (parseTypeAndValue(Op, Loc, PFS))
7065     return true;
7066 
7067   Inst = new FreezeInst(Op);
7068   return false;
7069 }
7070 
7071 /// parseCall
7072 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
7073 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7074 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7075 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7076 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7077 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7078 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
7079 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
7080 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7081                          CallInst::TailCallKind TCK) {
7082   AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7083   std::vector<unsigned> FwdRefAttrGrps;
7084   LocTy BuiltinLoc;
7085   unsigned CallAddrSpace;
7086   unsigned CC;
7087   Type *RetType = nullptr;
7088   LocTy RetTypeLoc;
7089   ValID CalleeID;
7090   SmallVector<ParamInfo, 16> ArgList;
7091   SmallVector<OperandBundleDef, 2> BundleList;
7092   LocTy CallLoc = Lex.getLoc();
7093 
7094   if (TCK != CallInst::TCK_None &&
7095       parseToken(lltok::kw_call,
7096                  "expected 'tail call', 'musttail call', or 'notail call'"))
7097     return true;
7098 
7099   FastMathFlags FMF = EatFastMathFlagsIfPresent();
7100 
7101   if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7102       parseOptionalProgramAddrSpace(CallAddrSpace) ||
7103       parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7104       parseValID(CalleeID, &PFS) ||
7105       parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7106                          PFS.getFunction().isVarArg()) ||
7107       parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7108       parseOptionalOperandBundles(BundleList, PFS))
7109     return true;
7110 
7111   // If RetType is a non-function pointer type, then this is the short syntax
7112   // for the call, which means that RetType is just the return type.  Infer the
7113   // rest of the function argument types from the arguments that are present.
7114   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
7115   if (!Ty) {
7116     // Pull out the types of all of the arguments...
7117     std::vector<Type*> ParamTypes;
7118     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7119       ParamTypes.push_back(ArgList[i].V->getType());
7120 
7121     if (!FunctionType::isValidReturnType(RetType))
7122       return error(RetTypeLoc, "Invalid result type for LLVM function");
7123 
7124     Ty = FunctionType::get(RetType, ParamTypes, false);
7125   }
7126 
7127   CalleeID.FTy = Ty;
7128 
7129   // Look up the callee.
7130   Value *Callee;
7131   if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7132                           &PFS))
7133     return true;
7134 
7135   // Set up the Attribute for the function.
7136   SmallVector<AttributeSet, 8> Attrs;
7137 
7138   SmallVector<Value*, 8> Args;
7139 
7140   // Loop through FunctionType's arguments and ensure they are specified
7141   // correctly.  Also, gather any parameter attributes.
7142   FunctionType::param_iterator I = Ty->param_begin();
7143   FunctionType::param_iterator E = Ty->param_end();
7144   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7145     Type *ExpectedTy = nullptr;
7146     if (I != E) {
7147       ExpectedTy = *I++;
7148     } else if (!Ty->isVarArg()) {
7149       return error(ArgList[i].Loc, "too many arguments specified");
7150     }
7151 
7152     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7153       return error(ArgList[i].Loc, "argument is not of expected type '" +
7154                                        getTypeString(ExpectedTy) + "'");
7155     Args.push_back(ArgList[i].V);
7156     Attrs.push_back(ArgList[i].Attrs);
7157   }
7158 
7159   if (I != E)
7160     return error(CallLoc, "not enough parameters specified for call");
7161 
7162   if (FnAttrs.hasAlignmentAttr())
7163     return error(CallLoc, "call instructions may not have an alignment");
7164 
7165   // Finish off the Attribute and check them
7166   AttributeList PAL =
7167       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7168                          AttributeSet::get(Context, RetAttrs), Attrs);
7169 
7170   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7171   CI->setTailCallKind(TCK);
7172   CI->setCallingConv(CC);
7173   if (FMF.any()) {
7174     if (!isa<FPMathOperator>(CI)) {
7175       CI->deleteValue();
7176       return error(CallLoc, "fast-math-flags specified for call without "
7177                             "floating-point scalar or vector return type");
7178     }
7179     CI->setFastMathFlags(FMF);
7180   }
7181   CI->setAttributes(PAL);
7182   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7183   Inst = CI;
7184   return false;
7185 }
7186 
7187 //===----------------------------------------------------------------------===//
7188 // Memory Instructions.
7189 //===----------------------------------------------------------------------===//
7190 
7191 /// parseAlloc
7192 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7193 ///       (',' 'align' i32)? (',', 'addrspace(n))?
7194 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7195   Value *Size = nullptr;
7196   LocTy SizeLoc, TyLoc, ASLoc;
7197   MaybeAlign Alignment;
7198   unsigned AddrSpace = 0;
7199   Type *Ty = nullptr;
7200 
7201   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7202   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7203 
7204   if (parseType(Ty, TyLoc))
7205     return true;
7206 
7207   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7208     return error(TyLoc, "invalid type for alloca");
7209 
7210   bool AteExtraComma = false;
7211   if (EatIfPresent(lltok::comma)) {
7212     if (Lex.getKind() == lltok::kw_align) {
7213       if (parseOptionalAlignment(Alignment))
7214         return true;
7215       if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7216         return true;
7217     } else if (Lex.getKind() == lltok::kw_addrspace) {
7218       ASLoc = Lex.getLoc();
7219       if (parseOptionalAddrSpace(AddrSpace))
7220         return true;
7221     } else if (Lex.getKind() == lltok::MetadataVar) {
7222       AteExtraComma = true;
7223     } else {
7224       if (parseTypeAndValue(Size, SizeLoc, PFS))
7225         return true;
7226       if (EatIfPresent(lltok::comma)) {
7227         if (Lex.getKind() == lltok::kw_align) {
7228           if (parseOptionalAlignment(Alignment))
7229             return true;
7230           if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7231             return true;
7232         } else if (Lex.getKind() == lltok::kw_addrspace) {
7233           ASLoc = Lex.getLoc();
7234           if (parseOptionalAddrSpace(AddrSpace))
7235             return true;
7236         } else if (Lex.getKind() == lltok::MetadataVar) {
7237           AteExtraComma = true;
7238         }
7239       }
7240     }
7241   }
7242 
7243   if (Size && !Size->getType()->isIntegerTy())
7244     return error(SizeLoc, "element count must have integer type");
7245 
7246   SmallPtrSet<Type *, 4> Visited;
7247   if (!Alignment && !Ty->isSized(&Visited))
7248     return error(TyLoc, "Cannot allocate unsized type");
7249   if (!Alignment)
7250     Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7251   AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7252   AI->setUsedWithInAlloca(IsInAlloca);
7253   AI->setSwiftError(IsSwiftError);
7254   Inst = AI;
7255   return AteExtraComma ? InstExtraComma : InstNormal;
7256 }
7257 
7258 /// parseLoad
7259 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7260 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
7261 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7262 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7263   Value *Val; LocTy Loc;
7264   MaybeAlign Alignment;
7265   bool AteExtraComma = false;
7266   bool isAtomic = false;
7267   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7268   SyncScope::ID SSID = SyncScope::System;
7269 
7270   if (Lex.getKind() == lltok::kw_atomic) {
7271     isAtomic = true;
7272     Lex.Lex();
7273   }
7274 
7275   bool isVolatile = false;
7276   if (Lex.getKind() == lltok::kw_volatile) {
7277     isVolatile = true;
7278     Lex.Lex();
7279   }
7280 
7281   Type *Ty;
7282   LocTy ExplicitTypeLoc = Lex.getLoc();
7283   if (parseType(Ty) ||
7284       parseToken(lltok::comma, "expected comma after load's type") ||
7285       parseTypeAndValue(Val, Loc, PFS) ||
7286       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7287       parseOptionalCommaAlign(Alignment, AteExtraComma))
7288     return true;
7289 
7290   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7291     return error(Loc, "load operand must be a pointer to a first class type");
7292   if (isAtomic && !Alignment)
7293     return error(Loc, "atomic load must have explicit non-zero alignment");
7294   if (Ordering == AtomicOrdering::Release ||
7295       Ordering == AtomicOrdering::AcquireRelease)
7296     return error(Loc, "atomic load cannot use Release ordering");
7297 
7298   if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
7299     return error(
7300         ExplicitTypeLoc,
7301         typeComparisonErrorMessage(
7302             "explicit pointee type doesn't match operand's pointee type", Ty,
7303             Val->getType()->getNonOpaquePointerElementType()));
7304   }
7305   SmallPtrSet<Type *, 4> Visited;
7306   if (!Alignment && !Ty->isSized(&Visited))
7307     return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7308   if (!Alignment)
7309     Alignment = M->getDataLayout().getABITypeAlign(Ty);
7310   Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7311   return AteExtraComma ? InstExtraComma : InstNormal;
7312 }
7313 
7314 /// parseStore
7315 
7316 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7317 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7318 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
7319 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7320   Value *Val, *Ptr; LocTy Loc, PtrLoc;
7321   MaybeAlign Alignment;
7322   bool AteExtraComma = false;
7323   bool isAtomic = false;
7324   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7325   SyncScope::ID SSID = SyncScope::System;
7326 
7327   if (Lex.getKind() == lltok::kw_atomic) {
7328     isAtomic = true;
7329     Lex.Lex();
7330   }
7331 
7332   bool isVolatile = false;
7333   if (Lex.getKind() == lltok::kw_volatile) {
7334     isVolatile = true;
7335     Lex.Lex();
7336   }
7337 
7338   if (parseTypeAndValue(Val, Loc, PFS) ||
7339       parseToken(lltok::comma, "expected ',' after store operand") ||
7340       parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7341       parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7342       parseOptionalCommaAlign(Alignment, AteExtraComma))
7343     return true;
7344 
7345   if (!Ptr->getType()->isPointerTy())
7346     return error(PtrLoc, "store operand must be a pointer");
7347   if (!Val->getType()->isFirstClassType())
7348     return error(Loc, "store operand must be a first class value");
7349   if (!cast<PointerType>(Ptr->getType())
7350            ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7351     return error(Loc, "stored value and pointer type do not match");
7352   if (isAtomic && !Alignment)
7353     return error(Loc, "atomic store must have explicit non-zero alignment");
7354   if (Ordering == AtomicOrdering::Acquire ||
7355       Ordering == AtomicOrdering::AcquireRelease)
7356     return error(Loc, "atomic store cannot use Acquire ordering");
7357   SmallPtrSet<Type *, 4> Visited;
7358   if (!Alignment && !Val->getType()->isSized(&Visited))
7359     return error(Loc, "storing unsized types is not allowed");
7360   if (!Alignment)
7361     Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7362 
7363   Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7364   return AteExtraComma ? InstExtraComma : InstNormal;
7365 }
7366 
7367 /// parseCmpXchg
7368 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7369 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7370 ///       'Align'?
7371 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7372   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7373   bool AteExtraComma = false;
7374   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7375   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7376   SyncScope::ID SSID = SyncScope::System;
7377   bool isVolatile = false;
7378   bool isWeak = false;
7379   MaybeAlign Alignment;
7380 
7381   if (EatIfPresent(lltok::kw_weak))
7382     isWeak = true;
7383 
7384   if (EatIfPresent(lltok::kw_volatile))
7385     isVolatile = true;
7386 
7387   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7388       parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7389       parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7390       parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7391       parseTypeAndValue(New, NewLoc, PFS) ||
7392       parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7393       parseOrdering(FailureOrdering) ||
7394       parseOptionalCommaAlign(Alignment, AteExtraComma))
7395     return true;
7396 
7397   if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7398     return tokError("invalid cmpxchg success ordering");
7399   if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7400     return tokError("invalid cmpxchg failure ordering");
7401   if (!Ptr->getType()->isPointerTy())
7402     return error(PtrLoc, "cmpxchg operand must be a pointer");
7403   if (!cast<PointerType>(Ptr->getType())
7404            ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
7405     return error(CmpLoc, "compare value and pointer type do not match");
7406   if (!cast<PointerType>(Ptr->getType())
7407            ->isOpaqueOrPointeeTypeMatches(New->getType()))
7408     return error(NewLoc, "new value and pointer type do not match");
7409   if (Cmp->getType() != New->getType())
7410     return error(NewLoc, "compare value and new value type do not match");
7411   if (!New->getType()->isFirstClassType())
7412     return error(NewLoc, "cmpxchg operand must be a first class value");
7413 
7414   const Align DefaultAlignment(
7415       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7416           Cmp->getType()));
7417 
7418   AtomicCmpXchgInst *CXI =
7419       new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
7420                             SuccessOrdering, FailureOrdering, SSID);
7421   CXI->setVolatile(isVolatile);
7422   CXI->setWeak(isWeak);
7423 
7424   Inst = CXI;
7425   return AteExtraComma ? InstExtraComma : InstNormal;
7426 }
7427 
7428 /// parseAtomicRMW
7429 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7430 ///       'singlethread'? AtomicOrdering
7431 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7432   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7433   bool AteExtraComma = false;
7434   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7435   SyncScope::ID SSID = SyncScope::System;
7436   bool isVolatile = false;
7437   bool IsFP = false;
7438   AtomicRMWInst::BinOp Operation;
7439   MaybeAlign Alignment;
7440 
7441   if (EatIfPresent(lltok::kw_volatile))
7442     isVolatile = true;
7443 
7444   switch (Lex.getKind()) {
7445   default:
7446     return tokError("expected binary operation in atomicrmw");
7447   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7448   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7449   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7450   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7451   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7452   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7453   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7454   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7455   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7456   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7457   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7458   case lltok::kw_fadd:
7459     Operation = AtomicRMWInst::FAdd;
7460     IsFP = true;
7461     break;
7462   case lltok::kw_fsub:
7463     Operation = AtomicRMWInst::FSub;
7464     IsFP = true;
7465     break;
7466   case lltok::kw_fmax:
7467     Operation = AtomicRMWInst::FMax;
7468     IsFP = true;
7469     break;
7470   case lltok::kw_fmin:
7471     Operation = AtomicRMWInst::FMin;
7472     IsFP = true;
7473     break;
7474   }
7475   Lex.Lex();  // Eat the operation.
7476 
7477   if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7478       parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7479       parseTypeAndValue(Val, ValLoc, PFS) ||
7480       parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7481       parseOptionalCommaAlign(Alignment, AteExtraComma))
7482     return true;
7483 
7484   if (Ordering == AtomicOrdering::Unordered)
7485     return tokError("atomicrmw cannot be unordered");
7486   if (!Ptr->getType()->isPointerTy())
7487     return error(PtrLoc, "atomicrmw operand must be a pointer");
7488   if (!cast<PointerType>(Ptr->getType())
7489            ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7490     return error(ValLoc, "atomicrmw value and pointer type do not match");
7491 
7492   if (Operation == AtomicRMWInst::Xchg) {
7493     if (!Val->getType()->isIntegerTy() &&
7494         !Val->getType()->isFloatingPointTy() &&
7495         !Val->getType()->isPointerTy()) {
7496       return error(
7497           ValLoc,
7498           "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7499               " operand must be an integer, floating point, or pointer type");
7500     }
7501   } else if (IsFP) {
7502     if (!Val->getType()->isFloatingPointTy()) {
7503       return error(ValLoc, "atomicrmw " +
7504                                AtomicRMWInst::getOperationName(Operation) +
7505                                " operand must be a floating point type");
7506     }
7507   } else {
7508     if (!Val->getType()->isIntegerTy()) {
7509       return error(ValLoc, "atomicrmw " +
7510                                AtomicRMWInst::getOperationName(Operation) +
7511                                " operand must be an integer");
7512     }
7513   }
7514 
7515   unsigned Size =
7516       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
7517           Val->getType());
7518   if (Size < 8 || (Size & (Size - 1)))
7519     return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7520                          " integer");
7521   const Align DefaultAlignment(
7522       PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7523           Val->getType()));
7524   AtomicRMWInst *RMWI =
7525       new AtomicRMWInst(Operation, Ptr, Val,
7526                         Alignment.value_or(DefaultAlignment), Ordering, SSID);
7527   RMWI->setVolatile(isVolatile);
7528   Inst = RMWI;
7529   return AteExtraComma ? InstExtraComma : InstNormal;
7530 }
7531 
7532 /// parseFence
7533 ///   ::= 'fence' 'singlethread'? AtomicOrdering
7534 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7535   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7536   SyncScope::ID SSID = SyncScope::System;
7537   if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7538     return true;
7539 
7540   if (Ordering == AtomicOrdering::Unordered)
7541     return tokError("fence cannot be unordered");
7542   if (Ordering == AtomicOrdering::Monotonic)
7543     return tokError("fence cannot be monotonic");
7544 
7545   Inst = new FenceInst(Context, Ordering, SSID);
7546   return InstNormal;
7547 }
7548 
7549 /// parseGetElementPtr
7550 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7551 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7552   Value *Ptr = nullptr;
7553   Value *Val = nullptr;
7554   LocTy Loc, EltLoc;
7555 
7556   bool InBounds = EatIfPresent(lltok::kw_inbounds);
7557 
7558   Type *Ty = nullptr;
7559   LocTy ExplicitTypeLoc = Lex.getLoc();
7560   if (parseType(Ty) ||
7561       parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7562       parseTypeAndValue(Ptr, Loc, PFS))
7563     return true;
7564 
7565   Type *BaseType = Ptr->getType();
7566   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7567   if (!BasePointerType)
7568     return error(Loc, "base of getelementptr must be a pointer");
7569 
7570   if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
7571     return error(
7572         ExplicitTypeLoc,
7573         typeComparisonErrorMessage(
7574             "explicit pointee type doesn't match operand's pointee type", Ty,
7575             BasePointerType->getNonOpaquePointerElementType()));
7576   }
7577 
7578   SmallVector<Value*, 16> Indices;
7579   bool AteExtraComma = false;
7580   // GEP returns a vector of pointers if at least one of parameters is a vector.
7581   // All vector parameters should have the same vector width.
7582   ElementCount GEPWidth = BaseType->isVectorTy()
7583                               ? cast<VectorType>(BaseType)->getElementCount()
7584                               : ElementCount::getFixed(0);
7585 
7586   while (EatIfPresent(lltok::comma)) {
7587     if (Lex.getKind() == lltok::MetadataVar) {
7588       AteExtraComma = true;
7589       break;
7590     }
7591     if (parseTypeAndValue(Val, EltLoc, PFS))
7592       return true;
7593     if (!Val->getType()->isIntOrIntVectorTy())
7594       return error(EltLoc, "getelementptr index must be an integer");
7595 
7596     if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7597       ElementCount ValNumEl = ValVTy->getElementCount();
7598       if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7599         return error(
7600             EltLoc,
7601             "getelementptr vector index has a wrong number of elements");
7602       GEPWidth = ValNumEl;
7603     }
7604     Indices.push_back(Val);
7605   }
7606 
7607   SmallPtrSet<Type*, 4> Visited;
7608   if (!Indices.empty() && !Ty->isSized(&Visited))
7609     return error(Loc, "base element of getelementptr must be sized");
7610 
7611   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7612     return error(Loc, "invalid getelementptr indices");
7613   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7614   if (InBounds)
7615     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7616   return AteExtraComma ? InstExtraComma : InstNormal;
7617 }
7618 
7619 /// parseExtractValue
7620 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
7621 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7622   Value *Val; LocTy Loc;
7623   SmallVector<unsigned, 4> Indices;
7624   bool AteExtraComma;
7625   if (parseTypeAndValue(Val, Loc, PFS) ||
7626       parseIndexList(Indices, AteExtraComma))
7627     return true;
7628 
7629   if (!Val->getType()->isAggregateType())
7630     return error(Loc, "extractvalue operand must be aggregate type");
7631 
7632   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7633     return error(Loc, "invalid indices for extractvalue");
7634   Inst = ExtractValueInst::Create(Val, Indices);
7635   return AteExtraComma ? InstExtraComma : InstNormal;
7636 }
7637 
7638 /// parseInsertValue
7639 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7640 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7641   Value *Val0, *Val1; LocTy Loc0, Loc1;
7642   SmallVector<unsigned, 4> Indices;
7643   bool AteExtraComma;
7644   if (parseTypeAndValue(Val0, Loc0, PFS) ||
7645       parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7646       parseTypeAndValue(Val1, Loc1, PFS) ||
7647       parseIndexList(Indices, AteExtraComma))
7648     return true;
7649 
7650   if (!Val0->getType()->isAggregateType())
7651     return error(Loc0, "insertvalue operand must be aggregate type");
7652 
7653   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7654   if (!IndexedType)
7655     return error(Loc0, "invalid indices for insertvalue");
7656   if (IndexedType != Val1->getType())
7657     return error(Loc1, "insertvalue operand and field disagree in type: '" +
7658                            getTypeString(Val1->getType()) + "' instead of '" +
7659                            getTypeString(IndexedType) + "'");
7660   Inst = InsertValueInst::Create(Val0, Val1, Indices);
7661   return AteExtraComma ? InstExtraComma : InstNormal;
7662 }
7663 
7664 //===----------------------------------------------------------------------===//
7665 // Embedded metadata.
7666 //===----------------------------------------------------------------------===//
7667 
7668 /// parseMDNodeVector
7669 ///   ::= { Element (',' Element)* }
7670 /// Element
7671 ///   ::= 'null' | TypeAndValue
7672 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7673   if (parseToken(lltok::lbrace, "expected '{' here"))
7674     return true;
7675 
7676   // Check for an empty list.
7677   if (EatIfPresent(lltok::rbrace))
7678     return false;
7679 
7680   do {
7681     // Null is a special case since it is typeless.
7682     if (EatIfPresent(lltok::kw_null)) {
7683       Elts.push_back(nullptr);
7684       continue;
7685     }
7686 
7687     Metadata *MD;
7688     if (parseMetadata(MD, nullptr))
7689       return true;
7690     Elts.push_back(MD);
7691   } while (EatIfPresent(lltok::comma));
7692 
7693   return parseToken(lltok::rbrace, "expected end of metadata node");
7694 }
7695 
7696 //===----------------------------------------------------------------------===//
7697 // Use-list order directives.
7698 //===----------------------------------------------------------------------===//
7699 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7700                                 SMLoc Loc) {
7701   if (V->use_empty())
7702     return error(Loc, "value has no uses");
7703 
7704   unsigned NumUses = 0;
7705   SmallDenseMap<const Use *, unsigned, 16> Order;
7706   for (const Use &U : V->uses()) {
7707     if (++NumUses > Indexes.size())
7708       break;
7709     Order[&U] = Indexes[NumUses - 1];
7710   }
7711   if (NumUses < 2)
7712     return error(Loc, "value only has one use");
7713   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7714     return error(Loc,
7715                  "wrong number of indexes, expected " + Twine(V->getNumUses()));
7716 
7717   V->sortUseList([&](const Use &L, const Use &R) {
7718     return Order.lookup(&L) < Order.lookup(&R);
7719   });
7720   return false;
7721 }
7722 
7723 /// parseUseListOrderIndexes
7724 ///   ::= '{' uint32 (',' uint32)+ '}'
7725 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7726   SMLoc Loc = Lex.getLoc();
7727   if (parseToken(lltok::lbrace, "expected '{' here"))
7728     return true;
7729   if (Lex.getKind() == lltok::rbrace)
7730     return Lex.Error("expected non-empty list of uselistorder indexes");
7731 
7732   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
7733   // indexes should be distinct numbers in the range [0, size-1], and should
7734   // not be in order.
7735   unsigned Offset = 0;
7736   unsigned Max = 0;
7737   bool IsOrdered = true;
7738   assert(Indexes.empty() && "Expected empty order vector");
7739   do {
7740     unsigned Index;
7741     if (parseUInt32(Index))
7742       return true;
7743 
7744     // Update consistency checks.
7745     Offset += Index - Indexes.size();
7746     Max = std::max(Max, Index);
7747     IsOrdered &= Index == Indexes.size();
7748 
7749     Indexes.push_back(Index);
7750   } while (EatIfPresent(lltok::comma));
7751 
7752   if (parseToken(lltok::rbrace, "expected '}' here"))
7753     return true;
7754 
7755   if (Indexes.size() < 2)
7756     return error(Loc, "expected >= 2 uselistorder indexes");
7757   if (Offset != 0 || Max >= Indexes.size())
7758     return error(Loc,
7759                  "expected distinct uselistorder indexes in range [0, size)");
7760   if (IsOrdered)
7761     return error(Loc, "expected uselistorder indexes to change the order");
7762 
7763   return false;
7764 }
7765 
7766 /// parseUseListOrder
7767 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7768 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7769   SMLoc Loc = Lex.getLoc();
7770   if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7771     return true;
7772 
7773   Value *V;
7774   SmallVector<unsigned, 16> Indexes;
7775   if (parseTypeAndValue(V, PFS) ||
7776       parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7777       parseUseListOrderIndexes(Indexes))
7778     return true;
7779 
7780   return sortUseListOrder(V, Indexes, Loc);
7781 }
7782 
7783 /// parseUseListOrderBB
7784 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7785 bool LLParser::parseUseListOrderBB() {
7786   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7787   SMLoc Loc = Lex.getLoc();
7788   Lex.Lex();
7789 
7790   ValID Fn, Label;
7791   SmallVector<unsigned, 16> Indexes;
7792   if (parseValID(Fn, /*PFS=*/nullptr) ||
7793       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7794       parseValID(Label, /*PFS=*/nullptr) ||
7795       parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7796       parseUseListOrderIndexes(Indexes))
7797     return true;
7798 
7799   // Check the function.
7800   GlobalValue *GV;
7801   if (Fn.Kind == ValID::t_GlobalName)
7802     GV = M->getNamedValue(Fn.StrVal);
7803   else if (Fn.Kind == ValID::t_GlobalID)
7804     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7805   else
7806     return error(Fn.Loc, "expected function name in uselistorder_bb");
7807   if (!GV)
7808     return error(Fn.Loc,
7809                  "invalid function forward reference in uselistorder_bb");
7810   auto *F = dyn_cast<Function>(GV);
7811   if (!F)
7812     return error(Fn.Loc, "expected function name in uselistorder_bb");
7813   if (F->isDeclaration())
7814     return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7815 
7816   // Check the basic block.
7817   if (Label.Kind == ValID::t_LocalID)
7818     return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7819   if (Label.Kind != ValID::t_LocalName)
7820     return error(Label.Loc, "expected basic block name in uselistorder_bb");
7821   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7822   if (!V)
7823     return error(Label.Loc, "invalid basic block in uselistorder_bb");
7824   if (!isa<BasicBlock>(V))
7825     return error(Label.Loc, "expected basic block in uselistorder_bb");
7826 
7827   return sortUseListOrder(V, Indexes, Loc);
7828 }
7829 
7830 /// ModuleEntry
7831 ///   ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7832 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7833 bool LLParser::parseModuleEntry(unsigned ID) {
7834   assert(Lex.getKind() == lltok::kw_module);
7835   Lex.Lex();
7836 
7837   std::string Path;
7838   if (parseToken(lltok::colon, "expected ':' here") ||
7839       parseToken(lltok::lparen, "expected '(' here") ||
7840       parseToken(lltok::kw_path, "expected 'path' here") ||
7841       parseToken(lltok::colon, "expected ':' here") ||
7842       parseStringConstant(Path) ||
7843       parseToken(lltok::comma, "expected ',' here") ||
7844       parseToken(lltok::kw_hash, "expected 'hash' here") ||
7845       parseToken(lltok::colon, "expected ':' here") ||
7846       parseToken(lltok::lparen, "expected '(' here"))
7847     return true;
7848 
7849   ModuleHash Hash;
7850   if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
7851       parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
7852       parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
7853       parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
7854       parseUInt32(Hash[4]))
7855     return true;
7856 
7857   if (parseToken(lltok::rparen, "expected ')' here") ||
7858       parseToken(lltok::rparen, "expected ')' here"))
7859     return true;
7860 
7861   auto ModuleEntry = Index->addModule(Path, ID, Hash);
7862   ModuleIdMap[ID] = ModuleEntry->first();
7863 
7864   return false;
7865 }
7866 
7867 /// TypeIdEntry
7868 ///   ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7869 bool LLParser::parseTypeIdEntry(unsigned ID) {
7870   assert(Lex.getKind() == lltok::kw_typeid);
7871   Lex.Lex();
7872 
7873   std::string Name;
7874   if (parseToken(lltok::colon, "expected ':' here") ||
7875       parseToken(lltok::lparen, "expected '(' here") ||
7876       parseToken(lltok::kw_name, "expected 'name' here") ||
7877       parseToken(lltok::colon, "expected ':' here") ||
7878       parseStringConstant(Name))
7879     return true;
7880 
7881   TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7882   if (parseToken(lltok::comma, "expected ',' here") ||
7883       parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
7884     return true;
7885 
7886   // Check if this ID was forward referenced, and if so, update the
7887   // corresponding GUIDs.
7888   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7889   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7890     for (auto TIDRef : FwdRefTIDs->second) {
7891       assert(!*TIDRef.first &&
7892              "Forward referenced type id GUID expected to be 0");
7893       *TIDRef.first = GlobalValue::getGUID(Name);
7894     }
7895     ForwardRefTypeIds.erase(FwdRefTIDs);
7896   }
7897 
7898   return false;
7899 }
7900 
7901 /// TypeIdSummary
7902 ///   ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7903 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
7904   if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
7905       parseToken(lltok::colon, "expected ':' here") ||
7906       parseToken(lltok::lparen, "expected '(' here") ||
7907       parseTypeTestResolution(TIS.TTRes))
7908     return true;
7909 
7910   if (EatIfPresent(lltok::comma)) {
7911     // Expect optional wpdResolutions field
7912     if (parseOptionalWpdResolutions(TIS.WPDRes))
7913       return true;
7914   }
7915 
7916   if (parseToken(lltok::rparen, "expected ')' here"))
7917     return true;
7918 
7919   return false;
7920 }
7921 
7922 static ValueInfo EmptyVI =
7923     ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7924 
7925 /// TypeIdCompatibleVtableEntry
7926 ///   ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7927 ///   TypeIdCompatibleVtableInfo
7928 ///   ')'
7929 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
7930   assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7931   Lex.Lex();
7932 
7933   std::string Name;
7934   if (parseToken(lltok::colon, "expected ':' here") ||
7935       parseToken(lltok::lparen, "expected '(' here") ||
7936       parseToken(lltok::kw_name, "expected 'name' here") ||
7937       parseToken(lltok::colon, "expected ':' here") ||
7938       parseStringConstant(Name))
7939     return true;
7940 
7941   TypeIdCompatibleVtableInfo &TI =
7942       Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7943   if (parseToken(lltok::comma, "expected ',' here") ||
7944       parseToken(lltok::kw_summary, "expected 'summary' here") ||
7945       parseToken(lltok::colon, "expected ':' here") ||
7946       parseToken(lltok::lparen, "expected '(' here"))
7947     return true;
7948 
7949   IdToIndexMapType IdToIndexMap;
7950   // parse each call edge
7951   do {
7952     uint64_t Offset;
7953     if (parseToken(lltok::lparen, "expected '(' here") ||
7954         parseToken(lltok::kw_offset, "expected 'offset' here") ||
7955         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7956         parseToken(lltok::comma, "expected ',' here"))
7957       return true;
7958 
7959     LocTy Loc = Lex.getLoc();
7960     unsigned GVId;
7961     ValueInfo VI;
7962     if (parseGVReference(VI, GVId))
7963       return true;
7964 
7965     // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7966     // forward reference. We will save the location of the ValueInfo needing an
7967     // update, but can only do so once the std::vector is finalized.
7968     if (VI == EmptyVI)
7969       IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7970     TI.push_back({Offset, VI});
7971 
7972     if (parseToken(lltok::rparen, "expected ')' in call"))
7973       return true;
7974   } while (EatIfPresent(lltok::comma));
7975 
7976   // Now that the TI vector is finalized, it is safe to save the locations
7977   // of any forward GV references that need updating later.
7978   for (auto I : IdToIndexMap) {
7979     auto &Infos = ForwardRefValueInfos[I.first];
7980     for (auto P : I.second) {
7981       assert(TI[P.first].VTableVI == EmptyVI &&
7982              "Forward referenced ValueInfo expected to be empty");
7983       Infos.emplace_back(&TI[P.first].VTableVI, P.second);
7984     }
7985   }
7986 
7987   if (parseToken(lltok::rparen, "expected ')' here") ||
7988       parseToken(lltok::rparen, "expected ')' here"))
7989     return true;
7990 
7991   // Check if this ID was forward referenced, and if so, update the
7992   // corresponding GUIDs.
7993   auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7994   if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7995     for (auto TIDRef : FwdRefTIDs->second) {
7996       assert(!*TIDRef.first &&
7997              "Forward referenced type id GUID expected to be 0");
7998       *TIDRef.first = GlobalValue::getGUID(Name);
7999     }
8000     ForwardRefTypeIds.erase(FwdRefTIDs);
8001   }
8002 
8003   return false;
8004 }
8005 
8006 /// TypeTestResolution
8007 ///   ::= 'typeTestRes' ':' '(' 'kind' ':'
8008 ///         ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8009 ///         'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8010 ///         [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8011 ///         [',' 'inlinesBits' ':' UInt64]? ')'
8012 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8013   if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8014       parseToken(lltok::colon, "expected ':' here") ||
8015       parseToken(lltok::lparen, "expected '(' here") ||
8016       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8017       parseToken(lltok::colon, "expected ':' here"))
8018     return true;
8019 
8020   switch (Lex.getKind()) {
8021   case lltok::kw_unknown:
8022     TTRes.TheKind = TypeTestResolution::Unknown;
8023     break;
8024   case lltok::kw_unsat:
8025     TTRes.TheKind = TypeTestResolution::Unsat;
8026     break;
8027   case lltok::kw_byteArray:
8028     TTRes.TheKind = TypeTestResolution::ByteArray;
8029     break;
8030   case lltok::kw_inline:
8031     TTRes.TheKind = TypeTestResolution::Inline;
8032     break;
8033   case lltok::kw_single:
8034     TTRes.TheKind = TypeTestResolution::Single;
8035     break;
8036   case lltok::kw_allOnes:
8037     TTRes.TheKind = TypeTestResolution::AllOnes;
8038     break;
8039   default:
8040     return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8041   }
8042   Lex.Lex();
8043 
8044   if (parseToken(lltok::comma, "expected ',' here") ||
8045       parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8046       parseToken(lltok::colon, "expected ':' here") ||
8047       parseUInt32(TTRes.SizeM1BitWidth))
8048     return true;
8049 
8050   // parse optional fields
8051   while (EatIfPresent(lltok::comma)) {
8052     switch (Lex.getKind()) {
8053     case lltok::kw_alignLog2:
8054       Lex.Lex();
8055       if (parseToken(lltok::colon, "expected ':'") ||
8056           parseUInt64(TTRes.AlignLog2))
8057         return true;
8058       break;
8059     case lltok::kw_sizeM1:
8060       Lex.Lex();
8061       if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8062         return true;
8063       break;
8064     case lltok::kw_bitMask: {
8065       unsigned Val;
8066       Lex.Lex();
8067       if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8068         return true;
8069       assert(Val <= 0xff);
8070       TTRes.BitMask = (uint8_t)Val;
8071       break;
8072     }
8073     case lltok::kw_inlineBits:
8074       Lex.Lex();
8075       if (parseToken(lltok::colon, "expected ':'") ||
8076           parseUInt64(TTRes.InlineBits))
8077         return true;
8078       break;
8079     default:
8080       return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8081     }
8082   }
8083 
8084   if (parseToken(lltok::rparen, "expected ')' here"))
8085     return true;
8086 
8087   return false;
8088 }
8089 
8090 /// OptionalWpdResolutions
8091 ///   ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8092 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8093 bool LLParser::parseOptionalWpdResolutions(
8094     std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8095   if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8096       parseToken(lltok::colon, "expected ':' here") ||
8097       parseToken(lltok::lparen, "expected '(' here"))
8098     return true;
8099 
8100   do {
8101     uint64_t Offset;
8102     WholeProgramDevirtResolution WPDRes;
8103     if (parseToken(lltok::lparen, "expected '(' here") ||
8104         parseToken(lltok::kw_offset, "expected 'offset' here") ||
8105         parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8106         parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8107         parseToken(lltok::rparen, "expected ')' here"))
8108       return true;
8109     WPDResMap[Offset] = WPDRes;
8110   } while (EatIfPresent(lltok::comma));
8111 
8112   if (parseToken(lltok::rparen, "expected ')' here"))
8113     return true;
8114 
8115   return false;
8116 }
8117 
8118 /// WpdRes
8119 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8120 ///         [',' OptionalResByArg]? ')'
8121 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8122 ///         ',' 'singleImplName' ':' STRINGCONSTANT ','
8123 ///         [',' OptionalResByArg]? ')'
8124 ///   ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8125 ///         [',' OptionalResByArg]? ')'
8126 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8127   if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8128       parseToken(lltok::colon, "expected ':' here") ||
8129       parseToken(lltok::lparen, "expected '(' here") ||
8130       parseToken(lltok::kw_kind, "expected 'kind' here") ||
8131       parseToken(lltok::colon, "expected ':' here"))
8132     return true;
8133 
8134   switch (Lex.getKind()) {
8135   case lltok::kw_indir:
8136     WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8137     break;
8138   case lltok::kw_singleImpl:
8139     WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8140     break;
8141   case lltok::kw_branchFunnel:
8142     WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8143     break;
8144   default:
8145     return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8146   }
8147   Lex.Lex();
8148 
8149   // parse optional fields
8150   while (EatIfPresent(lltok::comma)) {
8151     switch (Lex.getKind()) {
8152     case lltok::kw_singleImplName:
8153       Lex.Lex();
8154       if (parseToken(lltok::colon, "expected ':' here") ||
8155           parseStringConstant(WPDRes.SingleImplName))
8156         return true;
8157       break;
8158     case lltok::kw_resByArg:
8159       if (parseOptionalResByArg(WPDRes.ResByArg))
8160         return true;
8161       break;
8162     default:
8163       return error(Lex.getLoc(),
8164                    "expected optional WholeProgramDevirtResolution field");
8165     }
8166   }
8167 
8168   if (parseToken(lltok::rparen, "expected ')' here"))
8169     return true;
8170 
8171   return false;
8172 }
8173 
8174 /// OptionalResByArg
8175 ///   ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8176 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8177 ///                ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8178 ///                  'virtualConstProp' )
8179 ///                [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8180 ///                [',' 'bit' ':' UInt32]? ')'
8181 bool LLParser::parseOptionalResByArg(
8182     std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8183         &ResByArg) {
8184   if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8185       parseToken(lltok::colon, "expected ':' here") ||
8186       parseToken(lltok::lparen, "expected '(' here"))
8187     return true;
8188 
8189   do {
8190     std::vector<uint64_t> Args;
8191     if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8192         parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8193         parseToken(lltok::colon, "expected ':' here") ||
8194         parseToken(lltok::lparen, "expected '(' here") ||
8195         parseToken(lltok::kw_kind, "expected 'kind' here") ||
8196         parseToken(lltok::colon, "expected ':' here"))
8197       return true;
8198 
8199     WholeProgramDevirtResolution::ByArg ByArg;
8200     switch (Lex.getKind()) {
8201     case lltok::kw_indir:
8202       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8203       break;
8204     case lltok::kw_uniformRetVal:
8205       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8206       break;
8207     case lltok::kw_uniqueRetVal:
8208       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8209       break;
8210     case lltok::kw_virtualConstProp:
8211       ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8212       break;
8213     default:
8214       return error(Lex.getLoc(),
8215                    "unexpected WholeProgramDevirtResolution::ByArg kind");
8216     }
8217     Lex.Lex();
8218 
8219     // parse optional fields
8220     while (EatIfPresent(lltok::comma)) {
8221       switch (Lex.getKind()) {
8222       case lltok::kw_info:
8223         Lex.Lex();
8224         if (parseToken(lltok::colon, "expected ':' here") ||
8225             parseUInt64(ByArg.Info))
8226           return true;
8227         break;
8228       case lltok::kw_byte:
8229         Lex.Lex();
8230         if (parseToken(lltok::colon, "expected ':' here") ||
8231             parseUInt32(ByArg.Byte))
8232           return true;
8233         break;
8234       case lltok::kw_bit:
8235         Lex.Lex();
8236         if (parseToken(lltok::colon, "expected ':' here") ||
8237             parseUInt32(ByArg.Bit))
8238           return true;
8239         break;
8240       default:
8241         return error(Lex.getLoc(),
8242                      "expected optional whole program devirt field");
8243       }
8244     }
8245 
8246     if (parseToken(lltok::rparen, "expected ')' here"))
8247       return true;
8248 
8249     ResByArg[Args] = ByArg;
8250   } while (EatIfPresent(lltok::comma));
8251 
8252   if (parseToken(lltok::rparen, "expected ')' here"))
8253     return true;
8254 
8255   return false;
8256 }
8257 
8258 /// OptionalResByArg
8259 ///   ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8260 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8261   if (parseToken(lltok::kw_args, "expected 'args' here") ||
8262       parseToken(lltok::colon, "expected ':' here") ||
8263       parseToken(lltok::lparen, "expected '(' here"))
8264     return true;
8265 
8266   do {
8267     uint64_t Val;
8268     if (parseUInt64(Val))
8269       return true;
8270     Args.push_back(Val);
8271   } while (EatIfPresent(lltok::comma));
8272 
8273   if (parseToken(lltok::rparen, "expected ')' here"))
8274     return true;
8275 
8276   return false;
8277 }
8278 
8279 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8280 
8281 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8282   bool ReadOnly = Fwd->isReadOnly();
8283   bool WriteOnly = Fwd->isWriteOnly();
8284   assert(!(ReadOnly && WriteOnly));
8285   *Fwd = Resolved;
8286   if (ReadOnly)
8287     Fwd->setReadOnly();
8288   if (WriteOnly)
8289     Fwd->setWriteOnly();
8290 }
8291 
8292 /// Stores the given Name/GUID and associated summary into the Index.
8293 /// Also updates any forward references to the associated entry ID.
8294 void LLParser::addGlobalValueToIndex(
8295     std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8296     unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8297   // First create the ValueInfo utilizing the Name or GUID.
8298   ValueInfo VI;
8299   if (GUID != 0) {
8300     assert(Name.empty());
8301     VI = Index->getOrInsertValueInfo(GUID);
8302   } else {
8303     assert(!Name.empty());
8304     if (M) {
8305       auto *GV = M->getNamedValue(Name);
8306       assert(GV);
8307       VI = Index->getOrInsertValueInfo(GV);
8308     } else {
8309       assert(
8310           (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8311           "Need a source_filename to compute GUID for local");
8312       GUID = GlobalValue::getGUID(
8313           GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8314       VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8315     }
8316   }
8317 
8318   // Resolve forward references from calls/refs
8319   auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8320   if (FwdRefVIs != ForwardRefValueInfos.end()) {
8321     for (auto VIRef : FwdRefVIs->second) {
8322       assert(VIRef.first->getRef() == FwdVIRef &&
8323              "Forward referenced ValueInfo expected to be empty");
8324       resolveFwdRef(VIRef.first, VI);
8325     }
8326     ForwardRefValueInfos.erase(FwdRefVIs);
8327   }
8328 
8329   // Resolve forward references from aliases
8330   auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8331   if (FwdRefAliasees != ForwardRefAliasees.end()) {
8332     for (auto AliaseeRef : FwdRefAliasees->second) {
8333       assert(!AliaseeRef.first->hasAliasee() &&
8334              "Forward referencing alias already has aliasee");
8335       assert(Summary && "Aliasee must be a definition");
8336       AliaseeRef.first->setAliasee(VI, Summary.get());
8337     }
8338     ForwardRefAliasees.erase(FwdRefAliasees);
8339   }
8340 
8341   // Add the summary if one was provided.
8342   if (Summary)
8343     Index->addGlobalValueSummary(VI, std::move(Summary));
8344 
8345   // Save the associated ValueInfo for use in later references by ID.
8346   if (ID == NumberedValueInfos.size())
8347     NumberedValueInfos.push_back(VI);
8348   else {
8349     // Handle non-continuous numbers (to make test simplification easier).
8350     if (ID > NumberedValueInfos.size())
8351       NumberedValueInfos.resize(ID + 1);
8352     NumberedValueInfos[ID] = VI;
8353   }
8354 }
8355 
8356 /// parseSummaryIndexFlags
8357 ///   ::= 'flags' ':' UInt64
8358 bool LLParser::parseSummaryIndexFlags() {
8359   assert(Lex.getKind() == lltok::kw_flags);
8360   Lex.Lex();
8361 
8362   if (parseToken(lltok::colon, "expected ':' here"))
8363     return true;
8364   uint64_t Flags;
8365   if (parseUInt64(Flags))
8366     return true;
8367   if (Index)
8368     Index->setFlags(Flags);
8369   return false;
8370 }
8371 
8372 /// parseBlockCount
8373 ///   ::= 'blockcount' ':' UInt64
8374 bool LLParser::parseBlockCount() {
8375   assert(Lex.getKind() == lltok::kw_blockcount);
8376   Lex.Lex();
8377 
8378   if (parseToken(lltok::colon, "expected ':' here"))
8379     return true;
8380   uint64_t BlockCount;
8381   if (parseUInt64(BlockCount))
8382     return true;
8383   if (Index)
8384     Index->setBlockCount(BlockCount);
8385   return false;
8386 }
8387 
8388 /// parseGVEntry
8389 ///   ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8390 ///         [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8391 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8392 bool LLParser::parseGVEntry(unsigned ID) {
8393   assert(Lex.getKind() == lltok::kw_gv);
8394   Lex.Lex();
8395 
8396   if (parseToken(lltok::colon, "expected ':' here") ||
8397       parseToken(lltok::lparen, "expected '(' here"))
8398     return true;
8399 
8400   std::string Name;
8401   GlobalValue::GUID GUID = 0;
8402   switch (Lex.getKind()) {
8403   case lltok::kw_name:
8404     Lex.Lex();
8405     if (parseToken(lltok::colon, "expected ':' here") ||
8406         parseStringConstant(Name))
8407       return true;
8408     // Can't create GUID/ValueInfo until we have the linkage.
8409     break;
8410   case lltok::kw_guid:
8411     Lex.Lex();
8412     if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8413       return true;
8414     break;
8415   default:
8416     return error(Lex.getLoc(), "expected name or guid tag");
8417   }
8418 
8419   if (!EatIfPresent(lltok::comma)) {
8420     // No summaries. Wrap up.
8421     if (parseToken(lltok::rparen, "expected ')' here"))
8422       return true;
8423     // This was created for a call to an external or indirect target.
8424     // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8425     // created for indirect calls with VP. A Name with no GUID came from
8426     // an external definition. We pass ExternalLinkage since that is only
8427     // used when the GUID must be computed from Name, and in that case
8428     // the symbol must have external linkage.
8429     addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8430                           nullptr);
8431     return false;
8432   }
8433 
8434   // Have a list of summaries
8435   if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8436       parseToken(lltok::colon, "expected ':' here") ||
8437       parseToken(lltok::lparen, "expected '(' here"))
8438     return true;
8439   do {
8440     switch (Lex.getKind()) {
8441     case lltok::kw_function:
8442       if (parseFunctionSummary(Name, GUID, ID))
8443         return true;
8444       break;
8445     case lltok::kw_variable:
8446       if (parseVariableSummary(Name, GUID, ID))
8447         return true;
8448       break;
8449     case lltok::kw_alias:
8450       if (parseAliasSummary(Name, GUID, ID))
8451         return true;
8452       break;
8453     default:
8454       return error(Lex.getLoc(), "expected summary type");
8455     }
8456   } while (EatIfPresent(lltok::comma));
8457 
8458   if (parseToken(lltok::rparen, "expected ')' here") ||
8459       parseToken(lltok::rparen, "expected ')' here"))
8460     return true;
8461 
8462   return false;
8463 }
8464 
8465 /// FunctionSummary
8466 ///   ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8467 ///         ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8468 ///         [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8469 ///         [',' OptionalRefs]? ')'
8470 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8471                                     unsigned ID) {
8472   assert(Lex.getKind() == lltok::kw_function);
8473   Lex.Lex();
8474 
8475   StringRef ModulePath;
8476   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8477       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8478       /*NotEligibleToImport=*/false,
8479       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8480   unsigned InstCount;
8481   std::vector<FunctionSummary::EdgeTy> Calls;
8482   FunctionSummary::TypeIdInfo TypeIdInfo;
8483   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8484   std::vector<ValueInfo> Refs;
8485   // Default is all-zeros (conservative values).
8486   FunctionSummary::FFlags FFlags = {};
8487   if (parseToken(lltok::colon, "expected ':' here") ||
8488       parseToken(lltok::lparen, "expected '(' here") ||
8489       parseModuleReference(ModulePath) ||
8490       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8491       parseToken(lltok::comma, "expected ',' here") ||
8492       parseToken(lltok::kw_insts, "expected 'insts' here") ||
8493       parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8494     return true;
8495 
8496   // parse optional fields
8497   while (EatIfPresent(lltok::comma)) {
8498     switch (Lex.getKind()) {
8499     case lltok::kw_funcFlags:
8500       if (parseOptionalFFlags(FFlags))
8501         return true;
8502       break;
8503     case lltok::kw_calls:
8504       if (parseOptionalCalls(Calls))
8505         return true;
8506       break;
8507     case lltok::kw_typeIdInfo:
8508       if (parseOptionalTypeIdInfo(TypeIdInfo))
8509         return true;
8510       break;
8511     case lltok::kw_refs:
8512       if (parseOptionalRefs(Refs))
8513         return true;
8514       break;
8515     case lltok::kw_params:
8516       if (parseOptionalParamAccesses(ParamAccesses))
8517         return true;
8518       break;
8519     default:
8520       return error(Lex.getLoc(), "expected optional function summary field");
8521     }
8522   }
8523 
8524   if (parseToken(lltok::rparen, "expected ')' here"))
8525     return true;
8526 
8527   auto FS = std::make_unique<FunctionSummary>(
8528       GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8529       std::move(Calls), std::move(TypeIdInfo.TypeTests),
8530       std::move(TypeIdInfo.TypeTestAssumeVCalls),
8531       std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8532       std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8533       std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8534       std::move(ParamAccesses));
8535 
8536   FS->setModulePath(ModulePath);
8537 
8538   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8539                         ID, std::move(FS));
8540 
8541   return false;
8542 }
8543 
8544 /// VariableSummary
8545 ///   ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8546 ///         [',' OptionalRefs]? ')'
8547 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8548                                     unsigned ID) {
8549   assert(Lex.getKind() == lltok::kw_variable);
8550   Lex.Lex();
8551 
8552   StringRef ModulePath;
8553   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8554       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8555       /*NotEligibleToImport=*/false,
8556       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8557   GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8558                                         /* WriteOnly */ false,
8559                                         /* Constant */ false,
8560                                         GlobalObject::VCallVisibilityPublic);
8561   std::vector<ValueInfo> Refs;
8562   VTableFuncList VTableFuncs;
8563   if (parseToken(lltok::colon, "expected ':' here") ||
8564       parseToken(lltok::lparen, "expected '(' here") ||
8565       parseModuleReference(ModulePath) ||
8566       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8567       parseToken(lltok::comma, "expected ',' here") ||
8568       parseGVarFlags(GVarFlags))
8569     return true;
8570 
8571   // parse optional fields
8572   while (EatIfPresent(lltok::comma)) {
8573     switch (Lex.getKind()) {
8574     case lltok::kw_vTableFuncs:
8575       if (parseOptionalVTableFuncs(VTableFuncs))
8576         return true;
8577       break;
8578     case lltok::kw_refs:
8579       if (parseOptionalRefs(Refs))
8580         return true;
8581       break;
8582     default:
8583       return error(Lex.getLoc(), "expected optional variable summary field");
8584     }
8585   }
8586 
8587   if (parseToken(lltok::rparen, "expected ')' here"))
8588     return true;
8589 
8590   auto GS =
8591       std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8592 
8593   GS->setModulePath(ModulePath);
8594   GS->setVTableFuncs(std::move(VTableFuncs));
8595 
8596   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8597                         ID, std::move(GS));
8598 
8599   return false;
8600 }
8601 
8602 /// AliasSummary
8603 ///   ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8604 ///         'aliasee' ':' GVReference ')'
8605 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8606                                  unsigned ID) {
8607   assert(Lex.getKind() == lltok::kw_alias);
8608   LocTy Loc = Lex.getLoc();
8609   Lex.Lex();
8610 
8611   StringRef ModulePath;
8612   GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8613       GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8614       /*NotEligibleToImport=*/false,
8615       /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8616   if (parseToken(lltok::colon, "expected ':' here") ||
8617       parseToken(lltok::lparen, "expected '(' here") ||
8618       parseModuleReference(ModulePath) ||
8619       parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8620       parseToken(lltok::comma, "expected ',' here") ||
8621       parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8622       parseToken(lltok::colon, "expected ':' here"))
8623     return true;
8624 
8625   ValueInfo AliaseeVI;
8626   unsigned GVId;
8627   if (parseGVReference(AliaseeVI, GVId))
8628     return true;
8629 
8630   if (parseToken(lltok::rparen, "expected ')' here"))
8631     return true;
8632 
8633   auto AS = std::make_unique<AliasSummary>(GVFlags);
8634 
8635   AS->setModulePath(ModulePath);
8636 
8637   // Record forward reference if the aliasee is not parsed yet.
8638   if (AliaseeVI.getRef() == FwdVIRef) {
8639     ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8640   } else {
8641     auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8642     assert(Summary && "Aliasee must be a definition");
8643     AS->setAliasee(AliaseeVI, Summary);
8644   }
8645 
8646   addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8647                         ID, std::move(AS));
8648 
8649   return false;
8650 }
8651 
8652 /// Flag
8653 ///   ::= [0|1]
8654 bool LLParser::parseFlag(unsigned &Val) {
8655   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8656     return tokError("expected integer");
8657   Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8658   Lex.Lex();
8659   return false;
8660 }
8661 
8662 /// OptionalFFlags
8663 ///   := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8664 ///        [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8665 ///        [',' 'returnDoesNotAlias' ':' Flag]? ')'
8666 ///        [',' 'noInline' ':' Flag]? ')'
8667 ///        [',' 'alwaysInline' ':' Flag]? ')'
8668 ///        [',' 'noUnwind' ':' Flag]? ')'
8669 ///        [',' 'mayThrow' ':' Flag]? ')'
8670 ///        [',' 'hasUnknownCall' ':' Flag]? ')'
8671 ///        [',' 'mustBeUnreachable' ':' Flag]? ')'
8672 
8673 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8674   assert(Lex.getKind() == lltok::kw_funcFlags);
8675   Lex.Lex();
8676 
8677   if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
8678       parseToken(lltok::lparen, "expected '(' in funcFlags"))
8679     return true;
8680 
8681   do {
8682     unsigned Val = 0;
8683     switch (Lex.getKind()) {
8684     case lltok::kw_readNone:
8685       Lex.Lex();
8686       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8687         return true;
8688       FFlags.ReadNone = Val;
8689       break;
8690     case lltok::kw_readOnly:
8691       Lex.Lex();
8692       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8693         return true;
8694       FFlags.ReadOnly = Val;
8695       break;
8696     case lltok::kw_noRecurse:
8697       Lex.Lex();
8698       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8699         return true;
8700       FFlags.NoRecurse = Val;
8701       break;
8702     case lltok::kw_returnDoesNotAlias:
8703       Lex.Lex();
8704       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8705         return true;
8706       FFlags.ReturnDoesNotAlias = Val;
8707       break;
8708     case lltok::kw_noInline:
8709       Lex.Lex();
8710       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8711         return true;
8712       FFlags.NoInline = Val;
8713       break;
8714     case lltok::kw_alwaysInline:
8715       Lex.Lex();
8716       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8717         return true;
8718       FFlags.AlwaysInline = Val;
8719       break;
8720     case lltok::kw_noUnwind:
8721       Lex.Lex();
8722       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8723         return true;
8724       FFlags.NoUnwind = Val;
8725       break;
8726     case lltok::kw_mayThrow:
8727       Lex.Lex();
8728       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8729         return true;
8730       FFlags.MayThrow = Val;
8731       break;
8732     case lltok::kw_hasUnknownCall:
8733       Lex.Lex();
8734       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8735         return true;
8736       FFlags.HasUnknownCall = Val;
8737       break;
8738     case lltok::kw_mustBeUnreachable:
8739       Lex.Lex();
8740       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8741         return true;
8742       FFlags.MustBeUnreachable = Val;
8743       break;
8744     default:
8745       return error(Lex.getLoc(), "expected function flag type");
8746     }
8747   } while (EatIfPresent(lltok::comma));
8748 
8749   if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8750     return true;
8751 
8752   return false;
8753 }
8754 
8755 /// OptionalCalls
8756 ///   := 'calls' ':' '(' Call [',' Call]* ')'
8757 /// Call ::= '(' 'callee' ':' GVReference
8758 ///            [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8759 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8760   assert(Lex.getKind() == lltok::kw_calls);
8761   Lex.Lex();
8762 
8763   if (parseToken(lltok::colon, "expected ':' in calls") ||
8764       parseToken(lltok::lparen, "expected '(' in calls"))
8765     return true;
8766 
8767   IdToIndexMapType IdToIndexMap;
8768   // parse each call edge
8769   do {
8770     ValueInfo VI;
8771     if (parseToken(lltok::lparen, "expected '(' in call") ||
8772         parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8773         parseToken(lltok::colon, "expected ':'"))
8774       return true;
8775 
8776     LocTy Loc = Lex.getLoc();
8777     unsigned GVId;
8778     if (parseGVReference(VI, GVId))
8779       return true;
8780 
8781     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8782     unsigned RelBF = 0;
8783     if (EatIfPresent(lltok::comma)) {
8784       // Expect either hotness or relbf
8785       if (EatIfPresent(lltok::kw_hotness)) {
8786         if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8787           return true;
8788       } else {
8789         if (parseToken(lltok::kw_relbf, "expected relbf") ||
8790             parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8791           return true;
8792       }
8793     }
8794     // Keep track of the Call array index needing a forward reference.
8795     // We will save the location of the ValueInfo needing an update, but
8796     // can only do so once the std::vector is finalized.
8797     if (VI.getRef() == FwdVIRef)
8798       IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8799     Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8800 
8801     if (parseToken(lltok::rparen, "expected ')' in call"))
8802       return true;
8803   } while (EatIfPresent(lltok::comma));
8804 
8805   // Now that the Calls vector is finalized, it is safe to save the locations
8806   // of any forward GV references that need updating later.
8807   for (auto I : IdToIndexMap) {
8808     auto &Infos = ForwardRefValueInfos[I.first];
8809     for (auto P : I.second) {
8810       assert(Calls[P.first].first.getRef() == FwdVIRef &&
8811              "Forward referenced ValueInfo expected to be empty");
8812       Infos.emplace_back(&Calls[P.first].first, P.second);
8813     }
8814   }
8815 
8816   if (parseToken(lltok::rparen, "expected ')' in calls"))
8817     return true;
8818 
8819   return false;
8820 }
8821 
8822 /// Hotness
8823 ///   := ('unknown'|'cold'|'none'|'hot'|'critical')
8824 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8825   switch (Lex.getKind()) {
8826   case lltok::kw_unknown:
8827     Hotness = CalleeInfo::HotnessType::Unknown;
8828     break;
8829   case lltok::kw_cold:
8830     Hotness = CalleeInfo::HotnessType::Cold;
8831     break;
8832   case lltok::kw_none:
8833     Hotness = CalleeInfo::HotnessType::None;
8834     break;
8835   case lltok::kw_hot:
8836     Hotness = CalleeInfo::HotnessType::Hot;
8837     break;
8838   case lltok::kw_critical:
8839     Hotness = CalleeInfo::HotnessType::Critical;
8840     break;
8841   default:
8842     return error(Lex.getLoc(), "invalid call edge hotness");
8843   }
8844   Lex.Lex();
8845   return false;
8846 }
8847 
8848 /// OptionalVTableFuncs
8849 ///   := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8850 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8851 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8852   assert(Lex.getKind() == lltok::kw_vTableFuncs);
8853   Lex.Lex();
8854 
8855   if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
8856       parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8857     return true;
8858 
8859   IdToIndexMapType IdToIndexMap;
8860   // parse each virtual function pair
8861   do {
8862     ValueInfo VI;
8863     if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8864         parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8865         parseToken(lltok::colon, "expected ':'"))
8866       return true;
8867 
8868     LocTy Loc = Lex.getLoc();
8869     unsigned GVId;
8870     if (parseGVReference(VI, GVId))
8871       return true;
8872 
8873     uint64_t Offset;
8874     if (parseToken(lltok::comma, "expected comma") ||
8875         parseToken(lltok::kw_offset, "expected offset") ||
8876         parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
8877       return true;
8878 
8879     // Keep track of the VTableFuncs array index needing a forward reference.
8880     // We will save the location of the ValueInfo needing an update, but
8881     // can only do so once the std::vector is finalized.
8882     if (VI == EmptyVI)
8883       IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8884     VTableFuncs.push_back({VI, Offset});
8885 
8886     if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
8887       return true;
8888   } while (EatIfPresent(lltok::comma));
8889 
8890   // Now that the VTableFuncs vector is finalized, it is safe to save the
8891   // locations of any forward GV references that need updating later.
8892   for (auto I : IdToIndexMap) {
8893     auto &Infos = ForwardRefValueInfos[I.first];
8894     for (auto P : I.second) {
8895       assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8896              "Forward referenced ValueInfo expected to be empty");
8897       Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
8898     }
8899   }
8900 
8901   if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8902     return true;
8903 
8904   return false;
8905 }
8906 
8907 /// ParamNo := 'param' ':' UInt64
8908 bool LLParser::parseParamNo(uint64_t &ParamNo) {
8909   if (parseToken(lltok::kw_param, "expected 'param' here") ||
8910       parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
8911     return true;
8912   return false;
8913 }
8914 
8915 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
8916 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
8917   APSInt Lower;
8918   APSInt Upper;
8919   auto ParseAPSInt = [&](APSInt &Val) {
8920     if (Lex.getKind() != lltok::APSInt)
8921       return tokError("expected integer");
8922     Val = Lex.getAPSIntVal();
8923     Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
8924     Val.setIsSigned(true);
8925     Lex.Lex();
8926     return false;
8927   };
8928   if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
8929       parseToken(lltok::colon, "expected ':' here") ||
8930       parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
8931       parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
8932       parseToken(lltok::rsquare, "expected ']' here"))
8933     return true;
8934 
8935   ++Upper;
8936   Range =
8937       (Lower == Upper && !Lower.isMaxValue())
8938           ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
8939           : ConstantRange(Lower, Upper);
8940 
8941   return false;
8942 }
8943 
8944 /// ParamAccessCall
8945 ///   := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
8946 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
8947                                     IdLocListType &IdLocList) {
8948   if (parseToken(lltok::lparen, "expected '(' here") ||
8949       parseToken(lltok::kw_callee, "expected 'callee' here") ||
8950       parseToken(lltok::colon, "expected ':' here"))
8951     return true;
8952 
8953   unsigned GVId;
8954   ValueInfo VI;
8955   LocTy Loc = Lex.getLoc();
8956   if (parseGVReference(VI, GVId))
8957     return true;
8958 
8959   Call.Callee = VI;
8960   IdLocList.emplace_back(GVId, Loc);
8961 
8962   if (parseToken(lltok::comma, "expected ',' here") ||
8963       parseParamNo(Call.ParamNo) ||
8964       parseToken(lltok::comma, "expected ',' here") ||
8965       parseParamAccessOffset(Call.Offsets))
8966     return true;
8967 
8968   if (parseToken(lltok::rparen, "expected ')' here"))
8969     return true;
8970 
8971   return false;
8972 }
8973 
8974 /// ParamAccess
8975 ///   := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
8976 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
8977 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
8978                                 IdLocListType &IdLocList) {
8979   if (parseToken(lltok::lparen, "expected '(' here") ||
8980       parseParamNo(Param.ParamNo) ||
8981       parseToken(lltok::comma, "expected ',' here") ||
8982       parseParamAccessOffset(Param.Use))
8983     return true;
8984 
8985   if (EatIfPresent(lltok::comma)) {
8986     if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
8987         parseToken(lltok::colon, "expected ':' here") ||
8988         parseToken(lltok::lparen, "expected '(' here"))
8989       return true;
8990     do {
8991       FunctionSummary::ParamAccess::Call Call;
8992       if (parseParamAccessCall(Call, IdLocList))
8993         return true;
8994       Param.Calls.push_back(Call);
8995     } while (EatIfPresent(lltok::comma));
8996 
8997     if (parseToken(lltok::rparen, "expected ')' here"))
8998       return true;
8999   }
9000 
9001   if (parseToken(lltok::rparen, "expected ')' here"))
9002     return true;
9003 
9004   return false;
9005 }
9006 
9007 /// OptionalParamAccesses
9008 ///   := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9009 bool LLParser::parseOptionalParamAccesses(
9010     std::vector<FunctionSummary::ParamAccess> &Params) {
9011   assert(Lex.getKind() == lltok::kw_params);
9012   Lex.Lex();
9013 
9014   if (parseToken(lltok::colon, "expected ':' here") ||
9015       parseToken(lltok::lparen, "expected '(' here"))
9016     return true;
9017 
9018   IdLocListType VContexts;
9019   size_t CallsNum = 0;
9020   do {
9021     FunctionSummary::ParamAccess ParamAccess;
9022     if (parseParamAccess(ParamAccess, VContexts))
9023       return true;
9024     CallsNum += ParamAccess.Calls.size();
9025     assert(VContexts.size() == CallsNum);
9026     (void)CallsNum;
9027     Params.emplace_back(std::move(ParamAccess));
9028   } while (EatIfPresent(lltok::comma));
9029 
9030   if (parseToken(lltok::rparen, "expected ')' here"))
9031     return true;
9032 
9033   // Now that the Params is finalized, it is safe to save the locations
9034   // of any forward GV references that need updating later.
9035   IdLocListType::const_iterator ItContext = VContexts.begin();
9036   for (auto &PA : Params) {
9037     for (auto &C : PA.Calls) {
9038       if (C.Callee.getRef() == FwdVIRef)
9039         ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9040                                                             ItContext->second);
9041       ++ItContext;
9042     }
9043   }
9044   assert(ItContext == VContexts.end());
9045 
9046   return false;
9047 }
9048 
9049 /// OptionalRefs
9050 ///   := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9051 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9052   assert(Lex.getKind() == lltok::kw_refs);
9053   Lex.Lex();
9054 
9055   if (parseToken(lltok::colon, "expected ':' in refs") ||
9056       parseToken(lltok::lparen, "expected '(' in refs"))
9057     return true;
9058 
9059   struct ValueContext {
9060     ValueInfo VI;
9061     unsigned GVId;
9062     LocTy Loc;
9063   };
9064   std::vector<ValueContext> VContexts;
9065   // parse each ref edge
9066   do {
9067     ValueContext VC;
9068     VC.Loc = Lex.getLoc();
9069     if (parseGVReference(VC.VI, VC.GVId))
9070       return true;
9071     VContexts.push_back(VC);
9072   } while (EatIfPresent(lltok::comma));
9073 
9074   // Sort value contexts so that ones with writeonly
9075   // and readonly ValueInfo  are at the end of VContexts vector.
9076   // See FunctionSummary::specialRefCounts()
9077   llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9078     return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9079   });
9080 
9081   IdToIndexMapType IdToIndexMap;
9082   for (auto &VC : VContexts) {
9083     // Keep track of the Refs array index needing a forward reference.
9084     // We will save the location of the ValueInfo needing an update, but
9085     // can only do so once the std::vector is finalized.
9086     if (VC.VI.getRef() == FwdVIRef)
9087       IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9088     Refs.push_back(VC.VI);
9089   }
9090 
9091   // Now that the Refs vector is finalized, it is safe to save the locations
9092   // of any forward GV references that need updating later.
9093   for (auto I : IdToIndexMap) {
9094     auto &Infos = ForwardRefValueInfos[I.first];
9095     for (auto P : I.second) {
9096       assert(Refs[P.first].getRef() == FwdVIRef &&
9097              "Forward referenced ValueInfo expected to be empty");
9098       Infos.emplace_back(&Refs[P.first], P.second);
9099     }
9100   }
9101 
9102   if (parseToken(lltok::rparen, "expected ')' in refs"))
9103     return true;
9104 
9105   return false;
9106 }
9107 
9108 /// OptionalTypeIdInfo
9109 ///   := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9110 ///         [',' TypeCheckedLoadVCalls]?  [',' TypeTestAssumeConstVCalls]?
9111 ///         [',' TypeCheckedLoadConstVCalls]? ')'
9112 bool LLParser::parseOptionalTypeIdInfo(
9113     FunctionSummary::TypeIdInfo &TypeIdInfo) {
9114   assert(Lex.getKind() == lltok::kw_typeIdInfo);
9115   Lex.Lex();
9116 
9117   if (parseToken(lltok::colon, "expected ':' here") ||
9118       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9119     return true;
9120 
9121   do {
9122     switch (Lex.getKind()) {
9123     case lltok::kw_typeTests:
9124       if (parseTypeTests(TypeIdInfo.TypeTests))
9125         return true;
9126       break;
9127     case lltok::kw_typeTestAssumeVCalls:
9128       if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9129                            TypeIdInfo.TypeTestAssumeVCalls))
9130         return true;
9131       break;
9132     case lltok::kw_typeCheckedLoadVCalls:
9133       if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9134                            TypeIdInfo.TypeCheckedLoadVCalls))
9135         return true;
9136       break;
9137     case lltok::kw_typeTestAssumeConstVCalls:
9138       if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9139                               TypeIdInfo.TypeTestAssumeConstVCalls))
9140         return true;
9141       break;
9142     case lltok::kw_typeCheckedLoadConstVCalls:
9143       if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9144                               TypeIdInfo.TypeCheckedLoadConstVCalls))
9145         return true;
9146       break;
9147     default:
9148       return error(Lex.getLoc(), "invalid typeIdInfo list type");
9149     }
9150   } while (EatIfPresent(lltok::comma));
9151 
9152   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9153     return true;
9154 
9155   return false;
9156 }
9157 
9158 /// TypeTests
9159 ///   ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9160 ///         [',' (SummaryID | UInt64)]* ')'
9161 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9162   assert(Lex.getKind() == lltok::kw_typeTests);
9163   Lex.Lex();
9164 
9165   if (parseToken(lltok::colon, "expected ':' here") ||
9166       parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9167     return true;
9168 
9169   IdToIndexMapType IdToIndexMap;
9170   do {
9171     GlobalValue::GUID GUID = 0;
9172     if (Lex.getKind() == lltok::SummaryID) {
9173       unsigned ID = Lex.getUIntVal();
9174       LocTy Loc = Lex.getLoc();
9175       // Keep track of the TypeTests array index needing a forward reference.
9176       // We will save the location of the GUID needing an update, but
9177       // can only do so once the std::vector is finalized.
9178       IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9179       Lex.Lex();
9180     } else if (parseUInt64(GUID))
9181       return true;
9182     TypeTests.push_back(GUID);
9183   } while (EatIfPresent(lltok::comma));
9184 
9185   // Now that the TypeTests vector is finalized, it is safe to save the
9186   // locations of any forward GV references that need updating later.
9187   for (auto I : IdToIndexMap) {
9188     auto &Ids = ForwardRefTypeIds[I.first];
9189     for (auto P : I.second) {
9190       assert(TypeTests[P.first] == 0 &&
9191              "Forward referenced type id GUID expected to be 0");
9192       Ids.emplace_back(&TypeTests[P.first], P.second);
9193     }
9194   }
9195 
9196   if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9197     return true;
9198 
9199   return false;
9200 }
9201 
9202 /// VFuncIdList
9203 ///   ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9204 bool LLParser::parseVFuncIdList(
9205     lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9206   assert(Lex.getKind() == Kind);
9207   Lex.Lex();
9208 
9209   if (parseToken(lltok::colon, "expected ':' here") ||
9210       parseToken(lltok::lparen, "expected '(' here"))
9211     return true;
9212 
9213   IdToIndexMapType IdToIndexMap;
9214   do {
9215     FunctionSummary::VFuncId VFuncId;
9216     if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9217       return true;
9218     VFuncIdList.push_back(VFuncId);
9219   } while (EatIfPresent(lltok::comma));
9220 
9221   if (parseToken(lltok::rparen, "expected ')' here"))
9222     return true;
9223 
9224   // Now that the VFuncIdList vector is finalized, it is safe to save the
9225   // locations of any forward GV references that need updating later.
9226   for (auto I : IdToIndexMap) {
9227     auto &Ids = ForwardRefTypeIds[I.first];
9228     for (auto P : I.second) {
9229       assert(VFuncIdList[P.first].GUID == 0 &&
9230              "Forward referenced type id GUID expected to be 0");
9231       Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9232     }
9233   }
9234 
9235   return false;
9236 }
9237 
9238 /// ConstVCallList
9239 ///   ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9240 bool LLParser::parseConstVCallList(
9241     lltok::Kind Kind,
9242     std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9243   assert(Lex.getKind() == Kind);
9244   Lex.Lex();
9245 
9246   if (parseToken(lltok::colon, "expected ':' here") ||
9247       parseToken(lltok::lparen, "expected '(' here"))
9248     return true;
9249 
9250   IdToIndexMapType IdToIndexMap;
9251   do {
9252     FunctionSummary::ConstVCall ConstVCall;
9253     if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9254       return true;
9255     ConstVCallList.push_back(ConstVCall);
9256   } while (EatIfPresent(lltok::comma));
9257 
9258   if (parseToken(lltok::rparen, "expected ')' here"))
9259     return true;
9260 
9261   // Now that the ConstVCallList vector is finalized, it is safe to save the
9262   // locations of any forward GV references that need updating later.
9263   for (auto I : IdToIndexMap) {
9264     auto &Ids = ForwardRefTypeIds[I.first];
9265     for (auto P : I.second) {
9266       assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9267              "Forward referenced type id GUID expected to be 0");
9268       Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9269     }
9270   }
9271 
9272   return false;
9273 }
9274 
9275 /// ConstVCall
9276 ///   ::= '(' VFuncId ',' Args ')'
9277 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9278                                IdToIndexMapType &IdToIndexMap, unsigned Index) {
9279   if (parseToken(lltok::lparen, "expected '(' here") ||
9280       parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9281     return true;
9282 
9283   if (EatIfPresent(lltok::comma))
9284     if (parseArgs(ConstVCall.Args))
9285       return true;
9286 
9287   if (parseToken(lltok::rparen, "expected ')' here"))
9288     return true;
9289 
9290   return false;
9291 }
9292 
9293 /// VFuncId
9294 ///   ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9295 ///         'offset' ':' UInt64 ')'
9296 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9297                             IdToIndexMapType &IdToIndexMap, unsigned Index) {
9298   assert(Lex.getKind() == lltok::kw_vFuncId);
9299   Lex.Lex();
9300 
9301   if (parseToken(lltok::colon, "expected ':' here") ||
9302       parseToken(lltok::lparen, "expected '(' here"))
9303     return true;
9304 
9305   if (Lex.getKind() == lltok::SummaryID) {
9306     VFuncId.GUID = 0;
9307     unsigned ID = Lex.getUIntVal();
9308     LocTy Loc = Lex.getLoc();
9309     // Keep track of the array index needing a forward reference.
9310     // We will save the location of the GUID needing an update, but
9311     // can only do so once the caller's std::vector is finalized.
9312     IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9313     Lex.Lex();
9314   } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9315              parseToken(lltok::colon, "expected ':' here") ||
9316              parseUInt64(VFuncId.GUID))
9317     return true;
9318 
9319   if (parseToken(lltok::comma, "expected ',' here") ||
9320       parseToken(lltok::kw_offset, "expected 'offset' here") ||
9321       parseToken(lltok::colon, "expected ':' here") ||
9322       parseUInt64(VFuncId.Offset) ||
9323       parseToken(lltok::rparen, "expected ')' here"))
9324     return true;
9325 
9326   return false;
9327 }
9328 
9329 /// GVFlags
9330 ///   ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9331 ///         'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9332 ///         'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9333 ///         'canAutoHide' ':' Flag ',' ')'
9334 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9335   assert(Lex.getKind() == lltok::kw_flags);
9336   Lex.Lex();
9337 
9338   if (parseToken(lltok::colon, "expected ':' here") ||
9339       parseToken(lltok::lparen, "expected '(' here"))
9340     return true;
9341 
9342   do {
9343     unsigned Flag = 0;
9344     switch (Lex.getKind()) {
9345     case lltok::kw_linkage:
9346       Lex.Lex();
9347       if (parseToken(lltok::colon, "expected ':'"))
9348         return true;
9349       bool HasLinkage;
9350       GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9351       assert(HasLinkage && "Linkage not optional in summary entry");
9352       Lex.Lex();
9353       break;
9354     case lltok::kw_visibility:
9355       Lex.Lex();
9356       if (parseToken(lltok::colon, "expected ':'"))
9357         return true;
9358       parseOptionalVisibility(Flag);
9359       GVFlags.Visibility = Flag;
9360       break;
9361     case lltok::kw_notEligibleToImport:
9362       Lex.Lex();
9363       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9364         return true;
9365       GVFlags.NotEligibleToImport = Flag;
9366       break;
9367     case lltok::kw_live:
9368       Lex.Lex();
9369       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9370         return true;
9371       GVFlags.Live = Flag;
9372       break;
9373     case lltok::kw_dsoLocal:
9374       Lex.Lex();
9375       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9376         return true;
9377       GVFlags.DSOLocal = Flag;
9378       break;
9379     case lltok::kw_canAutoHide:
9380       Lex.Lex();
9381       if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9382         return true;
9383       GVFlags.CanAutoHide = Flag;
9384       break;
9385     default:
9386       return error(Lex.getLoc(), "expected gv flag type");
9387     }
9388   } while (EatIfPresent(lltok::comma));
9389 
9390   if (parseToken(lltok::rparen, "expected ')' here"))
9391     return true;
9392 
9393   return false;
9394 }
9395 
9396 /// GVarFlags
9397 ///   ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9398 ///                      ',' 'writeonly' ':' Flag
9399 ///                      ',' 'constant' ':' Flag ')'
9400 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9401   assert(Lex.getKind() == lltok::kw_varFlags);
9402   Lex.Lex();
9403 
9404   if (parseToken(lltok::colon, "expected ':' here") ||
9405       parseToken(lltok::lparen, "expected '(' here"))
9406     return true;
9407 
9408   auto ParseRest = [this](unsigned int &Val) {
9409     Lex.Lex();
9410     if (parseToken(lltok::colon, "expected ':'"))
9411       return true;
9412     return parseFlag(Val);
9413   };
9414 
9415   do {
9416     unsigned Flag = 0;
9417     switch (Lex.getKind()) {
9418     case lltok::kw_readonly:
9419       if (ParseRest(Flag))
9420         return true;
9421       GVarFlags.MaybeReadOnly = Flag;
9422       break;
9423     case lltok::kw_writeonly:
9424       if (ParseRest(Flag))
9425         return true;
9426       GVarFlags.MaybeWriteOnly = Flag;
9427       break;
9428     case lltok::kw_constant:
9429       if (ParseRest(Flag))
9430         return true;
9431       GVarFlags.Constant = Flag;
9432       break;
9433     case lltok::kw_vcall_visibility:
9434       if (ParseRest(Flag))
9435         return true;
9436       GVarFlags.VCallVisibility = Flag;
9437       break;
9438     default:
9439       return error(Lex.getLoc(), "expected gvar flag type");
9440     }
9441   } while (EatIfPresent(lltok::comma));
9442   return parseToken(lltok::rparen, "expected ')' here");
9443 }
9444 
9445 /// ModuleReference
9446 ///   ::= 'module' ':' UInt
9447 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9448   // parse module id.
9449   if (parseToken(lltok::kw_module, "expected 'module' here") ||
9450       parseToken(lltok::colon, "expected ':' here") ||
9451       parseToken(lltok::SummaryID, "expected module ID"))
9452     return true;
9453 
9454   unsigned ModuleID = Lex.getUIntVal();
9455   auto I = ModuleIdMap.find(ModuleID);
9456   // We should have already parsed all module IDs
9457   assert(I != ModuleIdMap.end());
9458   ModulePath = I->second;
9459   return false;
9460 }
9461 
9462 /// GVReference
9463 ///   ::= SummaryID
9464 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9465   bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9466   if (!ReadOnly)
9467     WriteOnly = EatIfPresent(lltok::kw_writeonly);
9468   if (parseToken(lltok::SummaryID, "expected GV ID"))
9469     return true;
9470 
9471   GVId = Lex.getUIntVal();
9472   // Check if we already have a VI for this GV
9473   if (GVId < NumberedValueInfos.size()) {
9474     assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9475     VI = NumberedValueInfos[GVId];
9476   } else
9477     // We will create a forward reference to the stored location.
9478     VI = ValueInfo(false, FwdVIRef);
9479 
9480   if (ReadOnly)
9481     VI.setReadOnly();
9482   if (WriteOnly)
9483     VI.setWriteOnly();
9484   return false;
9485 }
9486