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