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