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