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