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