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