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