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