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