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