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