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