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