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