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