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