1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LLParser.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/AsmParser/SlotMapping.h"
19 #include "llvm/IR/AutoUpgrade.h"
20 #include "llvm/IR/CallingConv.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/DebugInfoMetadata.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/SaveAndRestore.h"
35 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
37 
38 static std::string getTypeString(Type *T) {
39   std::string Result;
40   raw_string_ostream Tmp(Result);
41   Tmp << *T;
42   return Tmp.str();
43 }
44 
45 /// Run: module ::= toplevelentity*
46 bool LLParser::Run() {
47   // Prime the lexer.
48   Lex.Lex();
49 
50   if (Context.shouldDiscardValueNames())
51     return Error(
52         Lex.getLoc(),
53         "Can't read textual IR with a Context that discards named Values");
54 
55   return ParseTopLevelEntities() ||
56          ValidateEndOfModule();
57 }
58 
59 bool LLParser::parseStandaloneConstantValue(Constant *&C,
60                                             const SlotMapping *Slots) {
61   restoreParsingState(Slots);
62   Lex.Lex();
63 
64   Type *Ty = nullptr;
65   if (ParseType(Ty) || parseConstantValue(Ty, C))
66     return true;
67   if (Lex.getKind() != lltok::Eof)
68     return Error(Lex.getLoc(), "expected end of string");
69   return false;
70 }
71 
72 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
73                                     const SlotMapping *Slots) {
74   restoreParsingState(Slots);
75   Lex.Lex();
76 
77   Read = 0;
78   SMLoc Start = Lex.getLoc();
79   Ty = nullptr;
80   if (ParseType(Ty))
81     return true;
82   SMLoc End = Lex.getLoc();
83   Read = End.getPointer() - Start.getPointer();
84 
85   return false;
86 }
87 
88 void LLParser::restoreParsingState(const SlotMapping *Slots) {
89   if (!Slots)
90     return;
91   NumberedVals = Slots->GlobalValues;
92   NumberedMetadata = Slots->MetadataNodes;
93   for (const auto &I : Slots->NamedTypes)
94     NamedTypes.insert(
95         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
96   for (const auto &I : Slots->Types)
97     NumberedTypes.insert(
98         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
99 }
100 
101 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
102 /// module.
103 bool LLParser::ValidateEndOfModule() {
104   // Handle any function attribute group forward references.
105   for (std::map<Value*, std::vector<unsigned> >::iterator
106          I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
107          I != E; ++I) {
108     Value *V = I->first;
109     std::vector<unsigned> &Vec = I->second;
110     AttrBuilder B;
111 
112     for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
113          VI != VE; ++VI)
114       B.merge(NumberedAttrBuilders[*VI]);
115 
116     if (Function *Fn = dyn_cast<Function>(V)) {
117       AttributeSet AS = Fn->getAttributes();
118       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120                                AS.getFnAttributes());
121 
122       FnAttrs.merge(B);
123 
124       // If the alignment was parsed as an attribute, move to the alignment
125       // field.
126       if (FnAttrs.hasAlignmentAttr()) {
127         Fn->setAlignment(FnAttrs.getAlignment());
128         FnAttrs.removeAttribute(Attribute::Alignment);
129       }
130 
131       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
132                             AttributeSet::get(Context,
133                                               AttributeSet::FunctionIndex,
134                                               FnAttrs));
135       Fn->setAttributes(AS);
136     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
137       AttributeSet AS = CI->getAttributes();
138       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
139       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
140                                AS.getFnAttributes());
141       FnAttrs.merge(B);
142       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
143                             AttributeSet::get(Context,
144                                               AttributeSet::FunctionIndex,
145                                               FnAttrs));
146       CI->setAttributes(AS);
147     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
148       AttributeSet AS = II->getAttributes();
149       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
150       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
151                                AS.getFnAttributes());
152       FnAttrs.merge(B);
153       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
154                             AttributeSet::get(Context,
155                                               AttributeSet::FunctionIndex,
156                                               FnAttrs));
157       II->setAttributes(AS);
158     } else {
159       llvm_unreachable("invalid object with forward attribute group reference");
160     }
161   }
162 
163   // If there are entries in ForwardRefBlockAddresses at this point, the
164   // function was never defined.
165   if (!ForwardRefBlockAddresses.empty())
166     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
167                  "expected function name in blockaddress");
168 
169   for (const auto &NT : NumberedTypes)
170     if (NT.second.second.isValid())
171       return Error(NT.second.second,
172                    "use of undefined type '%" + Twine(NT.first) + "'");
173 
174   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
175        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
176     if (I->second.second.isValid())
177       return Error(I->second.second,
178                    "use of undefined type named '" + I->getKey() + "'");
179 
180   if (!ForwardRefComdats.empty())
181     return Error(ForwardRefComdats.begin()->second,
182                  "use of undefined comdat '$" +
183                      ForwardRefComdats.begin()->first + "'");
184 
185   if (!ForwardRefVals.empty())
186     return Error(ForwardRefVals.begin()->second.second,
187                  "use of undefined value '@" + ForwardRefVals.begin()->first +
188                  "'");
189 
190   if (!ForwardRefValIDs.empty())
191     return Error(ForwardRefValIDs.begin()->second.second,
192                  "use of undefined value '@" +
193                  Twine(ForwardRefValIDs.begin()->first) + "'");
194 
195   if (!ForwardRefMDNodes.empty())
196     return Error(ForwardRefMDNodes.begin()->second.second,
197                  "use of undefined metadata '!" +
198                  Twine(ForwardRefMDNodes.begin()->first) + "'");
199 
200   // Resolve metadata cycles.
201   for (auto &N : NumberedMetadata) {
202     if (N.second && !N.second->isResolved())
203       N.second->resolveCycles();
204   }
205 
206   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
207     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
208 
209   // Look for intrinsic functions and CallInst that need to be upgraded
210   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
211     UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
212 
213   UpgradeDebugInfo(*M);
214 
215   UpgradeModuleFlags(*M);
216 
217   if (!Slots)
218     return false;
219   // Initialize the slot mapping.
220   // Because by this point we've parsed and validated everything, we can "steal"
221   // the mapping from LLParser as it doesn't need it anymore.
222   Slots->GlobalValues = std::move(NumberedVals);
223   Slots->MetadataNodes = std::move(NumberedMetadata);
224   for (const auto &I : NamedTypes)
225     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
226   for (const auto &I : NumberedTypes)
227     Slots->Types.insert(std::make_pair(I.first, I.second.first));
228 
229   return false;
230 }
231 
232 //===----------------------------------------------------------------------===//
233 // Top-Level Entities
234 //===----------------------------------------------------------------------===//
235 
236 bool LLParser::ParseTopLevelEntities() {
237   while (1) {
238     switch (Lex.getKind()) {
239     default:         return TokError("expected top-level entity");
240     case lltok::Eof: return false;
241     case lltok::kw_declare: if (ParseDeclare()) return true; break;
242     case lltok::kw_define:  if (ParseDefine()) return true; break;
243     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
244     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
245     case lltok::kw_source_filename:
246       if (ParseSourceFileName())
247         return true;
248       break;
249     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
250     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
251     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
252     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
253     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
254     case lltok::ComdatVar:  if (parseComdat()) return true; break;
255     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
256     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
257     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
258     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
259     case lltok::kw_uselistorder_bb:
260                                  if (ParseUseListOrderBB()) return true; break;
261     }
262   }
263 }
264 
265 
266 /// toplevelentity
267 ///   ::= 'module' 'asm' STRINGCONSTANT
268 bool LLParser::ParseModuleAsm() {
269   assert(Lex.getKind() == lltok::kw_module);
270   Lex.Lex();
271 
272   std::string AsmStr;
273   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
274       ParseStringConstant(AsmStr)) return true;
275 
276   M->appendModuleInlineAsm(AsmStr);
277   return false;
278 }
279 
280 /// toplevelentity
281 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
282 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
283 bool LLParser::ParseTargetDefinition() {
284   assert(Lex.getKind() == lltok::kw_target);
285   std::string Str;
286   switch (Lex.Lex()) {
287   default: return TokError("unknown target property");
288   case lltok::kw_triple:
289     Lex.Lex();
290     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
291         ParseStringConstant(Str))
292       return true;
293     M->setTargetTriple(Str);
294     return false;
295   case lltok::kw_datalayout:
296     Lex.Lex();
297     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
298         ParseStringConstant(Str))
299       return true;
300     M->setDataLayout(Str);
301     return false;
302   }
303 }
304 
305 /// toplevelentity
306 ///   ::= 'source_filename' '=' STRINGCONSTANT
307 bool LLParser::ParseSourceFileName() {
308   assert(Lex.getKind() == lltok::kw_source_filename);
309   std::string Str;
310   Lex.Lex();
311   if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
312       ParseStringConstant(Str))
313     return true;
314   M->setSourceFileName(Str);
315   return false;
316 }
317 
318 /// toplevelentity
319 ///   ::= 'deplibs' '=' '[' ']'
320 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
321 /// FIXME: Remove in 4.0. Currently parse, but ignore.
322 bool LLParser::ParseDepLibs() {
323   assert(Lex.getKind() == lltok::kw_deplibs);
324   Lex.Lex();
325   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
326       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
327     return true;
328 
329   if (EatIfPresent(lltok::rsquare))
330     return false;
331 
332   do {
333     std::string Str;
334     if (ParseStringConstant(Str)) return true;
335   } while (EatIfPresent(lltok::comma));
336 
337   return ParseToken(lltok::rsquare, "expected ']' at end of list");
338 }
339 
340 /// ParseUnnamedType:
341 ///   ::= LocalVarID '=' 'type' type
342 bool LLParser::ParseUnnamedType() {
343   LocTy TypeLoc = Lex.getLoc();
344   unsigned TypeID = Lex.getUIntVal();
345   Lex.Lex(); // eat LocalVarID;
346 
347   if (ParseToken(lltok::equal, "expected '=' after name") ||
348       ParseToken(lltok::kw_type, "expected 'type' after '='"))
349     return true;
350 
351   Type *Result = nullptr;
352   if (ParseStructDefinition(TypeLoc, "",
353                             NumberedTypes[TypeID], Result)) return true;
354 
355   if (!isa<StructType>(Result)) {
356     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
357     if (Entry.first)
358       return Error(TypeLoc, "non-struct types may not be recursive");
359     Entry.first = Result;
360     Entry.second = SMLoc();
361   }
362 
363   return false;
364 }
365 
366 
367 /// toplevelentity
368 ///   ::= LocalVar '=' 'type' type
369 bool LLParser::ParseNamedType() {
370   std::string Name = Lex.getStrVal();
371   LocTy NameLoc = Lex.getLoc();
372   Lex.Lex();  // eat LocalVar.
373 
374   if (ParseToken(lltok::equal, "expected '=' after name") ||
375       ParseToken(lltok::kw_type, "expected 'type' after name"))
376     return true;
377 
378   Type *Result = nullptr;
379   if (ParseStructDefinition(NameLoc, Name,
380                             NamedTypes[Name], Result)) return true;
381 
382   if (!isa<StructType>(Result)) {
383     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
384     if (Entry.first)
385       return Error(NameLoc, "non-struct types may not be recursive");
386     Entry.first = Result;
387     Entry.second = SMLoc();
388   }
389 
390   return false;
391 }
392 
393 
394 /// toplevelentity
395 ///   ::= 'declare' FunctionHeader
396 bool LLParser::ParseDeclare() {
397   assert(Lex.getKind() == lltok::kw_declare);
398   Lex.Lex();
399 
400   Function *F;
401   return ParseFunctionHeader(F, false);
402 }
403 
404 /// toplevelentity
405 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
406 bool LLParser::ParseDefine() {
407   assert(Lex.getKind() == lltok::kw_define);
408   Lex.Lex();
409 
410   Function *F;
411   return ParseFunctionHeader(F, true) ||
412          ParseOptionalFunctionMetadata(*F) ||
413          ParseFunctionBody(*F);
414 }
415 
416 /// ParseGlobalType
417 ///   ::= 'constant'
418 ///   ::= 'global'
419 bool LLParser::ParseGlobalType(bool &IsConstant) {
420   if (Lex.getKind() == lltok::kw_constant)
421     IsConstant = true;
422   else if (Lex.getKind() == lltok::kw_global)
423     IsConstant = false;
424   else {
425     IsConstant = false;
426     return TokError("expected 'global' or 'constant'");
427   }
428   Lex.Lex();
429   return false;
430 }
431 
432 bool LLParser::ParseOptionalUnnamedAddr(
433     GlobalVariable::UnnamedAddr &UnnamedAddr) {
434   if (EatIfPresent(lltok::kw_unnamed_addr))
435     UnnamedAddr = GlobalValue::UnnamedAddr::Global;
436   else if (EatIfPresent(lltok::kw_local_unnamed_addr))
437     UnnamedAddr = GlobalValue::UnnamedAddr::Local;
438   else
439     UnnamedAddr = GlobalValue::UnnamedAddr::None;
440   return false;
441 }
442 
443 /// ParseUnnamedGlobal:
444 ///   OptionalVisibility (ALIAS | IFUNC) ...
445 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
446 ///                                                     ...   -> global variable
447 ///   GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
448 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
449 ///                                                     ...   -> global variable
450 bool LLParser::ParseUnnamedGlobal() {
451   unsigned VarID = NumberedVals.size();
452   std::string Name;
453   LocTy NameLoc = Lex.getLoc();
454 
455   // Handle the GlobalID form.
456   if (Lex.getKind() == lltok::GlobalID) {
457     if (Lex.getUIntVal() != VarID)
458       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
459                    Twine(VarID) + "'");
460     Lex.Lex(); // eat GlobalID;
461 
462     if (ParseToken(lltok::equal, "expected '=' after name"))
463       return true;
464   }
465 
466   bool HasLinkage;
467   unsigned Linkage, Visibility, DLLStorageClass;
468   GlobalVariable::ThreadLocalMode TLM;
469   GlobalVariable::UnnamedAddr UnnamedAddr;
470   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
471       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
472     return true;
473 
474   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
475     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
476                        DLLStorageClass, TLM, UnnamedAddr);
477 
478   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
479                              DLLStorageClass, TLM, UnnamedAddr);
480 }
481 
482 /// ParseNamedGlobal:
483 ///   GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
484 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
485 ///                                                     ...   -> global variable
486 bool LLParser::ParseNamedGlobal() {
487   assert(Lex.getKind() == lltok::GlobalVar);
488   LocTy NameLoc = Lex.getLoc();
489   std::string Name = Lex.getStrVal();
490   Lex.Lex();
491 
492   bool HasLinkage;
493   unsigned Linkage, Visibility, DLLStorageClass;
494   GlobalVariable::ThreadLocalMode TLM;
495   GlobalVariable::UnnamedAddr UnnamedAddr;
496   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
497       ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
498       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
499     return true;
500 
501   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
502     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
503                        DLLStorageClass, TLM, UnnamedAddr);
504 
505   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
506                              DLLStorageClass, TLM, UnnamedAddr);
507 }
508 
509 bool LLParser::parseComdat() {
510   assert(Lex.getKind() == lltok::ComdatVar);
511   std::string Name = Lex.getStrVal();
512   LocTy NameLoc = Lex.getLoc();
513   Lex.Lex();
514 
515   if (ParseToken(lltok::equal, "expected '=' here"))
516     return true;
517 
518   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
519     return TokError("expected comdat type");
520 
521   Comdat::SelectionKind SK;
522   switch (Lex.getKind()) {
523   default:
524     return TokError("unknown selection kind");
525   case lltok::kw_any:
526     SK = Comdat::Any;
527     break;
528   case lltok::kw_exactmatch:
529     SK = Comdat::ExactMatch;
530     break;
531   case lltok::kw_largest:
532     SK = Comdat::Largest;
533     break;
534   case lltok::kw_noduplicates:
535     SK = Comdat::NoDuplicates;
536     break;
537   case lltok::kw_samesize:
538     SK = Comdat::SameSize;
539     break;
540   }
541   Lex.Lex();
542 
543   // See if the comdat was forward referenced, if so, use the comdat.
544   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
545   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
546   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
547     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
548 
549   Comdat *C;
550   if (I != ComdatSymTab.end())
551     C = &I->second;
552   else
553     C = M->getOrInsertComdat(Name);
554   C->setSelectionKind(SK);
555 
556   return false;
557 }
558 
559 // MDString:
560 //   ::= '!' STRINGCONSTANT
561 bool LLParser::ParseMDString(MDString *&Result) {
562   std::string Str;
563   if (ParseStringConstant(Str)) return true;
564   Result = MDString::get(Context, Str);
565   return false;
566 }
567 
568 // MDNode:
569 //   ::= '!' MDNodeNumber
570 bool LLParser::ParseMDNodeID(MDNode *&Result) {
571   // !{ ..., !42, ... }
572   LocTy IDLoc = Lex.getLoc();
573   unsigned MID = 0;
574   if (ParseUInt32(MID))
575     return true;
576 
577   // If not a forward reference, just return it now.
578   if (NumberedMetadata.count(MID)) {
579     Result = NumberedMetadata[MID];
580     return false;
581   }
582 
583   // Otherwise, create MDNode forward reference.
584   auto &FwdRef = ForwardRefMDNodes[MID];
585   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
586 
587   Result = FwdRef.first.get();
588   NumberedMetadata[MID].reset(Result);
589   return false;
590 }
591 
592 /// ParseNamedMetadata:
593 ///   !foo = !{ !1, !2 }
594 bool LLParser::ParseNamedMetadata() {
595   assert(Lex.getKind() == lltok::MetadataVar);
596   std::string Name = Lex.getStrVal();
597   Lex.Lex();
598 
599   if (ParseToken(lltok::equal, "expected '=' here") ||
600       ParseToken(lltok::exclaim, "Expected '!' here") ||
601       ParseToken(lltok::lbrace, "Expected '{' here"))
602     return true;
603 
604   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
605   if (Lex.getKind() != lltok::rbrace)
606     do {
607       if (ParseToken(lltok::exclaim, "Expected '!' here"))
608         return true;
609 
610       MDNode *N = nullptr;
611       if (ParseMDNodeID(N)) return true;
612       NMD->addOperand(N);
613     } while (EatIfPresent(lltok::comma));
614 
615   return ParseToken(lltok::rbrace, "expected end of metadata node");
616 }
617 
618 /// ParseStandaloneMetadata:
619 ///   !42 = !{...}
620 bool LLParser::ParseStandaloneMetadata() {
621   assert(Lex.getKind() == lltok::exclaim);
622   Lex.Lex();
623   unsigned MetadataID = 0;
624 
625   MDNode *Init;
626   if (ParseUInt32(MetadataID) ||
627       ParseToken(lltok::equal, "expected '=' here"))
628     return true;
629 
630   // Detect common error, from old metadata syntax.
631   if (Lex.getKind() == lltok::Type)
632     return TokError("unexpected type in metadata definition");
633 
634   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
635   if (Lex.getKind() == lltok::MetadataVar) {
636     if (ParseSpecializedMDNode(Init, IsDistinct))
637       return true;
638   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
639              ParseMDTuple(Init, IsDistinct))
640     return true;
641 
642   // See if this was forward referenced, if so, handle it.
643   auto FI = ForwardRefMDNodes.find(MetadataID);
644   if (FI != ForwardRefMDNodes.end()) {
645     FI->second.first->replaceAllUsesWith(Init);
646     ForwardRefMDNodes.erase(FI);
647 
648     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
649   } else {
650     if (NumberedMetadata.count(MetadataID))
651       return TokError("Metadata id is already used");
652     NumberedMetadata[MetadataID].reset(Init);
653   }
654 
655   return false;
656 }
657 
658 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
659   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
660          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
661 }
662 
663 /// parseIndirectSymbol:
664 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
665 ///                     OptionalDLLStorageClass OptionalThreadLocal
666 ///                     OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
667 ///
668 /// IndirectSymbol
669 ///   ::= TypeAndValue
670 ///
671 /// Everything through OptionalUnnamedAddr has already been parsed.
672 ///
673 bool LLParser::parseIndirectSymbol(
674     const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
675     unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
676     GlobalVariable::UnnamedAddr UnnamedAddr) {
677   bool IsAlias;
678   if (Lex.getKind() == lltok::kw_alias)
679     IsAlias = true;
680   else if (Lex.getKind() == lltok::kw_ifunc)
681     IsAlias = false;
682   else
683     llvm_unreachable("Not an alias or ifunc!");
684   Lex.Lex();
685 
686   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
687 
688   if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
689     return Error(NameLoc, "invalid linkage type for alias");
690 
691   if (!isValidVisibilityForLinkage(Visibility, L))
692     return Error(NameLoc,
693                  "symbol with local linkage must have default visibility");
694 
695   Type *Ty;
696   LocTy ExplicitTypeLoc = Lex.getLoc();
697   if (ParseType(Ty) ||
698       ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
699     return true;
700 
701   Constant *Aliasee;
702   LocTy AliaseeLoc = Lex.getLoc();
703   if (Lex.getKind() != lltok::kw_bitcast &&
704       Lex.getKind() != lltok::kw_getelementptr &&
705       Lex.getKind() != lltok::kw_addrspacecast &&
706       Lex.getKind() != lltok::kw_inttoptr) {
707     if (ParseGlobalTypeAndValue(Aliasee))
708       return true;
709   } else {
710     // The bitcast dest type is not present, it is implied by the dest type.
711     ValID ID;
712     if (ParseValID(ID))
713       return true;
714     if (ID.Kind != ValID::t_Constant)
715       return Error(AliaseeLoc, "invalid aliasee");
716     Aliasee = ID.ConstantVal;
717   }
718 
719   Type *AliaseeType = Aliasee->getType();
720   auto *PTy = dyn_cast<PointerType>(AliaseeType);
721   if (!PTy)
722     return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
723   unsigned AddrSpace = PTy->getAddressSpace();
724 
725   if (IsAlias && Ty != PTy->getElementType())
726     return Error(
727         ExplicitTypeLoc,
728         "explicit pointee type doesn't match operand's pointee type");
729 
730   if (!IsAlias && !PTy->getElementType()->isFunctionTy())
731     return Error(
732         ExplicitTypeLoc,
733         "explicit pointee type should be a function type");
734 
735   GlobalValue *GVal = nullptr;
736 
737   // See if the alias was forward referenced, if so, prepare to replace the
738   // forward reference.
739   if (!Name.empty()) {
740     GVal = M->getNamedValue(Name);
741     if (GVal) {
742       if (!ForwardRefVals.erase(Name))
743         return Error(NameLoc, "redefinition of global '@" + Name + "'");
744     }
745   } else {
746     auto I = ForwardRefValIDs.find(NumberedVals.size());
747     if (I != ForwardRefValIDs.end()) {
748       GVal = I->second.first;
749       ForwardRefValIDs.erase(I);
750     }
751   }
752 
753   // Okay, create the alias but do not insert it into the module yet.
754   std::unique_ptr<GlobalIndirectSymbol> GA;
755   if (IsAlias)
756     GA.reset(GlobalAlias::create(Ty, AddrSpace,
757                                  (GlobalValue::LinkageTypes)Linkage, Name,
758                                  Aliasee, /*Parent*/ nullptr));
759   else
760     GA.reset(GlobalIFunc::create(Ty, AddrSpace,
761                                  (GlobalValue::LinkageTypes)Linkage, Name,
762                                  Aliasee, /*Parent*/ nullptr));
763   GA->setThreadLocalMode(TLM);
764   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
765   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
766   GA->setUnnamedAddr(UnnamedAddr);
767 
768   if (Name.empty())
769     NumberedVals.push_back(GA.get());
770 
771   if (GVal) {
772     // Verify that types agree.
773     if (GVal->getType() != GA->getType())
774       return Error(
775           ExplicitTypeLoc,
776           "forward reference and definition of alias have different types");
777 
778     // If they agree, just RAUW the old value with the alias and remove the
779     // forward ref info.
780     GVal->replaceAllUsesWith(GA.get());
781     GVal->eraseFromParent();
782   }
783 
784   // Insert into the module, we know its name won't collide now.
785   if (IsAlias)
786     M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
787   else
788     M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
789   assert(GA->getName() == Name && "Should not be a name conflict!");
790 
791   // The module owns this now
792   GA.release();
793 
794   return false;
795 }
796 
797 /// ParseGlobal
798 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
799 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
800 ///       OptionalExternallyInitialized GlobalType Type Const
801 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
802 ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
803 ///       OptionalExternallyInitialized GlobalType Type Const
804 ///
805 /// Everything up to and including OptionalUnnamedAddr has been parsed
806 /// already.
807 ///
808 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
809                            unsigned Linkage, bool HasLinkage,
810                            unsigned Visibility, unsigned DLLStorageClass,
811                            GlobalVariable::ThreadLocalMode TLM,
812                            GlobalVariable::UnnamedAddr UnnamedAddr) {
813   if (!isValidVisibilityForLinkage(Visibility, Linkage))
814     return Error(NameLoc,
815                  "symbol with local linkage must have default visibility");
816 
817   unsigned AddrSpace;
818   bool IsConstant, IsExternallyInitialized;
819   LocTy IsExternallyInitializedLoc;
820   LocTy TyLoc;
821 
822   Type *Ty = nullptr;
823   if (ParseOptionalAddrSpace(AddrSpace) ||
824       ParseOptionalToken(lltok::kw_externally_initialized,
825                          IsExternallyInitialized,
826                          &IsExternallyInitializedLoc) ||
827       ParseGlobalType(IsConstant) ||
828       ParseType(Ty, TyLoc))
829     return true;
830 
831   // If the linkage is specified and is external, then no initializer is
832   // present.
833   Constant *Init = nullptr;
834   if (!HasLinkage ||
835       !GlobalValue::isValidDeclarationLinkage(
836           (GlobalValue::LinkageTypes)Linkage)) {
837     if (ParseGlobalValue(Ty, Init))
838       return true;
839   }
840 
841   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
842     return Error(TyLoc, "invalid type for global variable");
843 
844   GlobalValue *GVal = nullptr;
845 
846   // See if the global was forward referenced, if so, use the global.
847   if (!Name.empty()) {
848     GVal = M->getNamedValue(Name);
849     if (GVal) {
850       if (!ForwardRefVals.erase(Name))
851         return Error(NameLoc, "redefinition of global '@" + Name + "'");
852     }
853   } else {
854     auto I = ForwardRefValIDs.find(NumberedVals.size());
855     if (I != ForwardRefValIDs.end()) {
856       GVal = I->second.first;
857       ForwardRefValIDs.erase(I);
858     }
859   }
860 
861   GlobalVariable *GV;
862   if (!GVal) {
863     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
864                             Name, nullptr, GlobalVariable::NotThreadLocal,
865                             AddrSpace);
866   } else {
867     if (GVal->getValueType() != Ty)
868       return Error(TyLoc,
869             "forward reference and definition of global have different types");
870 
871     GV = cast<GlobalVariable>(GVal);
872 
873     // Move the forward-reference to the correct spot in the module.
874     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
875   }
876 
877   if (Name.empty())
878     NumberedVals.push_back(GV);
879 
880   // Set the parsed properties on the global.
881   if (Init)
882     GV->setInitializer(Init);
883   GV->setConstant(IsConstant);
884   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
885   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
886   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
887   GV->setExternallyInitialized(IsExternallyInitialized);
888   GV->setThreadLocalMode(TLM);
889   GV->setUnnamedAddr(UnnamedAddr);
890 
891   // Parse attributes on the global.
892   while (Lex.getKind() == lltok::comma) {
893     Lex.Lex();
894 
895     if (Lex.getKind() == lltok::kw_section) {
896       Lex.Lex();
897       GV->setSection(Lex.getStrVal());
898       if (ParseToken(lltok::StringConstant, "expected global section string"))
899         return true;
900     } else if (Lex.getKind() == lltok::kw_align) {
901       unsigned Alignment;
902       if (ParseOptionalAlignment(Alignment)) return true;
903       GV->setAlignment(Alignment);
904     } else if (Lex.getKind() == lltok::MetadataVar) {
905       if (ParseGlobalObjectMetadataAttachment(*GV))
906         return true;
907     } else {
908       Comdat *C;
909       if (parseOptionalComdat(Name, C))
910         return true;
911       if (C)
912         GV->setComdat(C);
913       else
914         return TokError("unknown global variable property!");
915     }
916   }
917 
918   return false;
919 }
920 
921 /// ParseUnnamedAttrGrp
922 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
923 bool LLParser::ParseUnnamedAttrGrp() {
924   assert(Lex.getKind() == lltok::kw_attributes);
925   LocTy AttrGrpLoc = Lex.getLoc();
926   Lex.Lex();
927 
928   if (Lex.getKind() != lltok::AttrGrpID)
929     return TokError("expected attribute group id");
930 
931   unsigned VarID = Lex.getUIntVal();
932   std::vector<unsigned> unused;
933   LocTy BuiltinLoc;
934   Lex.Lex();
935 
936   if (ParseToken(lltok::equal, "expected '=' here") ||
937       ParseToken(lltok::lbrace, "expected '{' here") ||
938       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
939                                  BuiltinLoc) ||
940       ParseToken(lltok::rbrace, "expected end of attribute group"))
941     return true;
942 
943   if (!NumberedAttrBuilders[VarID].hasAttributes())
944     return Error(AttrGrpLoc, "attribute group has no attributes");
945 
946   return false;
947 }
948 
949 /// ParseFnAttributeValuePairs
950 ///   ::= <attr> | <attr> '=' <value>
951 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
952                                           std::vector<unsigned> &FwdRefAttrGrps,
953                                           bool inAttrGrp, LocTy &BuiltinLoc) {
954   bool HaveError = false;
955 
956   B.clear();
957 
958   while (true) {
959     lltok::Kind Token = Lex.getKind();
960     if (Token == lltok::kw_builtin)
961       BuiltinLoc = Lex.getLoc();
962     switch (Token) {
963     default:
964       if (!inAttrGrp) return HaveError;
965       return Error(Lex.getLoc(), "unterminated attribute group");
966     case lltok::rbrace:
967       // Finished.
968       return false;
969 
970     case lltok::AttrGrpID: {
971       // Allow a function to reference an attribute group:
972       //
973       //   define void @foo() #1 { ... }
974       if (inAttrGrp)
975         HaveError |=
976           Error(Lex.getLoc(),
977               "cannot have an attribute group reference in an attribute group");
978 
979       unsigned AttrGrpNum = Lex.getUIntVal();
980       if (inAttrGrp) break;
981 
982       // Save the reference to the attribute group. We'll fill it in later.
983       FwdRefAttrGrps.push_back(AttrGrpNum);
984       break;
985     }
986     // Target-dependent attributes:
987     case lltok::StringConstant: {
988       if (ParseStringAttribute(B))
989         return true;
990       continue;
991     }
992 
993     // Target-independent attributes:
994     case lltok::kw_align: {
995       // As a hack, we allow function alignment to be initially parsed as an
996       // attribute on a function declaration/definition or added to an attribute
997       // group and later moved to the alignment field.
998       unsigned Alignment;
999       if (inAttrGrp) {
1000         Lex.Lex();
1001         if (ParseToken(lltok::equal, "expected '=' here") ||
1002             ParseUInt32(Alignment))
1003           return true;
1004       } else {
1005         if (ParseOptionalAlignment(Alignment))
1006           return true;
1007       }
1008       B.addAlignmentAttr(Alignment);
1009       continue;
1010     }
1011     case lltok::kw_alignstack: {
1012       unsigned Alignment;
1013       if (inAttrGrp) {
1014         Lex.Lex();
1015         if (ParseToken(lltok::equal, "expected '=' here") ||
1016             ParseUInt32(Alignment))
1017           return true;
1018       } else {
1019         if (ParseOptionalStackAlignment(Alignment))
1020           return true;
1021       }
1022       B.addStackAlignmentAttr(Alignment);
1023       continue;
1024     }
1025     case lltok::kw_allocsize: {
1026       unsigned ElemSizeArg;
1027       Optional<unsigned> NumElemsArg;
1028       // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1029       if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1030         return true;
1031       B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1032       continue;
1033     }
1034     case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1035     case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1036     case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1037     case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1038     case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1039     case lltok::kw_inaccessiblememonly:
1040       B.addAttribute(Attribute::InaccessibleMemOnly); break;
1041     case lltok::kw_inaccessiblemem_or_argmemonly:
1042       B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1043     case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1044     case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1045     case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1046     case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1047     case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1048     case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1049     case lltok::kw_noimplicitfloat:
1050       B.addAttribute(Attribute::NoImplicitFloat); break;
1051     case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1052     case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1053     case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1054     case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1055     case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1056     case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1057     case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1058     case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1059     case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1060     case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1061     case lltok::kw_returns_twice:
1062       B.addAttribute(Attribute::ReturnsTwice); break;
1063     case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1064     case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1065     case lltok::kw_sspstrong:
1066       B.addAttribute(Attribute::StackProtectStrong); break;
1067     case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1068     case lltok::kw_sanitize_address:
1069       B.addAttribute(Attribute::SanitizeAddress); break;
1070     case lltok::kw_sanitize_thread:
1071       B.addAttribute(Attribute::SanitizeThread); break;
1072     case lltok::kw_sanitize_memory:
1073       B.addAttribute(Attribute::SanitizeMemory); break;
1074     case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1075 
1076     // Error handling.
1077     case lltok::kw_inreg:
1078     case lltok::kw_signext:
1079     case lltok::kw_zeroext:
1080       HaveError |=
1081         Error(Lex.getLoc(),
1082               "invalid use of attribute on a function");
1083       break;
1084     case lltok::kw_byval:
1085     case lltok::kw_dereferenceable:
1086     case lltok::kw_dereferenceable_or_null:
1087     case lltok::kw_inalloca:
1088     case lltok::kw_nest:
1089     case lltok::kw_noalias:
1090     case lltok::kw_nocapture:
1091     case lltok::kw_nonnull:
1092     case lltok::kw_returned:
1093     case lltok::kw_sret:
1094     case lltok::kw_swifterror:
1095     case lltok::kw_swiftself:
1096       HaveError |=
1097         Error(Lex.getLoc(),
1098               "invalid use of parameter-only attribute on a function");
1099       break;
1100     }
1101 
1102     Lex.Lex();
1103   }
1104 }
1105 
1106 //===----------------------------------------------------------------------===//
1107 // GlobalValue Reference/Resolution Routines.
1108 //===----------------------------------------------------------------------===//
1109 
1110 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1111                                               const std::string &Name) {
1112   if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1113     return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1114   else
1115     return new GlobalVariable(*M, PTy->getElementType(), false,
1116                               GlobalValue::ExternalWeakLinkage, nullptr, Name,
1117                               nullptr, GlobalVariable::NotThreadLocal,
1118                               PTy->getAddressSpace());
1119 }
1120 
1121 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1122 /// forward reference record if needed.  This can return null if the value
1123 /// exists but does not have the right type.
1124 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1125                                     LocTy Loc) {
1126   PointerType *PTy = dyn_cast<PointerType>(Ty);
1127   if (!PTy) {
1128     Error(Loc, "global variable reference must have pointer type");
1129     return nullptr;
1130   }
1131 
1132   // Look this name up in the normal function symbol table.
1133   GlobalValue *Val =
1134     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1135 
1136   // If this is a forward reference for the value, see if we already created a
1137   // forward ref record.
1138   if (!Val) {
1139     auto I = ForwardRefVals.find(Name);
1140     if (I != ForwardRefVals.end())
1141       Val = I->second.first;
1142   }
1143 
1144   // If we have the value in the symbol table or fwd-ref table, return it.
1145   if (Val) {
1146     if (Val->getType() == Ty) return Val;
1147     Error(Loc, "'@" + Name + "' defined with type '" +
1148           getTypeString(Val->getType()) + "'");
1149     return nullptr;
1150   }
1151 
1152   // Otherwise, create a new forward reference for this value and remember it.
1153   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1154   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1155   return FwdVal;
1156 }
1157 
1158 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1159   PointerType *PTy = dyn_cast<PointerType>(Ty);
1160   if (!PTy) {
1161     Error(Loc, "global variable reference must have pointer type");
1162     return nullptr;
1163   }
1164 
1165   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1166 
1167   // If this is a forward reference for the value, see if we already created a
1168   // forward ref record.
1169   if (!Val) {
1170     auto I = ForwardRefValIDs.find(ID);
1171     if (I != ForwardRefValIDs.end())
1172       Val = I->second.first;
1173   }
1174 
1175   // If we have the value in the symbol table or fwd-ref table, return it.
1176   if (Val) {
1177     if (Val->getType() == Ty) return Val;
1178     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1179           getTypeString(Val->getType()) + "'");
1180     return nullptr;
1181   }
1182 
1183   // Otherwise, create a new forward reference for this value and remember it.
1184   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1185   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1186   return FwdVal;
1187 }
1188 
1189 
1190 //===----------------------------------------------------------------------===//
1191 // Comdat Reference/Resolution Routines.
1192 //===----------------------------------------------------------------------===//
1193 
1194 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1195   // Look this name up in the comdat symbol table.
1196   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1197   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1198   if (I != ComdatSymTab.end())
1199     return &I->second;
1200 
1201   // Otherwise, create a new forward reference for this value and remember it.
1202   Comdat *C = M->getOrInsertComdat(Name);
1203   ForwardRefComdats[Name] = Loc;
1204   return C;
1205 }
1206 
1207 
1208 //===----------------------------------------------------------------------===//
1209 // Helper Routines.
1210 //===----------------------------------------------------------------------===//
1211 
1212 /// ParseToken - If the current token has the specified kind, eat it and return
1213 /// success.  Otherwise, emit the specified error and return failure.
1214 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1215   if (Lex.getKind() != T)
1216     return TokError(ErrMsg);
1217   Lex.Lex();
1218   return false;
1219 }
1220 
1221 /// ParseStringConstant
1222 ///   ::= StringConstant
1223 bool LLParser::ParseStringConstant(std::string &Result) {
1224   if (Lex.getKind() != lltok::StringConstant)
1225     return TokError("expected string constant");
1226   Result = Lex.getStrVal();
1227   Lex.Lex();
1228   return false;
1229 }
1230 
1231 /// ParseUInt32
1232 ///   ::= uint32
1233 bool LLParser::ParseUInt32(unsigned &Val) {
1234   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1235     return TokError("expected integer");
1236   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1237   if (Val64 != unsigned(Val64))
1238     return TokError("expected 32-bit integer (too large)");
1239   Val = Val64;
1240   Lex.Lex();
1241   return false;
1242 }
1243 
1244 /// ParseUInt64
1245 ///   ::= uint64
1246 bool LLParser::ParseUInt64(uint64_t &Val) {
1247   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1248     return TokError("expected integer");
1249   Val = Lex.getAPSIntVal().getLimitedValue();
1250   Lex.Lex();
1251   return false;
1252 }
1253 
1254 /// ParseTLSModel
1255 ///   := 'localdynamic'
1256 ///   := 'initialexec'
1257 ///   := 'localexec'
1258 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1259   switch (Lex.getKind()) {
1260     default:
1261       return TokError("expected localdynamic, initialexec or localexec");
1262     case lltok::kw_localdynamic:
1263       TLM = GlobalVariable::LocalDynamicTLSModel;
1264       break;
1265     case lltok::kw_initialexec:
1266       TLM = GlobalVariable::InitialExecTLSModel;
1267       break;
1268     case lltok::kw_localexec:
1269       TLM = GlobalVariable::LocalExecTLSModel;
1270       break;
1271   }
1272 
1273   Lex.Lex();
1274   return false;
1275 }
1276 
1277 /// ParseOptionalThreadLocal
1278 ///   := /*empty*/
1279 ///   := 'thread_local'
1280 ///   := 'thread_local' '(' tlsmodel ')'
1281 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1282   TLM = GlobalVariable::NotThreadLocal;
1283   if (!EatIfPresent(lltok::kw_thread_local))
1284     return false;
1285 
1286   TLM = GlobalVariable::GeneralDynamicTLSModel;
1287   if (Lex.getKind() == lltok::lparen) {
1288     Lex.Lex();
1289     return ParseTLSModel(TLM) ||
1290       ParseToken(lltok::rparen, "expected ')' after thread local model");
1291   }
1292   return false;
1293 }
1294 
1295 /// ParseOptionalAddrSpace
1296 ///   := /*empty*/
1297 ///   := 'addrspace' '(' uint32 ')'
1298 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1299   AddrSpace = 0;
1300   if (!EatIfPresent(lltok::kw_addrspace))
1301     return false;
1302   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1303          ParseUInt32(AddrSpace) ||
1304          ParseToken(lltok::rparen, "expected ')' in address space");
1305 }
1306 
1307 /// ParseStringAttribute
1308 ///   := StringConstant
1309 ///   := StringConstant '=' StringConstant
1310 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1311   std::string Attr = Lex.getStrVal();
1312   Lex.Lex();
1313   std::string Val;
1314   if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1315     return true;
1316   B.addAttribute(Attr, Val);
1317   return false;
1318 }
1319 
1320 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1321 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1322   bool HaveError = false;
1323 
1324   B.clear();
1325 
1326   while (1) {
1327     lltok::Kind Token = Lex.getKind();
1328     switch (Token) {
1329     default:  // End of attributes.
1330       return HaveError;
1331     case lltok::StringConstant: {
1332       if (ParseStringAttribute(B))
1333         return true;
1334       continue;
1335     }
1336     case lltok::kw_align: {
1337       unsigned Alignment;
1338       if (ParseOptionalAlignment(Alignment))
1339         return true;
1340       B.addAlignmentAttr(Alignment);
1341       continue;
1342     }
1343     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1344     case lltok::kw_dereferenceable: {
1345       uint64_t Bytes;
1346       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1347         return true;
1348       B.addDereferenceableAttr(Bytes);
1349       continue;
1350     }
1351     case lltok::kw_dereferenceable_or_null: {
1352       uint64_t Bytes;
1353       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1354         return true;
1355       B.addDereferenceableOrNullAttr(Bytes);
1356       continue;
1357     }
1358     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1359     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1360     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1361     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1362     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1363     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1364     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1365     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1366     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1367     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1368     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1369     case lltok::kw_swifterror:      B.addAttribute(Attribute::SwiftError); break;
1370     case lltok::kw_swiftself:       B.addAttribute(Attribute::SwiftSelf); break;
1371     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1372 
1373     case lltok::kw_alignstack:
1374     case lltok::kw_alwaysinline:
1375     case lltok::kw_argmemonly:
1376     case lltok::kw_builtin:
1377     case lltok::kw_inlinehint:
1378     case lltok::kw_jumptable:
1379     case lltok::kw_minsize:
1380     case lltok::kw_naked:
1381     case lltok::kw_nobuiltin:
1382     case lltok::kw_noduplicate:
1383     case lltok::kw_noimplicitfloat:
1384     case lltok::kw_noinline:
1385     case lltok::kw_nonlazybind:
1386     case lltok::kw_noredzone:
1387     case lltok::kw_noreturn:
1388     case lltok::kw_nounwind:
1389     case lltok::kw_optnone:
1390     case lltok::kw_optsize:
1391     case lltok::kw_returns_twice:
1392     case lltok::kw_sanitize_address:
1393     case lltok::kw_sanitize_memory:
1394     case lltok::kw_sanitize_thread:
1395     case lltok::kw_ssp:
1396     case lltok::kw_sspreq:
1397     case lltok::kw_sspstrong:
1398     case lltok::kw_safestack:
1399     case lltok::kw_uwtable:
1400       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1401       break;
1402     }
1403 
1404     Lex.Lex();
1405   }
1406 }
1407 
1408 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1409 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1410   bool HaveError = false;
1411 
1412   B.clear();
1413 
1414   while (1) {
1415     lltok::Kind Token = Lex.getKind();
1416     switch (Token) {
1417     default:  // End of attributes.
1418       return HaveError;
1419     case lltok::StringConstant: {
1420       if (ParseStringAttribute(B))
1421         return true;
1422       continue;
1423     }
1424     case lltok::kw_dereferenceable: {
1425       uint64_t Bytes;
1426       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1427         return true;
1428       B.addDereferenceableAttr(Bytes);
1429       continue;
1430     }
1431     case lltok::kw_dereferenceable_or_null: {
1432       uint64_t Bytes;
1433       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1434         return true;
1435       B.addDereferenceableOrNullAttr(Bytes);
1436       continue;
1437     }
1438     case lltok::kw_align: {
1439       unsigned Alignment;
1440       if (ParseOptionalAlignment(Alignment))
1441         return true;
1442       B.addAlignmentAttr(Alignment);
1443       continue;
1444     }
1445     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1446     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1447     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1448     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1449     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1450 
1451     // Error handling.
1452     case lltok::kw_byval:
1453     case lltok::kw_inalloca:
1454     case lltok::kw_nest:
1455     case lltok::kw_nocapture:
1456     case lltok::kw_returned:
1457     case lltok::kw_sret:
1458     case lltok::kw_swifterror:
1459     case lltok::kw_swiftself:
1460       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1461       break;
1462 
1463     case lltok::kw_alignstack:
1464     case lltok::kw_alwaysinline:
1465     case lltok::kw_argmemonly:
1466     case lltok::kw_builtin:
1467     case lltok::kw_cold:
1468     case lltok::kw_inlinehint:
1469     case lltok::kw_jumptable:
1470     case lltok::kw_minsize:
1471     case lltok::kw_naked:
1472     case lltok::kw_nobuiltin:
1473     case lltok::kw_noduplicate:
1474     case lltok::kw_noimplicitfloat:
1475     case lltok::kw_noinline:
1476     case lltok::kw_nonlazybind:
1477     case lltok::kw_noredzone:
1478     case lltok::kw_noreturn:
1479     case lltok::kw_nounwind:
1480     case lltok::kw_optnone:
1481     case lltok::kw_optsize:
1482     case lltok::kw_returns_twice:
1483     case lltok::kw_sanitize_address:
1484     case lltok::kw_sanitize_memory:
1485     case lltok::kw_sanitize_thread:
1486     case lltok::kw_ssp:
1487     case lltok::kw_sspreq:
1488     case lltok::kw_sspstrong:
1489     case lltok::kw_safestack:
1490     case lltok::kw_uwtable:
1491       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1492       break;
1493 
1494     case lltok::kw_readnone:
1495     case lltok::kw_readonly:
1496       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1497     }
1498 
1499     Lex.Lex();
1500   }
1501 }
1502 
1503 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1504   HasLinkage = true;
1505   switch (Kind) {
1506   default:
1507     HasLinkage = false;
1508     return GlobalValue::ExternalLinkage;
1509   case lltok::kw_private:
1510     return GlobalValue::PrivateLinkage;
1511   case lltok::kw_internal:
1512     return GlobalValue::InternalLinkage;
1513   case lltok::kw_weak:
1514     return GlobalValue::WeakAnyLinkage;
1515   case lltok::kw_weak_odr:
1516     return GlobalValue::WeakODRLinkage;
1517   case lltok::kw_linkonce:
1518     return GlobalValue::LinkOnceAnyLinkage;
1519   case lltok::kw_linkonce_odr:
1520     return GlobalValue::LinkOnceODRLinkage;
1521   case lltok::kw_available_externally:
1522     return GlobalValue::AvailableExternallyLinkage;
1523   case lltok::kw_appending:
1524     return GlobalValue::AppendingLinkage;
1525   case lltok::kw_common:
1526     return GlobalValue::CommonLinkage;
1527   case lltok::kw_extern_weak:
1528     return GlobalValue::ExternalWeakLinkage;
1529   case lltok::kw_external:
1530     return GlobalValue::ExternalLinkage;
1531   }
1532 }
1533 
1534 /// ParseOptionalLinkage
1535 ///   ::= /*empty*/
1536 ///   ::= 'private'
1537 ///   ::= 'internal'
1538 ///   ::= 'weak'
1539 ///   ::= 'weak_odr'
1540 ///   ::= 'linkonce'
1541 ///   ::= 'linkonce_odr'
1542 ///   ::= 'available_externally'
1543 ///   ::= 'appending'
1544 ///   ::= 'common'
1545 ///   ::= 'extern_weak'
1546 ///   ::= 'external'
1547 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1548                                     unsigned &Visibility,
1549                                     unsigned &DLLStorageClass) {
1550   Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1551   if (HasLinkage)
1552     Lex.Lex();
1553   ParseOptionalVisibility(Visibility);
1554   ParseOptionalDLLStorageClass(DLLStorageClass);
1555   return false;
1556 }
1557 
1558 /// ParseOptionalVisibility
1559 ///   ::= /*empty*/
1560 ///   ::= 'default'
1561 ///   ::= 'hidden'
1562 ///   ::= 'protected'
1563 ///
1564 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1565   switch (Lex.getKind()) {
1566   default:
1567     Res = GlobalValue::DefaultVisibility;
1568     return;
1569   case lltok::kw_default:
1570     Res = GlobalValue::DefaultVisibility;
1571     break;
1572   case lltok::kw_hidden:
1573     Res = GlobalValue::HiddenVisibility;
1574     break;
1575   case lltok::kw_protected:
1576     Res = GlobalValue::ProtectedVisibility;
1577     break;
1578   }
1579   Lex.Lex();
1580 }
1581 
1582 /// ParseOptionalDLLStorageClass
1583 ///   ::= /*empty*/
1584 ///   ::= 'dllimport'
1585 ///   ::= 'dllexport'
1586 ///
1587 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1588   switch (Lex.getKind()) {
1589   default:
1590     Res = GlobalValue::DefaultStorageClass;
1591     return;
1592   case lltok::kw_dllimport:
1593     Res = GlobalValue::DLLImportStorageClass;
1594     break;
1595   case lltok::kw_dllexport:
1596     Res = GlobalValue::DLLExportStorageClass;
1597     break;
1598   }
1599   Lex.Lex();
1600 }
1601 
1602 /// ParseOptionalCallingConv
1603 ///   ::= /*empty*/
1604 ///   ::= 'ccc'
1605 ///   ::= 'fastcc'
1606 ///   ::= 'intel_ocl_bicc'
1607 ///   ::= 'coldcc'
1608 ///   ::= 'x86_stdcallcc'
1609 ///   ::= 'x86_fastcallcc'
1610 ///   ::= 'x86_thiscallcc'
1611 ///   ::= 'x86_vectorcallcc'
1612 ///   ::= 'arm_apcscc'
1613 ///   ::= 'arm_aapcscc'
1614 ///   ::= 'arm_aapcs_vfpcc'
1615 ///   ::= 'msp430_intrcc'
1616 ///   ::= 'avr_intrcc'
1617 ///   ::= 'avr_signalcc'
1618 ///   ::= 'ptx_kernel'
1619 ///   ::= 'ptx_device'
1620 ///   ::= 'spir_func'
1621 ///   ::= 'spir_kernel'
1622 ///   ::= 'x86_64_sysvcc'
1623 ///   ::= 'x86_64_win64cc'
1624 ///   ::= 'webkit_jscc'
1625 ///   ::= 'anyregcc'
1626 ///   ::= 'preserve_mostcc'
1627 ///   ::= 'preserve_allcc'
1628 ///   ::= 'ghccc'
1629 ///   ::= 'swiftcc'
1630 ///   ::= 'x86_intrcc'
1631 ///   ::= 'hhvmcc'
1632 ///   ::= 'hhvm_ccc'
1633 ///   ::= 'cxx_fast_tlscc'
1634 ///   ::= 'amdgpu_vs'
1635 ///   ::= 'amdgpu_tcs'
1636 ///   ::= 'amdgpu_tes'
1637 ///   ::= 'amdgpu_gs'
1638 ///   ::= 'amdgpu_ps'
1639 ///   ::= 'amdgpu_cs'
1640 ///   ::= 'amdgpu_kernel'
1641 ///   ::= 'cc' UINT
1642 ///
1643 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1644   switch (Lex.getKind()) {
1645   default:                       CC = CallingConv::C; return false;
1646   case lltok::kw_ccc:            CC = CallingConv::C; break;
1647   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1648   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1649   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1650   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1651   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1652   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1653   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1654   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1655   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1656   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1657   case lltok::kw_avr_intrcc:     CC = CallingConv::AVR_INTR; break;
1658   case lltok::kw_avr_signalcc:   CC = CallingConv::AVR_SIGNAL; break;
1659   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1660   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1661   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1662   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1663   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1664   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1665   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1666   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1667   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1668   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1669   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1670   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1671   case lltok::kw_swiftcc:        CC = CallingConv::Swift; break;
1672   case lltok::kw_x86_intrcc:     CC = CallingConv::X86_INTR; break;
1673   case lltok::kw_hhvmcc:         CC = CallingConv::HHVM; break;
1674   case lltok::kw_hhvm_ccc:       CC = CallingConv::HHVM_C; break;
1675   case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1676   case lltok::kw_amdgpu_vs:      CC = CallingConv::AMDGPU_VS; break;
1677   case lltok::kw_amdgpu_gs:      CC = CallingConv::AMDGPU_GS; break;
1678   case lltok::kw_amdgpu_ps:      CC = CallingConv::AMDGPU_PS; break;
1679   case lltok::kw_amdgpu_cs:      CC = CallingConv::AMDGPU_CS; break;
1680   case lltok::kw_amdgpu_kernel:  CC = CallingConv::AMDGPU_KERNEL; break;
1681   case lltok::kw_cc: {
1682       Lex.Lex();
1683       return ParseUInt32(CC);
1684     }
1685   }
1686 
1687   Lex.Lex();
1688   return false;
1689 }
1690 
1691 /// ParseMetadataAttachment
1692 ///   ::= !dbg !42
1693 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1694   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1695 
1696   std::string Name = Lex.getStrVal();
1697   Kind = M->getMDKindID(Name);
1698   Lex.Lex();
1699 
1700   return ParseMDNode(MD);
1701 }
1702 
1703 /// ParseInstructionMetadata
1704 ///   ::= !dbg !42 (',' !dbg !57)*
1705 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1706   do {
1707     if (Lex.getKind() != lltok::MetadataVar)
1708       return TokError("expected metadata after comma");
1709 
1710     unsigned MDK;
1711     MDNode *N;
1712     if (ParseMetadataAttachment(MDK, N))
1713       return true;
1714 
1715     Inst.setMetadata(MDK, N);
1716     if (MDK == LLVMContext::MD_tbaa)
1717       InstsWithTBAATag.push_back(&Inst);
1718 
1719     // If this is the end of the list, we're done.
1720   } while (EatIfPresent(lltok::comma));
1721   return false;
1722 }
1723 
1724 /// ParseGlobalObjectMetadataAttachment
1725 ///   ::= !dbg !57
1726 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1727   unsigned MDK;
1728   MDNode *N;
1729   if (ParseMetadataAttachment(MDK, N))
1730     return true;
1731 
1732   GO.addMetadata(MDK, *N);
1733   return false;
1734 }
1735 
1736 /// ParseOptionalFunctionMetadata
1737 ///   ::= (!dbg !57)*
1738 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1739   while (Lex.getKind() == lltok::MetadataVar)
1740     if (ParseGlobalObjectMetadataAttachment(F))
1741       return true;
1742   return false;
1743 }
1744 
1745 /// ParseOptionalAlignment
1746 ///   ::= /* empty */
1747 ///   ::= 'align' 4
1748 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1749   Alignment = 0;
1750   if (!EatIfPresent(lltok::kw_align))
1751     return false;
1752   LocTy AlignLoc = Lex.getLoc();
1753   if (ParseUInt32(Alignment)) return true;
1754   if (!isPowerOf2_32(Alignment))
1755     return Error(AlignLoc, "alignment is not a power of two");
1756   if (Alignment > Value::MaximumAlignment)
1757     return Error(AlignLoc, "huge alignments are not supported yet");
1758   return false;
1759 }
1760 
1761 /// ParseOptionalDerefAttrBytes
1762 ///   ::= /* empty */
1763 ///   ::= AttrKind '(' 4 ')'
1764 ///
1765 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1766 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1767                                            uint64_t &Bytes) {
1768   assert((AttrKind == lltok::kw_dereferenceable ||
1769           AttrKind == lltok::kw_dereferenceable_or_null) &&
1770          "contract!");
1771 
1772   Bytes = 0;
1773   if (!EatIfPresent(AttrKind))
1774     return false;
1775   LocTy ParenLoc = Lex.getLoc();
1776   if (!EatIfPresent(lltok::lparen))
1777     return Error(ParenLoc, "expected '('");
1778   LocTy DerefLoc = Lex.getLoc();
1779   if (ParseUInt64(Bytes)) return true;
1780   ParenLoc = Lex.getLoc();
1781   if (!EatIfPresent(lltok::rparen))
1782     return Error(ParenLoc, "expected ')'");
1783   if (!Bytes)
1784     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1785   return false;
1786 }
1787 
1788 /// ParseOptionalCommaAlign
1789 ///   ::=
1790 ///   ::= ',' align 4
1791 ///
1792 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1793 /// end.
1794 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1795                                        bool &AteExtraComma) {
1796   AteExtraComma = false;
1797   while (EatIfPresent(lltok::comma)) {
1798     // Metadata at the end is an early exit.
1799     if (Lex.getKind() == lltok::MetadataVar) {
1800       AteExtraComma = true;
1801       return false;
1802     }
1803 
1804     if (Lex.getKind() != lltok::kw_align)
1805       return Error(Lex.getLoc(), "expected metadata or 'align'");
1806 
1807     if (ParseOptionalAlignment(Alignment)) return true;
1808   }
1809 
1810   return false;
1811 }
1812 
1813 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1814                                        Optional<unsigned> &HowManyArg) {
1815   Lex.Lex();
1816 
1817   auto StartParen = Lex.getLoc();
1818   if (!EatIfPresent(lltok::lparen))
1819     return Error(StartParen, "expected '('");
1820 
1821   if (ParseUInt32(BaseSizeArg))
1822     return true;
1823 
1824   if (EatIfPresent(lltok::comma)) {
1825     auto HowManyAt = Lex.getLoc();
1826     unsigned HowMany;
1827     if (ParseUInt32(HowMany))
1828       return true;
1829     if (HowMany == BaseSizeArg)
1830       return Error(HowManyAt,
1831                    "'allocsize' indices can't refer to the same parameter");
1832     HowManyArg = HowMany;
1833   } else
1834     HowManyArg = None;
1835 
1836   auto EndParen = Lex.getLoc();
1837   if (!EatIfPresent(lltok::rparen))
1838     return Error(EndParen, "expected ')'");
1839   return false;
1840 }
1841 
1842 /// ParseScopeAndOrdering
1843 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1844 ///   else: ::=
1845 ///
1846 /// This sets Scope and Ordering to the parsed values.
1847 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1848                                      AtomicOrdering &Ordering) {
1849   if (!isAtomic)
1850     return false;
1851 
1852   Scope = CrossThread;
1853   if (EatIfPresent(lltok::kw_singlethread))
1854     Scope = SingleThread;
1855 
1856   return ParseOrdering(Ordering);
1857 }
1858 
1859 /// ParseOrdering
1860 ///   ::= AtomicOrdering
1861 ///
1862 /// This sets Ordering to the parsed value.
1863 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1864   switch (Lex.getKind()) {
1865   default: return TokError("Expected ordering on atomic instruction");
1866   case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1867   case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1868   // Not specified yet:
1869   // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1870   case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1871   case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1872   case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1873   case lltok::kw_seq_cst:
1874     Ordering = AtomicOrdering::SequentiallyConsistent;
1875     break;
1876   }
1877   Lex.Lex();
1878   return false;
1879 }
1880 
1881 /// ParseOptionalStackAlignment
1882 ///   ::= /* empty */
1883 ///   ::= 'alignstack' '(' 4 ')'
1884 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1885   Alignment = 0;
1886   if (!EatIfPresent(lltok::kw_alignstack))
1887     return false;
1888   LocTy ParenLoc = Lex.getLoc();
1889   if (!EatIfPresent(lltok::lparen))
1890     return Error(ParenLoc, "expected '('");
1891   LocTy AlignLoc = Lex.getLoc();
1892   if (ParseUInt32(Alignment)) return true;
1893   ParenLoc = Lex.getLoc();
1894   if (!EatIfPresent(lltok::rparen))
1895     return Error(ParenLoc, "expected ')'");
1896   if (!isPowerOf2_32(Alignment))
1897     return Error(AlignLoc, "stack alignment is not a power of two");
1898   return false;
1899 }
1900 
1901 /// ParseIndexList - This parses the index list for an insert/extractvalue
1902 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1903 /// comma at the end of the line and find that it is followed by metadata.
1904 /// Clients that don't allow metadata can call the version of this function that
1905 /// only takes one argument.
1906 ///
1907 /// ParseIndexList
1908 ///    ::=  (',' uint32)+
1909 ///
1910 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1911                               bool &AteExtraComma) {
1912   AteExtraComma = false;
1913 
1914   if (Lex.getKind() != lltok::comma)
1915     return TokError("expected ',' as start of index list");
1916 
1917   while (EatIfPresent(lltok::comma)) {
1918     if (Lex.getKind() == lltok::MetadataVar) {
1919       if (Indices.empty()) return TokError("expected index");
1920       AteExtraComma = true;
1921       return false;
1922     }
1923     unsigned Idx = 0;
1924     if (ParseUInt32(Idx)) return true;
1925     Indices.push_back(Idx);
1926   }
1927 
1928   return false;
1929 }
1930 
1931 //===----------------------------------------------------------------------===//
1932 // Type Parsing.
1933 //===----------------------------------------------------------------------===//
1934 
1935 /// ParseType - Parse a type.
1936 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1937   SMLoc TypeLoc = Lex.getLoc();
1938   switch (Lex.getKind()) {
1939   default:
1940     return TokError(Msg);
1941   case lltok::Type:
1942     // Type ::= 'float' | 'void' (etc)
1943     Result = Lex.getTyVal();
1944     Lex.Lex();
1945     break;
1946   case lltok::lbrace:
1947     // Type ::= StructType
1948     if (ParseAnonStructType(Result, false))
1949       return true;
1950     break;
1951   case lltok::lsquare:
1952     // Type ::= '[' ... ']'
1953     Lex.Lex(); // eat the lsquare.
1954     if (ParseArrayVectorType(Result, false))
1955       return true;
1956     break;
1957   case lltok::less: // Either vector or packed struct.
1958     // Type ::= '<' ... '>'
1959     Lex.Lex();
1960     if (Lex.getKind() == lltok::lbrace) {
1961       if (ParseAnonStructType(Result, true) ||
1962           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1963         return true;
1964     } else if (ParseArrayVectorType(Result, true))
1965       return true;
1966     break;
1967   case lltok::LocalVar: {
1968     // Type ::= %foo
1969     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1970 
1971     // If the type hasn't been defined yet, create a forward definition and
1972     // remember where that forward def'n was seen (in case it never is defined).
1973     if (!Entry.first) {
1974       Entry.first = StructType::create(Context, Lex.getStrVal());
1975       Entry.second = Lex.getLoc();
1976     }
1977     Result = Entry.first;
1978     Lex.Lex();
1979     break;
1980   }
1981 
1982   case lltok::LocalVarID: {
1983     // Type ::= %4
1984     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1985 
1986     // If the type hasn't been defined yet, create a forward definition and
1987     // remember where that forward def'n was seen (in case it never is defined).
1988     if (!Entry.first) {
1989       Entry.first = StructType::create(Context);
1990       Entry.second = Lex.getLoc();
1991     }
1992     Result = Entry.first;
1993     Lex.Lex();
1994     break;
1995   }
1996   }
1997 
1998   // Parse the type suffixes.
1999   while (1) {
2000     switch (Lex.getKind()) {
2001     // End of type.
2002     default:
2003       if (!AllowVoid && Result->isVoidTy())
2004         return Error(TypeLoc, "void type only allowed for function results");
2005       return false;
2006 
2007     // Type ::= Type '*'
2008     case lltok::star:
2009       if (Result->isLabelTy())
2010         return TokError("basic block pointers are invalid");
2011       if (Result->isVoidTy())
2012         return TokError("pointers to void are invalid - use i8* instead");
2013       if (!PointerType::isValidElementType(Result))
2014         return TokError("pointer to this type is invalid");
2015       Result = PointerType::getUnqual(Result);
2016       Lex.Lex();
2017       break;
2018 
2019     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2020     case lltok::kw_addrspace: {
2021       if (Result->isLabelTy())
2022         return TokError("basic block pointers are invalid");
2023       if (Result->isVoidTy())
2024         return TokError("pointers to void are invalid; use i8* instead");
2025       if (!PointerType::isValidElementType(Result))
2026         return TokError("pointer to this type is invalid");
2027       unsigned AddrSpace;
2028       if (ParseOptionalAddrSpace(AddrSpace) ||
2029           ParseToken(lltok::star, "expected '*' in address space"))
2030         return true;
2031 
2032       Result = PointerType::get(Result, AddrSpace);
2033       break;
2034     }
2035 
2036     /// Types '(' ArgTypeListI ')' OptFuncAttrs
2037     case lltok::lparen:
2038       if (ParseFunctionType(Result))
2039         return true;
2040       break;
2041     }
2042   }
2043 }
2044 
2045 /// ParseParameterList
2046 ///    ::= '(' ')'
2047 ///    ::= '(' Arg (',' Arg)* ')'
2048 ///  Arg
2049 ///    ::= Type OptionalAttributes Value OptionalAttributes
2050 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2051                                   PerFunctionState &PFS, bool IsMustTailCall,
2052                                   bool InVarArgsFunc) {
2053   if (ParseToken(lltok::lparen, "expected '(' in call"))
2054     return true;
2055 
2056   unsigned AttrIndex = 1;
2057   while (Lex.getKind() != lltok::rparen) {
2058     // If this isn't the first argument, we need a comma.
2059     if (!ArgList.empty() &&
2060         ParseToken(lltok::comma, "expected ',' in argument list"))
2061       return true;
2062 
2063     // Parse an ellipsis if this is a musttail call in a variadic function.
2064     if (Lex.getKind() == lltok::dotdotdot) {
2065       const char *Msg = "unexpected ellipsis in argument list for ";
2066       if (!IsMustTailCall)
2067         return TokError(Twine(Msg) + "non-musttail call");
2068       if (!InVarArgsFunc)
2069         return TokError(Twine(Msg) + "musttail call in non-varargs function");
2070       Lex.Lex();  // Lex the '...', it is purely for readability.
2071       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2072     }
2073 
2074     // Parse the argument.
2075     LocTy ArgLoc;
2076     Type *ArgTy = nullptr;
2077     AttrBuilder ArgAttrs;
2078     Value *V;
2079     if (ParseType(ArgTy, ArgLoc))
2080       return true;
2081 
2082     if (ArgTy->isMetadataTy()) {
2083       if (ParseMetadataAsValue(V, PFS))
2084         return true;
2085     } else {
2086       // Otherwise, handle normal operands.
2087       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2088         return true;
2089     }
2090     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2091                                                              AttrIndex++,
2092                                                              ArgAttrs)));
2093   }
2094 
2095   if (IsMustTailCall && InVarArgsFunc)
2096     return TokError("expected '...' at end of argument list for musttail call "
2097                     "in varargs function");
2098 
2099   Lex.Lex();  // Lex the ')'.
2100   return false;
2101 }
2102 
2103 /// ParseOptionalOperandBundles
2104 ///    ::= /*empty*/
2105 ///    ::= '[' OperandBundle [, OperandBundle ]* ']'
2106 ///
2107 /// OperandBundle
2108 ///    ::= bundle-tag '(' ')'
2109 ///    ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2110 ///
2111 /// bundle-tag ::= String Constant
2112 bool LLParser::ParseOptionalOperandBundles(
2113     SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2114   LocTy BeginLoc = Lex.getLoc();
2115   if (!EatIfPresent(lltok::lsquare))
2116     return false;
2117 
2118   while (Lex.getKind() != lltok::rsquare) {
2119     // If this isn't the first operand bundle, we need a comma.
2120     if (!BundleList.empty() &&
2121         ParseToken(lltok::comma, "expected ',' in input list"))
2122       return true;
2123 
2124     std::string Tag;
2125     if (ParseStringConstant(Tag))
2126       return true;
2127 
2128     if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2129       return true;
2130 
2131     std::vector<Value *> Inputs;
2132     while (Lex.getKind() != lltok::rparen) {
2133       // If this isn't the first input, we need a comma.
2134       if (!Inputs.empty() &&
2135           ParseToken(lltok::comma, "expected ',' in input list"))
2136         return true;
2137 
2138       Type *Ty = nullptr;
2139       Value *Input = nullptr;
2140       if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2141         return true;
2142       Inputs.push_back(Input);
2143     }
2144 
2145     BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2146 
2147     Lex.Lex(); // Lex the ')'.
2148   }
2149 
2150   if (BundleList.empty())
2151     return Error(BeginLoc, "operand bundle set must not be empty");
2152 
2153   Lex.Lex(); // Lex the ']'.
2154   return false;
2155 }
2156 
2157 /// ParseArgumentList - Parse the argument list for a function type or function
2158 /// prototype.
2159 ///   ::= '(' ArgTypeListI ')'
2160 /// ArgTypeListI
2161 ///   ::= /*empty*/
2162 ///   ::= '...'
2163 ///   ::= ArgTypeList ',' '...'
2164 ///   ::= ArgType (',' ArgType)*
2165 ///
2166 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2167                                  bool &isVarArg){
2168   isVarArg = false;
2169   assert(Lex.getKind() == lltok::lparen);
2170   Lex.Lex(); // eat the (.
2171 
2172   if (Lex.getKind() == lltok::rparen) {
2173     // empty
2174   } else if (Lex.getKind() == lltok::dotdotdot) {
2175     isVarArg = true;
2176     Lex.Lex();
2177   } else {
2178     LocTy TypeLoc = Lex.getLoc();
2179     Type *ArgTy = nullptr;
2180     AttrBuilder Attrs;
2181     std::string Name;
2182 
2183     if (ParseType(ArgTy) ||
2184         ParseOptionalParamAttrs(Attrs)) return true;
2185 
2186     if (ArgTy->isVoidTy())
2187       return Error(TypeLoc, "argument can not have void type");
2188 
2189     if (Lex.getKind() == lltok::LocalVar) {
2190       Name = Lex.getStrVal();
2191       Lex.Lex();
2192     }
2193 
2194     if (!FunctionType::isValidArgumentType(ArgTy))
2195       return Error(TypeLoc, "invalid type for function argument");
2196 
2197     unsigned AttrIndex = 1;
2198     ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2199                                                            AttrIndex++, Attrs),
2200                          std::move(Name));
2201 
2202     while (EatIfPresent(lltok::comma)) {
2203       // Handle ... at end of arg list.
2204       if (EatIfPresent(lltok::dotdotdot)) {
2205         isVarArg = true;
2206         break;
2207       }
2208 
2209       // Otherwise must be an argument type.
2210       TypeLoc = Lex.getLoc();
2211       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2212 
2213       if (ArgTy->isVoidTy())
2214         return Error(TypeLoc, "argument can not have void type");
2215 
2216       if (Lex.getKind() == lltok::LocalVar) {
2217         Name = Lex.getStrVal();
2218         Lex.Lex();
2219       } else {
2220         Name = "";
2221       }
2222 
2223       if (!ArgTy->isFirstClassType())
2224         return Error(TypeLoc, "invalid type for function argument");
2225 
2226       ArgList.emplace_back(
2227           TypeLoc, ArgTy,
2228           AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2229           std::move(Name));
2230     }
2231   }
2232 
2233   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2234 }
2235 
2236 /// ParseFunctionType
2237 ///  ::= Type ArgumentList OptionalAttrs
2238 bool LLParser::ParseFunctionType(Type *&Result) {
2239   assert(Lex.getKind() == lltok::lparen);
2240 
2241   if (!FunctionType::isValidReturnType(Result))
2242     return TokError("invalid function return type");
2243 
2244   SmallVector<ArgInfo, 8> ArgList;
2245   bool isVarArg;
2246   if (ParseArgumentList(ArgList, isVarArg))
2247     return true;
2248 
2249   // Reject names on the arguments lists.
2250   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2251     if (!ArgList[i].Name.empty())
2252       return Error(ArgList[i].Loc, "argument name invalid in function type");
2253     if (ArgList[i].Attrs.hasAttributes(i + 1))
2254       return Error(ArgList[i].Loc,
2255                    "argument attributes invalid in function type");
2256   }
2257 
2258   SmallVector<Type*, 16> ArgListTy;
2259   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2260     ArgListTy.push_back(ArgList[i].Ty);
2261 
2262   Result = FunctionType::get(Result, ArgListTy, isVarArg);
2263   return false;
2264 }
2265 
2266 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2267 /// other structs.
2268 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2269   SmallVector<Type*, 8> Elts;
2270   if (ParseStructBody(Elts)) return true;
2271 
2272   Result = StructType::get(Context, Elts, Packed);
2273   return false;
2274 }
2275 
2276 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2277 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2278                                      std::pair<Type*, LocTy> &Entry,
2279                                      Type *&ResultTy) {
2280   // If the type was already defined, diagnose the redefinition.
2281   if (Entry.first && !Entry.second.isValid())
2282     return Error(TypeLoc, "redefinition of type");
2283 
2284   // If we have opaque, just return without filling in the definition for the
2285   // struct.  This counts as a definition as far as the .ll file goes.
2286   if (EatIfPresent(lltok::kw_opaque)) {
2287     // This type is being defined, so clear the location to indicate this.
2288     Entry.second = SMLoc();
2289 
2290     // If this type number has never been uttered, create it.
2291     if (!Entry.first)
2292       Entry.first = StructType::create(Context, Name);
2293     ResultTy = Entry.first;
2294     return false;
2295   }
2296 
2297   // If the type starts with '<', then it is either a packed struct or a vector.
2298   bool isPacked = EatIfPresent(lltok::less);
2299 
2300   // If we don't have a struct, then we have a random type alias, which we
2301   // accept for compatibility with old files.  These types are not allowed to be
2302   // forward referenced and not allowed to be recursive.
2303   if (Lex.getKind() != lltok::lbrace) {
2304     if (Entry.first)
2305       return Error(TypeLoc, "forward references to non-struct type");
2306 
2307     ResultTy = nullptr;
2308     if (isPacked)
2309       return ParseArrayVectorType(ResultTy, true);
2310     return ParseType(ResultTy);
2311   }
2312 
2313   // This type is being defined, so clear the location to indicate this.
2314   Entry.second = SMLoc();
2315 
2316   // If this type number has never been uttered, create it.
2317   if (!Entry.first)
2318     Entry.first = StructType::create(Context, Name);
2319 
2320   StructType *STy = cast<StructType>(Entry.first);
2321 
2322   SmallVector<Type*, 8> Body;
2323   if (ParseStructBody(Body) ||
2324       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2325     return true;
2326 
2327   STy->setBody(Body, isPacked);
2328   ResultTy = STy;
2329   return false;
2330 }
2331 
2332 
2333 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2334 ///   StructType
2335 ///     ::= '{' '}'
2336 ///     ::= '{' Type (',' Type)* '}'
2337 ///     ::= '<' '{' '}' '>'
2338 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2339 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2340   assert(Lex.getKind() == lltok::lbrace);
2341   Lex.Lex(); // Consume the '{'
2342 
2343   // Handle the empty struct.
2344   if (EatIfPresent(lltok::rbrace))
2345     return false;
2346 
2347   LocTy EltTyLoc = Lex.getLoc();
2348   Type *Ty = nullptr;
2349   if (ParseType(Ty)) return true;
2350   Body.push_back(Ty);
2351 
2352   if (!StructType::isValidElementType(Ty))
2353     return Error(EltTyLoc, "invalid element type for struct");
2354 
2355   while (EatIfPresent(lltok::comma)) {
2356     EltTyLoc = Lex.getLoc();
2357     if (ParseType(Ty)) return true;
2358 
2359     if (!StructType::isValidElementType(Ty))
2360       return Error(EltTyLoc, "invalid element type for struct");
2361 
2362     Body.push_back(Ty);
2363   }
2364 
2365   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2366 }
2367 
2368 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2369 /// token has already been consumed.
2370 ///   Type
2371 ///     ::= '[' APSINTVAL 'x' Types ']'
2372 ///     ::= '<' APSINTVAL 'x' Types '>'
2373 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2374   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2375       Lex.getAPSIntVal().getBitWidth() > 64)
2376     return TokError("expected number in address space");
2377 
2378   LocTy SizeLoc = Lex.getLoc();
2379   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2380   Lex.Lex();
2381 
2382   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2383       return true;
2384 
2385   LocTy TypeLoc = Lex.getLoc();
2386   Type *EltTy = nullptr;
2387   if (ParseType(EltTy)) return true;
2388 
2389   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2390                  "expected end of sequential type"))
2391     return true;
2392 
2393   if (isVector) {
2394     if (Size == 0)
2395       return Error(SizeLoc, "zero element vector is illegal");
2396     if ((unsigned)Size != Size)
2397       return Error(SizeLoc, "size too large for vector");
2398     if (!VectorType::isValidElementType(EltTy))
2399       return Error(TypeLoc, "invalid vector element type");
2400     Result = VectorType::get(EltTy, unsigned(Size));
2401   } else {
2402     if (!ArrayType::isValidElementType(EltTy))
2403       return Error(TypeLoc, "invalid array element type");
2404     Result = ArrayType::get(EltTy, Size);
2405   }
2406   return false;
2407 }
2408 
2409 //===----------------------------------------------------------------------===//
2410 // Function Semantic Analysis.
2411 //===----------------------------------------------------------------------===//
2412 
2413 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2414                                              int functionNumber)
2415   : P(p), F(f), FunctionNumber(functionNumber) {
2416 
2417   // Insert unnamed arguments into the NumberedVals list.
2418   for (Argument &A : F.args())
2419     if (!A.hasName())
2420       NumberedVals.push_back(&A);
2421 }
2422 
2423 LLParser::PerFunctionState::~PerFunctionState() {
2424   // If there were any forward referenced non-basicblock values, delete them.
2425 
2426   for (const auto &P : ForwardRefVals) {
2427     if (isa<BasicBlock>(P.second.first))
2428       continue;
2429     P.second.first->replaceAllUsesWith(
2430         UndefValue::get(P.second.first->getType()));
2431     delete P.second.first;
2432   }
2433 
2434   for (const auto &P : ForwardRefValIDs) {
2435     if (isa<BasicBlock>(P.second.first))
2436       continue;
2437     P.second.first->replaceAllUsesWith(
2438         UndefValue::get(P.second.first->getType()));
2439     delete P.second.first;
2440   }
2441 }
2442 
2443 bool LLParser::PerFunctionState::FinishFunction() {
2444   if (!ForwardRefVals.empty())
2445     return P.Error(ForwardRefVals.begin()->second.second,
2446                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2447                    "'");
2448   if (!ForwardRefValIDs.empty())
2449     return P.Error(ForwardRefValIDs.begin()->second.second,
2450                    "use of undefined value '%" +
2451                    Twine(ForwardRefValIDs.begin()->first) + "'");
2452   return false;
2453 }
2454 
2455 
2456 /// GetVal - Get a value with the specified name or ID, creating a
2457 /// forward reference record if needed.  This can return null if the value
2458 /// exists but does not have the right type.
2459 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2460                                           LocTy Loc) {
2461   // Look this name up in the normal function symbol table.
2462   Value *Val = F.getValueSymbolTable().lookup(Name);
2463 
2464   // If this is a forward reference for the value, see if we already created a
2465   // forward ref record.
2466   if (!Val) {
2467     auto I = ForwardRefVals.find(Name);
2468     if (I != ForwardRefVals.end())
2469       Val = I->second.first;
2470   }
2471 
2472   // If we have the value in the symbol table or fwd-ref table, return it.
2473   if (Val) {
2474     if (Val->getType() == Ty) return Val;
2475     if (Ty->isLabelTy())
2476       P.Error(Loc, "'%" + Name + "' is not a basic block");
2477     else
2478       P.Error(Loc, "'%" + Name + "' defined with type '" +
2479               getTypeString(Val->getType()) + "'");
2480     return nullptr;
2481   }
2482 
2483   // Don't make placeholders with invalid type.
2484   if (!Ty->isFirstClassType()) {
2485     P.Error(Loc, "invalid use of a non-first-class type");
2486     return nullptr;
2487   }
2488 
2489   // Otherwise, create a new forward reference for this value and remember it.
2490   Value *FwdVal;
2491   if (Ty->isLabelTy()) {
2492     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2493   } else {
2494     FwdVal = new Argument(Ty, Name);
2495   }
2496 
2497   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2498   return FwdVal;
2499 }
2500 
2501 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2502   // Look this name up in the normal function symbol table.
2503   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2504 
2505   // If this is a forward reference for the value, see if we already created a
2506   // forward ref record.
2507   if (!Val) {
2508     auto I = ForwardRefValIDs.find(ID);
2509     if (I != ForwardRefValIDs.end())
2510       Val = I->second.first;
2511   }
2512 
2513   // If we have the value in the symbol table or fwd-ref table, return it.
2514   if (Val) {
2515     if (Val->getType() == Ty) return Val;
2516     if (Ty->isLabelTy())
2517       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2518     else
2519       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2520               getTypeString(Val->getType()) + "'");
2521     return nullptr;
2522   }
2523 
2524   if (!Ty->isFirstClassType()) {
2525     P.Error(Loc, "invalid use of a non-first-class type");
2526     return nullptr;
2527   }
2528 
2529   // Otherwise, create a new forward reference for this value and remember it.
2530   Value *FwdVal;
2531   if (Ty->isLabelTy()) {
2532     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2533   } else {
2534     FwdVal = new Argument(Ty);
2535   }
2536 
2537   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2538   return FwdVal;
2539 }
2540 
2541 /// SetInstName - After an instruction is parsed and inserted into its
2542 /// basic block, this installs its name.
2543 bool LLParser::PerFunctionState::SetInstName(int NameID,
2544                                              const std::string &NameStr,
2545                                              LocTy NameLoc, Instruction *Inst) {
2546   // If this instruction has void type, it cannot have a name or ID specified.
2547   if (Inst->getType()->isVoidTy()) {
2548     if (NameID != -1 || !NameStr.empty())
2549       return P.Error(NameLoc, "instructions returning void cannot have a name");
2550     return false;
2551   }
2552 
2553   // If this was a numbered instruction, verify that the instruction is the
2554   // expected value and resolve any forward references.
2555   if (NameStr.empty()) {
2556     // If neither a name nor an ID was specified, just use the next ID.
2557     if (NameID == -1)
2558       NameID = NumberedVals.size();
2559 
2560     if (unsigned(NameID) != NumberedVals.size())
2561       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2562                      Twine(NumberedVals.size()) + "'");
2563 
2564     auto FI = ForwardRefValIDs.find(NameID);
2565     if (FI != ForwardRefValIDs.end()) {
2566       Value *Sentinel = FI->second.first;
2567       if (Sentinel->getType() != Inst->getType())
2568         return P.Error(NameLoc, "instruction forward referenced with type '" +
2569                        getTypeString(FI->second.first->getType()) + "'");
2570 
2571       Sentinel->replaceAllUsesWith(Inst);
2572       delete Sentinel;
2573       ForwardRefValIDs.erase(FI);
2574     }
2575 
2576     NumberedVals.push_back(Inst);
2577     return false;
2578   }
2579 
2580   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2581   auto FI = ForwardRefVals.find(NameStr);
2582   if (FI != ForwardRefVals.end()) {
2583     Value *Sentinel = FI->second.first;
2584     if (Sentinel->getType() != Inst->getType())
2585       return P.Error(NameLoc, "instruction forward referenced with type '" +
2586                      getTypeString(FI->second.first->getType()) + "'");
2587 
2588     Sentinel->replaceAllUsesWith(Inst);
2589     delete Sentinel;
2590     ForwardRefVals.erase(FI);
2591   }
2592 
2593   // Set the name on the instruction.
2594   Inst->setName(NameStr);
2595 
2596   if (Inst->getName() != NameStr)
2597     return P.Error(NameLoc, "multiple definition of local value named '" +
2598                    NameStr + "'");
2599   return false;
2600 }
2601 
2602 /// GetBB - Get a basic block with the specified name or ID, creating a
2603 /// forward reference record if needed.
2604 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2605                                               LocTy Loc) {
2606   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2607                                       Type::getLabelTy(F.getContext()), Loc));
2608 }
2609 
2610 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2611   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2612                                       Type::getLabelTy(F.getContext()), Loc));
2613 }
2614 
2615 /// DefineBB - Define the specified basic block, which is either named or
2616 /// unnamed.  If there is an error, this returns null otherwise it returns
2617 /// the block being defined.
2618 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2619                                                  LocTy Loc) {
2620   BasicBlock *BB;
2621   if (Name.empty())
2622     BB = GetBB(NumberedVals.size(), Loc);
2623   else
2624     BB = GetBB(Name, Loc);
2625   if (!BB) return nullptr; // Already diagnosed error.
2626 
2627   // Move the block to the end of the function.  Forward ref'd blocks are
2628   // inserted wherever they happen to be referenced.
2629   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2630 
2631   // Remove the block from forward ref sets.
2632   if (Name.empty()) {
2633     ForwardRefValIDs.erase(NumberedVals.size());
2634     NumberedVals.push_back(BB);
2635   } else {
2636     // BB forward references are already in the function symbol table.
2637     ForwardRefVals.erase(Name);
2638   }
2639 
2640   return BB;
2641 }
2642 
2643 //===----------------------------------------------------------------------===//
2644 // Constants.
2645 //===----------------------------------------------------------------------===//
2646 
2647 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2648 /// type implied.  For example, if we parse "4" we don't know what integer type
2649 /// it has.  The value will later be combined with its type and checked for
2650 /// sanity.  PFS is used to convert function-local operands of metadata (since
2651 /// metadata operands are not just parsed here but also converted to values).
2652 /// PFS can be null when we are not parsing metadata values inside a function.
2653 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2654   ID.Loc = Lex.getLoc();
2655   switch (Lex.getKind()) {
2656   default: return TokError("expected value token");
2657   case lltok::GlobalID:  // @42
2658     ID.UIntVal = Lex.getUIntVal();
2659     ID.Kind = ValID::t_GlobalID;
2660     break;
2661   case lltok::GlobalVar:  // @foo
2662     ID.StrVal = Lex.getStrVal();
2663     ID.Kind = ValID::t_GlobalName;
2664     break;
2665   case lltok::LocalVarID:  // %42
2666     ID.UIntVal = Lex.getUIntVal();
2667     ID.Kind = ValID::t_LocalID;
2668     break;
2669   case lltok::LocalVar:  // %foo
2670     ID.StrVal = Lex.getStrVal();
2671     ID.Kind = ValID::t_LocalName;
2672     break;
2673   case lltok::APSInt:
2674     ID.APSIntVal = Lex.getAPSIntVal();
2675     ID.Kind = ValID::t_APSInt;
2676     break;
2677   case lltok::APFloat:
2678     ID.APFloatVal = Lex.getAPFloatVal();
2679     ID.Kind = ValID::t_APFloat;
2680     break;
2681   case lltok::kw_true:
2682     ID.ConstantVal = ConstantInt::getTrue(Context);
2683     ID.Kind = ValID::t_Constant;
2684     break;
2685   case lltok::kw_false:
2686     ID.ConstantVal = ConstantInt::getFalse(Context);
2687     ID.Kind = ValID::t_Constant;
2688     break;
2689   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2690   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2691   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2692   case lltok::kw_none: ID.Kind = ValID::t_None; break;
2693 
2694   case lltok::lbrace: {
2695     // ValID ::= '{' ConstVector '}'
2696     Lex.Lex();
2697     SmallVector<Constant*, 16> Elts;
2698     if (ParseGlobalValueVector(Elts) ||
2699         ParseToken(lltok::rbrace, "expected end of struct constant"))
2700       return true;
2701 
2702     ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2703     ID.UIntVal = Elts.size();
2704     memcpy(ID.ConstantStructElts.get(), Elts.data(),
2705            Elts.size() * sizeof(Elts[0]));
2706     ID.Kind = ValID::t_ConstantStruct;
2707     return false;
2708   }
2709   case lltok::less: {
2710     // ValID ::= '<' ConstVector '>'         --> Vector.
2711     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2712     Lex.Lex();
2713     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2714 
2715     SmallVector<Constant*, 16> Elts;
2716     LocTy FirstEltLoc = Lex.getLoc();
2717     if (ParseGlobalValueVector(Elts) ||
2718         (isPackedStruct &&
2719          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2720         ParseToken(lltok::greater, "expected end of constant"))
2721       return true;
2722 
2723     if (isPackedStruct) {
2724       ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2725       memcpy(ID.ConstantStructElts.get(), Elts.data(),
2726              Elts.size() * sizeof(Elts[0]));
2727       ID.UIntVal = Elts.size();
2728       ID.Kind = ValID::t_PackedConstantStruct;
2729       return false;
2730     }
2731 
2732     if (Elts.empty())
2733       return Error(ID.Loc, "constant vector must not be empty");
2734 
2735     if (!Elts[0]->getType()->isIntegerTy() &&
2736         !Elts[0]->getType()->isFloatingPointTy() &&
2737         !Elts[0]->getType()->isPointerTy())
2738       return Error(FirstEltLoc,
2739             "vector elements must have integer, pointer or floating point type");
2740 
2741     // Verify that all the vector elements have the same type.
2742     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2743       if (Elts[i]->getType() != Elts[0]->getType())
2744         return Error(FirstEltLoc,
2745                      "vector element #" + Twine(i) +
2746                     " is not of type '" + getTypeString(Elts[0]->getType()));
2747 
2748     ID.ConstantVal = ConstantVector::get(Elts);
2749     ID.Kind = ValID::t_Constant;
2750     return false;
2751   }
2752   case lltok::lsquare: {   // Array Constant
2753     Lex.Lex();
2754     SmallVector<Constant*, 16> Elts;
2755     LocTy FirstEltLoc = Lex.getLoc();
2756     if (ParseGlobalValueVector(Elts) ||
2757         ParseToken(lltok::rsquare, "expected end of array constant"))
2758       return true;
2759 
2760     // Handle empty element.
2761     if (Elts.empty()) {
2762       // Use undef instead of an array because it's inconvenient to determine
2763       // the element type at this point, there being no elements to examine.
2764       ID.Kind = ValID::t_EmptyArray;
2765       return false;
2766     }
2767 
2768     if (!Elts[0]->getType()->isFirstClassType())
2769       return Error(FirstEltLoc, "invalid array element type: " +
2770                    getTypeString(Elts[0]->getType()));
2771 
2772     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2773 
2774     // Verify all elements are correct type!
2775     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2776       if (Elts[i]->getType() != Elts[0]->getType())
2777         return Error(FirstEltLoc,
2778                      "array element #" + Twine(i) +
2779                      " is not of type '" + getTypeString(Elts[0]->getType()));
2780     }
2781 
2782     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2783     ID.Kind = ValID::t_Constant;
2784     return false;
2785   }
2786   case lltok::kw_c:  // c "foo"
2787     Lex.Lex();
2788     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2789                                                   false);
2790     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2791     ID.Kind = ValID::t_Constant;
2792     return false;
2793 
2794   case lltok::kw_asm: {
2795     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2796     //             STRINGCONSTANT
2797     bool HasSideEffect, AlignStack, AsmDialect;
2798     Lex.Lex();
2799     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2800         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2801         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2802         ParseStringConstant(ID.StrVal) ||
2803         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2804         ParseToken(lltok::StringConstant, "expected constraint string"))
2805       return true;
2806     ID.StrVal2 = Lex.getStrVal();
2807     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2808       (unsigned(AsmDialect)<<2);
2809     ID.Kind = ValID::t_InlineAsm;
2810     return false;
2811   }
2812 
2813   case lltok::kw_blockaddress: {
2814     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2815     Lex.Lex();
2816 
2817     ValID Fn, Label;
2818 
2819     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2820         ParseValID(Fn) ||
2821         ParseToken(lltok::comma, "expected comma in block address expression")||
2822         ParseValID(Label) ||
2823         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2824       return true;
2825 
2826     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2827       return Error(Fn.Loc, "expected function name in blockaddress");
2828     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2829       return Error(Label.Loc, "expected basic block name in blockaddress");
2830 
2831     // Try to find the function (but skip it if it's forward-referenced).
2832     GlobalValue *GV = nullptr;
2833     if (Fn.Kind == ValID::t_GlobalID) {
2834       if (Fn.UIntVal < NumberedVals.size())
2835         GV = NumberedVals[Fn.UIntVal];
2836     } else if (!ForwardRefVals.count(Fn.StrVal)) {
2837       GV = M->getNamedValue(Fn.StrVal);
2838     }
2839     Function *F = nullptr;
2840     if (GV) {
2841       // Confirm that it's actually a function with a definition.
2842       if (!isa<Function>(GV))
2843         return Error(Fn.Loc, "expected function name in blockaddress");
2844       F = cast<Function>(GV);
2845       if (F->isDeclaration())
2846         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2847     }
2848 
2849     if (!F) {
2850       // Make a global variable as a placeholder for this reference.
2851       GlobalValue *&FwdRef =
2852           ForwardRefBlockAddresses.insert(std::make_pair(
2853                                               std::move(Fn),
2854                                               std::map<ValID, GlobalValue *>()))
2855               .first->second.insert(std::make_pair(std::move(Label), nullptr))
2856               .first->second;
2857       if (!FwdRef)
2858         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2859                                     GlobalValue::InternalLinkage, nullptr, "");
2860       ID.ConstantVal = FwdRef;
2861       ID.Kind = ValID::t_Constant;
2862       return false;
2863     }
2864 
2865     // We found the function; now find the basic block.  Don't use PFS, since we
2866     // might be inside a constant expression.
2867     BasicBlock *BB;
2868     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2869       if (Label.Kind == ValID::t_LocalID)
2870         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2871       else
2872         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2873       if (!BB)
2874         return Error(Label.Loc, "referenced value is not a basic block");
2875     } else {
2876       if (Label.Kind == ValID::t_LocalID)
2877         return Error(Label.Loc, "cannot take address of numeric label after "
2878                                 "the function is defined");
2879       BB = dyn_cast_or_null<BasicBlock>(
2880           F->getValueSymbolTable().lookup(Label.StrVal));
2881       if (!BB)
2882         return Error(Label.Loc, "referenced value is not a basic block");
2883     }
2884 
2885     ID.ConstantVal = BlockAddress::get(F, BB);
2886     ID.Kind = ValID::t_Constant;
2887     return false;
2888   }
2889 
2890   case lltok::kw_trunc:
2891   case lltok::kw_zext:
2892   case lltok::kw_sext:
2893   case lltok::kw_fptrunc:
2894   case lltok::kw_fpext:
2895   case lltok::kw_bitcast:
2896   case lltok::kw_addrspacecast:
2897   case lltok::kw_uitofp:
2898   case lltok::kw_sitofp:
2899   case lltok::kw_fptoui:
2900   case lltok::kw_fptosi:
2901   case lltok::kw_inttoptr:
2902   case lltok::kw_ptrtoint: {
2903     unsigned Opc = Lex.getUIntVal();
2904     Type *DestTy = nullptr;
2905     Constant *SrcVal;
2906     Lex.Lex();
2907     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2908         ParseGlobalTypeAndValue(SrcVal) ||
2909         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2910         ParseType(DestTy) ||
2911         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2912       return true;
2913     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2914       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2915                    getTypeString(SrcVal->getType()) + "' to '" +
2916                    getTypeString(DestTy) + "'");
2917     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2918                                                  SrcVal, DestTy);
2919     ID.Kind = ValID::t_Constant;
2920     return false;
2921   }
2922   case lltok::kw_extractvalue: {
2923     Lex.Lex();
2924     Constant *Val;
2925     SmallVector<unsigned, 4> Indices;
2926     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2927         ParseGlobalTypeAndValue(Val) ||
2928         ParseIndexList(Indices) ||
2929         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2930       return true;
2931 
2932     if (!Val->getType()->isAggregateType())
2933       return Error(ID.Loc, "extractvalue operand must be aggregate type");
2934     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2935       return Error(ID.Loc, "invalid indices for extractvalue");
2936     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2937     ID.Kind = ValID::t_Constant;
2938     return false;
2939   }
2940   case lltok::kw_insertvalue: {
2941     Lex.Lex();
2942     Constant *Val0, *Val1;
2943     SmallVector<unsigned, 4> Indices;
2944     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2945         ParseGlobalTypeAndValue(Val0) ||
2946         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2947         ParseGlobalTypeAndValue(Val1) ||
2948         ParseIndexList(Indices) ||
2949         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2950       return true;
2951     if (!Val0->getType()->isAggregateType())
2952       return Error(ID.Loc, "insertvalue operand must be aggregate type");
2953     Type *IndexedType =
2954         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2955     if (!IndexedType)
2956       return Error(ID.Loc, "invalid indices for insertvalue");
2957     if (IndexedType != Val1->getType())
2958       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2959                                getTypeString(Val1->getType()) +
2960                                "' instead of '" + getTypeString(IndexedType) +
2961                                "'");
2962     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2963     ID.Kind = ValID::t_Constant;
2964     return false;
2965   }
2966   case lltok::kw_icmp:
2967   case lltok::kw_fcmp: {
2968     unsigned PredVal, Opc = Lex.getUIntVal();
2969     Constant *Val0, *Val1;
2970     Lex.Lex();
2971     if (ParseCmpPredicate(PredVal, Opc) ||
2972         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2973         ParseGlobalTypeAndValue(Val0) ||
2974         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2975         ParseGlobalTypeAndValue(Val1) ||
2976         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2977       return true;
2978 
2979     if (Val0->getType() != Val1->getType())
2980       return Error(ID.Loc, "compare operands must have the same type");
2981 
2982     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2983 
2984     if (Opc == Instruction::FCmp) {
2985       if (!Val0->getType()->isFPOrFPVectorTy())
2986         return Error(ID.Loc, "fcmp requires floating point operands");
2987       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2988     } else {
2989       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2990       if (!Val0->getType()->isIntOrIntVectorTy() &&
2991           !Val0->getType()->getScalarType()->isPointerTy())
2992         return Error(ID.Loc, "icmp requires pointer or integer operands");
2993       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2994     }
2995     ID.Kind = ValID::t_Constant;
2996     return false;
2997   }
2998 
2999   // Binary Operators.
3000   case lltok::kw_add:
3001   case lltok::kw_fadd:
3002   case lltok::kw_sub:
3003   case lltok::kw_fsub:
3004   case lltok::kw_mul:
3005   case lltok::kw_fmul:
3006   case lltok::kw_udiv:
3007   case lltok::kw_sdiv:
3008   case lltok::kw_fdiv:
3009   case lltok::kw_urem:
3010   case lltok::kw_srem:
3011   case lltok::kw_frem:
3012   case lltok::kw_shl:
3013   case lltok::kw_lshr:
3014   case lltok::kw_ashr: {
3015     bool NUW = false;
3016     bool NSW = false;
3017     bool Exact = false;
3018     unsigned Opc = Lex.getUIntVal();
3019     Constant *Val0, *Val1;
3020     Lex.Lex();
3021     LocTy ModifierLoc = Lex.getLoc();
3022     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3023         Opc == Instruction::Mul || Opc == Instruction::Shl) {
3024       if (EatIfPresent(lltok::kw_nuw))
3025         NUW = true;
3026       if (EatIfPresent(lltok::kw_nsw)) {
3027         NSW = true;
3028         if (EatIfPresent(lltok::kw_nuw))
3029           NUW = true;
3030       }
3031     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3032                Opc == Instruction::LShr || Opc == Instruction::AShr) {
3033       if (EatIfPresent(lltok::kw_exact))
3034         Exact = true;
3035     }
3036     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3037         ParseGlobalTypeAndValue(Val0) ||
3038         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3039         ParseGlobalTypeAndValue(Val1) ||
3040         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3041       return true;
3042     if (Val0->getType() != Val1->getType())
3043       return Error(ID.Loc, "operands of constexpr must have same type");
3044     if (!Val0->getType()->isIntOrIntVectorTy()) {
3045       if (NUW)
3046         return Error(ModifierLoc, "nuw only applies to integer operations");
3047       if (NSW)
3048         return Error(ModifierLoc, "nsw only applies to integer operations");
3049     }
3050     // Check that the type is valid for the operator.
3051     switch (Opc) {
3052     case Instruction::Add:
3053     case Instruction::Sub:
3054     case Instruction::Mul:
3055     case Instruction::UDiv:
3056     case Instruction::SDiv:
3057     case Instruction::URem:
3058     case Instruction::SRem:
3059     case Instruction::Shl:
3060     case Instruction::AShr:
3061     case Instruction::LShr:
3062       if (!Val0->getType()->isIntOrIntVectorTy())
3063         return Error(ID.Loc, "constexpr requires integer operands");
3064       break;
3065     case Instruction::FAdd:
3066     case Instruction::FSub:
3067     case Instruction::FMul:
3068     case Instruction::FDiv:
3069     case Instruction::FRem:
3070       if (!Val0->getType()->isFPOrFPVectorTy())
3071         return Error(ID.Loc, "constexpr requires fp operands");
3072       break;
3073     default: llvm_unreachable("Unknown binary operator!");
3074     }
3075     unsigned Flags = 0;
3076     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3077     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
3078     if (Exact) Flags |= PossiblyExactOperator::IsExact;
3079     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3080     ID.ConstantVal = C;
3081     ID.Kind = ValID::t_Constant;
3082     return false;
3083   }
3084 
3085   // Logical Operations
3086   case lltok::kw_and:
3087   case lltok::kw_or:
3088   case lltok::kw_xor: {
3089     unsigned Opc = Lex.getUIntVal();
3090     Constant *Val0, *Val1;
3091     Lex.Lex();
3092     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3093         ParseGlobalTypeAndValue(Val0) ||
3094         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3095         ParseGlobalTypeAndValue(Val1) ||
3096         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3097       return true;
3098     if (Val0->getType() != Val1->getType())
3099       return Error(ID.Loc, "operands of constexpr must have same type");
3100     if (!Val0->getType()->isIntOrIntVectorTy())
3101       return Error(ID.Loc,
3102                    "constexpr requires integer or integer vector operands");
3103     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3104     ID.Kind = ValID::t_Constant;
3105     return false;
3106   }
3107 
3108   case lltok::kw_getelementptr:
3109   case lltok::kw_shufflevector:
3110   case lltok::kw_insertelement:
3111   case lltok::kw_extractelement:
3112   case lltok::kw_select: {
3113     unsigned Opc = Lex.getUIntVal();
3114     SmallVector<Constant*, 16> Elts;
3115     bool InBounds = false;
3116     Type *Ty;
3117     Lex.Lex();
3118 
3119     if (Opc == Instruction::GetElementPtr)
3120       InBounds = EatIfPresent(lltok::kw_inbounds);
3121 
3122     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3123       return true;
3124 
3125     LocTy ExplicitTypeLoc = Lex.getLoc();
3126     if (Opc == Instruction::GetElementPtr) {
3127       if (ParseType(Ty) ||
3128           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3129         return true;
3130     }
3131 
3132     if (ParseGlobalValueVector(Elts) ||
3133         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3134       return true;
3135 
3136     if (Opc == Instruction::GetElementPtr) {
3137       if (Elts.size() == 0 ||
3138           !Elts[0]->getType()->getScalarType()->isPointerTy())
3139         return Error(ID.Loc, "base of getelementptr must be a pointer");
3140 
3141       Type *BaseType = Elts[0]->getType();
3142       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3143       if (Ty != BasePointerType->getElementType())
3144         return Error(
3145             ExplicitTypeLoc,
3146             "explicit pointee type doesn't match operand's pointee type");
3147 
3148       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3149       for (Constant *Val : Indices) {
3150         Type *ValTy = Val->getType();
3151         if (!ValTy->getScalarType()->isIntegerTy())
3152           return Error(ID.Loc, "getelementptr index must be an integer");
3153         if (ValTy->isVectorTy() != BaseType->isVectorTy())
3154           return Error(ID.Loc, "getelementptr index type missmatch");
3155         if (ValTy->isVectorTy()) {
3156           unsigned ValNumEl = ValTy->getVectorNumElements();
3157           unsigned PtrNumEl = BaseType->getVectorNumElements();
3158           if (ValNumEl != PtrNumEl)
3159             return Error(
3160                 ID.Loc,
3161                 "getelementptr vector index has a wrong number of elements");
3162         }
3163       }
3164 
3165       SmallPtrSet<Type*, 4> Visited;
3166       if (!Indices.empty() && !Ty->isSized(&Visited))
3167         return Error(ID.Loc, "base element of getelementptr must be sized");
3168 
3169       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3170         return Error(ID.Loc, "invalid getelementptr indices");
3171       ID.ConstantVal =
3172           ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
3173     } else if (Opc == Instruction::Select) {
3174       if (Elts.size() != 3)
3175         return Error(ID.Loc, "expected three operands to select");
3176       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3177                                                               Elts[2]))
3178         return Error(ID.Loc, Reason);
3179       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3180     } else if (Opc == Instruction::ShuffleVector) {
3181       if (Elts.size() != 3)
3182         return Error(ID.Loc, "expected three operands to shufflevector");
3183       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3184         return Error(ID.Loc, "invalid operands to shufflevector");
3185       ID.ConstantVal =
3186                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3187     } else if (Opc == Instruction::ExtractElement) {
3188       if (Elts.size() != 2)
3189         return Error(ID.Loc, "expected two operands to extractelement");
3190       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3191         return Error(ID.Loc, "invalid extractelement operands");
3192       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3193     } else {
3194       assert(Opc == Instruction::InsertElement && "Unknown opcode");
3195       if (Elts.size() != 3)
3196       return Error(ID.Loc, "expected three operands to insertelement");
3197       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3198         return Error(ID.Loc, "invalid insertelement operands");
3199       ID.ConstantVal =
3200                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3201     }
3202 
3203     ID.Kind = ValID::t_Constant;
3204     return false;
3205   }
3206   }
3207 
3208   Lex.Lex();
3209   return false;
3210 }
3211 
3212 /// ParseGlobalValue - Parse a global value with the specified type.
3213 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3214   C = nullptr;
3215   ValID ID;
3216   Value *V = nullptr;
3217   bool Parsed = ParseValID(ID) ||
3218                 ConvertValIDToValue(Ty, ID, V, nullptr);
3219   if (V && !(C = dyn_cast<Constant>(V)))
3220     return Error(ID.Loc, "global values must be constants");
3221   return Parsed;
3222 }
3223 
3224 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3225   Type *Ty = nullptr;
3226   return ParseType(Ty) ||
3227          ParseGlobalValue(Ty, V);
3228 }
3229 
3230 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3231   C = nullptr;
3232 
3233   LocTy KwLoc = Lex.getLoc();
3234   if (!EatIfPresent(lltok::kw_comdat))
3235     return false;
3236 
3237   if (EatIfPresent(lltok::lparen)) {
3238     if (Lex.getKind() != lltok::ComdatVar)
3239       return TokError("expected comdat variable");
3240     C = getComdat(Lex.getStrVal(), Lex.getLoc());
3241     Lex.Lex();
3242     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3243       return true;
3244   } else {
3245     if (GlobalName.empty())
3246       return TokError("comdat cannot be unnamed");
3247     C = getComdat(GlobalName, KwLoc);
3248   }
3249 
3250   return false;
3251 }
3252 
3253 /// ParseGlobalValueVector
3254 ///   ::= /*empty*/
3255 ///   ::= TypeAndValue (',' TypeAndValue)*
3256 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
3257   // Empty list.
3258   if (Lex.getKind() == lltok::rbrace ||
3259       Lex.getKind() == lltok::rsquare ||
3260       Lex.getKind() == lltok::greater ||
3261       Lex.getKind() == lltok::rparen)
3262     return false;
3263 
3264   Constant *C;
3265   if (ParseGlobalTypeAndValue(C)) return true;
3266   Elts.push_back(C);
3267 
3268   while (EatIfPresent(lltok::comma)) {
3269     if (ParseGlobalTypeAndValue(C)) return true;
3270     Elts.push_back(C);
3271   }
3272 
3273   return false;
3274 }
3275 
3276 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3277   SmallVector<Metadata *, 16> Elts;
3278   if (ParseMDNodeVector(Elts))
3279     return true;
3280 
3281   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3282   return false;
3283 }
3284 
3285 /// MDNode:
3286 ///  ::= !{ ... }
3287 ///  ::= !7
3288 ///  ::= !DILocation(...)
3289 bool LLParser::ParseMDNode(MDNode *&N) {
3290   if (Lex.getKind() == lltok::MetadataVar)
3291     return ParseSpecializedMDNode(N);
3292 
3293   return ParseToken(lltok::exclaim, "expected '!' here") ||
3294          ParseMDNodeTail(N);
3295 }
3296 
3297 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3298   // !{ ... }
3299   if (Lex.getKind() == lltok::lbrace)
3300     return ParseMDTuple(N);
3301 
3302   // !42
3303   return ParseMDNodeID(N);
3304 }
3305 
3306 namespace {
3307 
3308 /// Structure to represent an optional metadata field.
3309 template <class FieldTy> struct MDFieldImpl {
3310   typedef MDFieldImpl ImplTy;
3311   FieldTy Val;
3312   bool Seen;
3313 
3314   void assign(FieldTy Val) {
3315     Seen = true;
3316     this->Val = std::move(Val);
3317   }
3318 
3319   explicit MDFieldImpl(FieldTy Default)
3320       : Val(std::move(Default)), Seen(false) {}
3321 };
3322 
3323 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3324   uint64_t Max;
3325 
3326   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3327       : ImplTy(Default), Max(Max) {}
3328 };
3329 struct LineField : public MDUnsignedField {
3330   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3331 };
3332 struct ColumnField : public MDUnsignedField {
3333   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3334 };
3335 struct DwarfTagField : public MDUnsignedField {
3336   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3337   DwarfTagField(dwarf::Tag DefaultTag)
3338       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3339 };
3340 struct DwarfMacinfoTypeField : public MDUnsignedField {
3341   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3342   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3343     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3344 };
3345 struct DwarfAttEncodingField : public MDUnsignedField {
3346   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3347 };
3348 struct DwarfVirtualityField : public MDUnsignedField {
3349   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3350 };
3351 struct DwarfLangField : public MDUnsignedField {
3352   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3353 };
3354 struct DwarfCCField : public MDUnsignedField {
3355   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3356 };
3357 struct EmissionKindField : public MDUnsignedField {
3358   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3359 };
3360 
3361 struct DIFlagField : public MDUnsignedField {
3362   DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3363 };
3364 
3365 struct MDSignedField : public MDFieldImpl<int64_t> {
3366   int64_t Min;
3367   int64_t Max;
3368 
3369   MDSignedField(int64_t Default = 0)
3370       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3371   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3372       : ImplTy(Default), Min(Min), Max(Max) {}
3373 };
3374 
3375 struct MDBoolField : public MDFieldImpl<bool> {
3376   MDBoolField(bool Default = false) : ImplTy(Default) {}
3377 };
3378 struct MDField : public MDFieldImpl<Metadata *> {
3379   bool AllowNull;
3380 
3381   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3382 };
3383 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3384   MDConstant() : ImplTy(nullptr) {}
3385 };
3386 struct MDStringField : public MDFieldImpl<MDString *> {
3387   bool AllowEmpty;
3388   MDStringField(bool AllowEmpty = true)
3389       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3390 };
3391 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3392   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3393 };
3394 
3395 } // end namespace
3396 
3397 namespace llvm {
3398 
3399 template <>
3400 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3401                             MDUnsignedField &Result) {
3402   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3403     return TokError("expected unsigned integer");
3404 
3405   auto &U = Lex.getAPSIntVal();
3406   if (U.ugt(Result.Max))
3407     return TokError("value for '" + Name + "' too large, limit is " +
3408                     Twine(Result.Max));
3409   Result.assign(U.getZExtValue());
3410   assert(Result.Val <= Result.Max && "Expected value in range");
3411   Lex.Lex();
3412   return false;
3413 }
3414 
3415 template <>
3416 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3417   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3418 }
3419 template <>
3420 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3421   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3422 }
3423 
3424 template <>
3425 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3426   if (Lex.getKind() == lltok::APSInt)
3427     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3428 
3429   if (Lex.getKind() != lltok::DwarfTag)
3430     return TokError("expected DWARF tag");
3431 
3432   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3433   if (Tag == dwarf::DW_TAG_invalid)
3434     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3435   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3436 
3437   Result.assign(Tag);
3438   Lex.Lex();
3439   return false;
3440 }
3441 
3442 template <>
3443 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3444                             DwarfMacinfoTypeField &Result) {
3445   if (Lex.getKind() == lltok::APSInt)
3446     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3447 
3448   if (Lex.getKind() != lltok::DwarfMacinfo)
3449     return TokError("expected DWARF macinfo type");
3450 
3451   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3452   if (Macinfo == dwarf::DW_MACINFO_invalid)
3453     return TokError(
3454         "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3455   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3456 
3457   Result.assign(Macinfo);
3458   Lex.Lex();
3459   return false;
3460 }
3461 
3462 template <>
3463 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3464                             DwarfVirtualityField &Result) {
3465   if (Lex.getKind() == lltok::APSInt)
3466     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3467 
3468   if (Lex.getKind() != lltok::DwarfVirtuality)
3469     return TokError("expected DWARF virtuality code");
3470 
3471   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3472   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3473     return TokError("invalid DWARF virtuality code" + Twine(" '") +
3474                     Lex.getStrVal() + "'");
3475   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3476   Result.assign(Virtuality);
3477   Lex.Lex();
3478   return false;
3479 }
3480 
3481 template <>
3482 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3483   if (Lex.getKind() == lltok::APSInt)
3484     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3485 
3486   if (Lex.getKind() != lltok::DwarfLang)
3487     return TokError("expected DWARF language");
3488 
3489   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3490   if (!Lang)
3491     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3492                     "'");
3493   assert(Lang <= Result.Max && "Expected valid DWARF language");
3494   Result.assign(Lang);
3495   Lex.Lex();
3496   return false;
3497 }
3498 
3499 template <>
3500 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3501   if (Lex.getKind() == lltok::APSInt)
3502     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3503 
3504   if (Lex.getKind() != lltok::DwarfCC)
3505     return TokError("expected DWARF calling convention");
3506 
3507   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3508   if (!CC)
3509     return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3510                     "'");
3511   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3512   Result.assign(CC);
3513   Lex.Lex();
3514   return false;
3515 }
3516 
3517 template <>
3518 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3519   if (Lex.getKind() == lltok::APSInt)
3520     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3521 
3522   if (Lex.getKind() != lltok::EmissionKind)
3523     return TokError("expected emission kind");
3524 
3525   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3526   if (!Kind)
3527     return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3528                     "'");
3529   assert(*Kind <= Result.Max && "Expected valid emission kind");
3530   Result.assign(*Kind);
3531   Lex.Lex();
3532   return false;
3533 }
3534 
3535 template <>
3536 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3537                             DwarfAttEncodingField &Result) {
3538   if (Lex.getKind() == lltok::APSInt)
3539     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3540 
3541   if (Lex.getKind() != lltok::DwarfAttEncoding)
3542     return TokError("expected DWARF type attribute encoding");
3543 
3544   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3545   if (!Encoding)
3546     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3547                     Lex.getStrVal() + "'");
3548   assert(Encoding <= Result.Max && "Expected valid DWARF language");
3549   Result.assign(Encoding);
3550   Lex.Lex();
3551   return false;
3552 }
3553 
3554 /// DIFlagField
3555 ///  ::= uint32
3556 ///  ::= DIFlagVector
3557 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3558 template <>
3559 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3560   assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3561 
3562   // Parser for a single flag.
3563   auto parseFlag = [&](unsigned &Val) {
3564     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3565       return ParseUInt32(Val);
3566 
3567     if (Lex.getKind() != lltok::DIFlag)
3568       return TokError("expected debug info flag");
3569 
3570     Val = DINode::getFlag(Lex.getStrVal());
3571     if (!Val)
3572       return TokError(Twine("invalid debug info flag flag '") +
3573                       Lex.getStrVal() + "'");
3574     Lex.Lex();
3575     return false;
3576   };
3577 
3578   // Parse the flags and combine them together.
3579   unsigned Combined = 0;
3580   do {
3581     unsigned Val;
3582     if (parseFlag(Val))
3583       return true;
3584     Combined |= Val;
3585   } while (EatIfPresent(lltok::bar));
3586 
3587   Result.assign(Combined);
3588   return false;
3589 }
3590 
3591 template <>
3592 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3593                             MDSignedField &Result) {
3594   if (Lex.getKind() != lltok::APSInt)
3595     return TokError("expected signed integer");
3596 
3597   auto &S = Lex.getAPSIntVal();
3598   if (S < Result.Min)
3599     return TokError("value for '" + Name + "' too small, limit is " +
3600                     Twine(Result.Min));
3601   if (S > Result.Max)
3602     return TokError("value for '" + Name + "' too large, limit is " +
3603                     Twine(Result.Max));
3604   Result.assign(S.getExtValue());
3605   assert(Result.Val >= Result.Min && "Expected value in range");
3606   assert(Result.Val <= Result.Max && "Expected value in range");
3607   Lex.Lex();
3608   return false;
3609 }
3610 
3611 template <>
3612 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3613   switch (Lex.getKind()) {
3614   default:
3615     return TokError("expected 'true' or 'false'");
3616   case lltok::kw_true:
3617     Result.assign(true);
3618     break;
3619   case lltok::kw_false:
3620     Result.assign(false);
3621     break;
3622   }
3623   Lex.Lex();
3624   return false;
3625 }
3626 
3627 template <>
3628 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3629   if (Lex.getKind() == lltok::kw_null) {
3630     if (!Result.AllowNull)
3631       return TokError("'" + Name + "' cannot be null");
3632     Lex.Lex();
3633     Result.assign(nullptr);
3634     return false;
3635   }
3636 
3637   Metadata *MD;
3638   if (ParseMetadata(MD, nullptr))
3639     return true;
3640 
3641   Result.assign(MD);
3642   return false;
3643 }
3644 
3645 template <>
3646 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3647   Metadata *MD;
3648   if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3649     return true;
3650 
3651   Result.assign(cast<ConstantAsMetadata>(MD));
3652   return false;
3653 }
3654 
3655 template <>
3656 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3657   LocTy ValueLoc = Lex.getLoc();
3658   std::string S;
3659   if (ParseStringConstant(S))
3660     return true;
3661 
3662   if (!Result.AllowEmpty && S.empty())
3663     return Error(ValueLoc, "'" + Name + "' cannot be empty");
3664 
3665   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3666   return false;
3667 }
3668 
3669 template <>
3670 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3671   SmallVector<Metadata *, 4> MDs;
3672   if (ParseMDNodeVector(MDs))
3673     return true;
3674 
3675   Result.assign(std::move(MDs));
3676   return false;
3677 }
3678 
3679 } // end namespace llvm
3680 
3681 template <class ParserTy>
3682 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3683   do {
3684     if (Lex.getKind() != lltok::LabelStr)
3685       return TokError("expected field label here");
3686 
3687     if (parseField())
3688       return true;
3689   } while (EatIfPresent(lltok::comma));
3690 
3691   return false;
3692 }
3693 
3694 template <class ParserTy>
3695 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3696   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3697   Lex.Lex();
3698 
3699   if (ParseToken(lltok::lparen, "expected '(' here"))
3700     return true;
3701   if (Lex.getKind() != lltok::rparen)
3702     if (ParseMDFieldsImplBody(parseField))
3703       return true;
3704 
3705   ClosingLoc = Lex.getLoc();
3706   return ParseToken(lltok::rparen, "expected ')' here");
3707 }
3708 
3709 template <class FieldTy>
3710 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3711   if (Result.Seen)
3712     return TokError("field '" + Name + "' cannot be specified more than once");
3713 
3714   LocTy Loc = Lex.getLoc();
3715   Lex.Lex();
3716   return ParseMDField(Loc, Name, Result);
3717 }
3718 
3719 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3720   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3721 
3722 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
3723   if (Lex.getStrVal() == #CLASS)                                               \
3724     return Parse##CLASS(N, IsDistinct);
3725 #include "llvm/IR/Metadata.def"
3726 
3727   return TokError("expected metadata type");
3728 }
3729 
3730 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3731 #define NOP_FIELD(NAME, TYPE, INIT)
3732 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
3733   if (!NAME.Seen)                                                              \
3734     return Error(ClosingLoc, "missing required field '" #NAME "'");
3735 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
3736   if (Lex.getStrVal() == #NAME)                                                \
3737     return ParseMDField(#NAME, NAME);
3738 #define PARSE_MD_FIELDS()                                                      \
3739   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
3740   do {                                                                         \
3741     LocTy ClosingLoc;                                                          \
3742     if (ParseMDFieldsImpl([&]() -> bool {                                      \
3743       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
3744       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
3745     }, ClosingLoc))                                                            \
3746       return true;                                                             \
3747     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
3748   } while (false)
3749 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
3750   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3751 
3752 /// ParseDILocationFields:
3753 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3754 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3755 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3756   OPTIONAL(line, LineField, );                                                 \
3757   OPTIONAL(column, ColumnField, );                                             \
3758   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3759   OPTIONAL(inlinedAt, MDField, );
3760   PARSE_MD_FIELDS();
3761 #undef VISIT_MD_FIELDS
3762 
3763   Result = GET_OR_DISTINCT(
3764       DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3765   return false;
3766 }
3767 
3768 /// ParseGenericDINode:
3769 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3770 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3771 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3772   REQUIRED(tag, DwarfTagField, );                                              \
3773   OPTIONAL(header, MDStringField, );                                           \
3774   OPTIONAL(operands, MDFieldList, );
3775   PARSE_MD_FIELDS();
3776 #undef VISIT_MD_FIELDS
3777 
3778   Result = GET_OR_DISTINCT(GenericDINode,
3779                            (Context, tag.Val, header.Val, operands.Val));
3780   return false;
3781 }
3782 
3783 /// ParseDISubrange:
3784 ///   ::= !DISubrange(count: 30, lowerBound: 2)
3785 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3786 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3787   REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX));                         \
3788   OPTIONAL(lowerBound, MDSignedField, );
3789   PARSE_MD_FIELDS();
3790 #undef VISIT_MD_FIELDS
3791 
3792   Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3793   return false;
3794 }
3795 
3796 /// ParseDIEnumerator:
3797 ///   ::= !DIEnumerator(value: 30, name: "SomeKind")
3798 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3799 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3800   REQUIRED(name, MDStringField, );                                             \
3801   REQUIRED(value, MDSignedField, );
3802   PARSE_MD_FIELDS();
3803 #undef VISIT_MD_FIELDS
3804 
3805   Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3806   return false;
3807 }
3808 
3809 /// ParseDIBasicType:
3810 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3811 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3812 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3813   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
3814   OPTIONAL(name, MDStringField, );                                             \
3815   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3816   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3817   OPTIONAL(encoding, DwarfAttEncodingField, );
3818   PARSE_MD_FIELDS();
3819 #undef VISIT_MD_FIELDS
3820 
3821   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3822                                          align.Val, encoding.Val));
3823   return false;
3824 }
3825 
3826 /// ParseDIDerivedType:
3827 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3828 ///                      line: 7, scope: !1, baseType: !2, size: 32,
3829 ///                      align: 32, offset: 0, flags: 0, extraData: !3)
3830 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3831 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3832   REQUIRED(tag, DwarfTagField, );                                              \
3833   OPTIONAL(name, MDStringField, );                                             \
3834   OPTIONAL(file, MDField, );                                                   \
3835   OPTIONAL(line, LineField, );                                                 \
3836   OPTIONAL(scope, MDField, );                                                  \
3837   REQUIRED(baseType, MDField, );                                               \
3838   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3839   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3840   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3841   OPTIONAL(flags, DIFlagField, );                                              \
3842   OPTIONAL(extraData, MDField, );
3843   PARSE_MD_FIELDS();
3844 #undef VISIT_MD_FIELDS
3845 
3846   Result = GET_OR_DISTINCT(DIDerivedType,
3847                            (Context, tag.Val, name.Val, file.Val, line.Val,
3848                             scope.Val, baseType.Val, size.Val, align.Val,
3849                             offset.Val, flags.Val, extraData.Val));
3850   return false;
3851 }
3852 
3853 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3854 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3855   REQUIRED(tag, DwarfTagField, );                                              \
3856   OPTIONAL(name, MDStringField, );                                             \
3857   OPTIONAL(file, MDField, );                                                   \
3858   OPTIONAL(line, LineField, );                                                 \
3859   OPTIONAL(scope, MDField, );                                                  \
3860   OPTIONAL(baseType, MDField, );                                               \
3861   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3862   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3863   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3864   OPTIONAL(flags, DIFlagField, );                                              \
3865   OPTIONAL(elements, MDField, );                                               \
3866   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
3867   OPTIONAL(vtableHolder, MDField, );                                           \
3868   OPTIONAL(templateParams, MDField, );                                         \
3869   OPTIONAL(identifier, MDStringField, );
3870   PARSE_MD_FIELDS();
3871 #undef VISIT_MD_FIELDS
3872 
3873   // If this has an identifier try to build an ODR type.
3874   if (identifier.Val)
3875     if (auto *CT = DICompositeType::buildODRType(
3876             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3877             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3878             elements.Val, runtimeLang.Val, vtableHolder.Val,
3879             templateParams.Val)) {
3880       Result = CT;
3881       return false;
3882     }
3883 
3884   // Create a new node, and save it in the context if it belongs in the type
3885   // map.
3886   Result = GET_OR_DISTINCT(
3887       DICompositeType,
3888       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3889        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3890        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3891   return false;
3892 }
3893 
3894 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3895 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3896   OPTIONAL(flags, DIFlagField, );                                              \
3897   OPTIONAL(cc, DwarfCCField, );                                                \
3898   REQUIRED(types, MDField, );
3899   PARSE_MD_FIELDS();
3900 #undef VISIT_MD_FIELDS
3901 
3902   Result = GET_OR_DISTINCT(DISubroutineType,
3903                            (Context, flags.Val, cc.Val, types.Val));
3904   return false;
3905 }
3906 
3907 /// ParseDIFileType:
3908 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3909 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3910 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3911   REQUIRED(filename, MDStringField, );                                         \
3912   REQUIRED(directory, MDStringField, );
3913   PARSE_MD_FIELDS();
3914 #undef VISIT_MD_FIELDS
3915 
3916   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3917   return false;
3918 }
3919 
3920 /// ParseDICompileUnit:
3921 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3922 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
3923 ///                      splitDebugFilename: "abc.debug",
3924 ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
3925 ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
3926 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3927   if (!IsDistinct)
3928     return Lex.Error("missing 'distinct', required for !DICompileUnit");
3929 
3930 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3931   REQUIRED(language, DwarfLangField, );                                        \
3932   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
3933   OPTIONAL(producer, MDStringField, );                                         \
3934   OPTIONAL(isOptimized, MDBoolField, );                                        \
3935   OPTIONAL(flags, MDStringField, );                                            \
3936   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
3937   OPTIONAL(splitDebugFilename, MDStringField, );                               \
3938   OPTIONAL(emissionKind, EmissionKindField, );                                 \
3939   OPTIONAL(enums, MDField, );                                                  \
3940   OPTIONAL(retainedTypes, MDField, );                                          \
3941   OPTIONAL(globals, MDField, );                                                \
3942   OPTIONAL(imports, MDField, );                                                \
3943   OPTIONAL(macros, MDField, );                                                 \
3944   OPTIONAL(dwoId, MDUnsignedField, );
3945   PARSE_MD_FIELDS();
3946 #undef VISIT_MD_FIELDS
3947 
3948   Result = DICompileUnit::getDistinct(
3949       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3950       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
3951       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val);
3952   return false;
3953 }
3954 
3955 /// ParseDISubprogram:
3956 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3957 ///                     file: !1, line: 7, type: !2, isLocal: false,
3958 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
3959 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
3960 ///                     virtualIndex: 10, flags: 11,
3961 ///                     isOptimized: false, templateParams: !4, declaration: !5,
3962 ///                     variables: !6)
3963 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3964   auto Loc = Lex.getLoc();
3965 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3966   OPTIONAL(scope, MDField, );                                                  \
3967   OPTIONAL(name, MDStringField, );                                             \
3968   OPTIONAL(linkageName, MDStringField, );                                      \
3969   OPTIONAL(file, MDField, );                                                   \
3970   OPTIONAL(line, LineField, );                                                 \
3971   OPTIONAL(type, MDField, );                                                   \
3972   OPTIONAL(isLocal, MDBoolField, );                                            \
3973   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3974   OPTIONAL(scopeLine, LineField, );                                            \
3975   OPTIONAL(containingType, MDField, );                                         \
3976   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
3977   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
3978   OPTIONAL(flags, DIFlagField, );                                              \
3979   OPTIONAL(isOptimized, MDBoolField, );                                        \
3980   OPTIONAL(unit, MDField, );                                                   \
3981   OPTIONAL(templateParams, MDField, );                                         \
3982   OPTIONAL(declaration, MDField, );                                            \
3983   OPTIONAL(variables, MDField, );
3984   PARSE_MD_FIELDS();
3985 #undef VISIT_MD_FIELDS
3986 
3987   if (isDefinition.Val && !IsDistinct)
3988     return Lex.Error(
3989         Loc,
3990         "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3991 
3992   Result = GET_OR_DISTINCT(
3993       DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3994                      line.Val, type.Val, isLocal.Val, isDefinition.Val,
3995                      scopeLine.Val, containingType.Val, virtuality.Val,
3996                      virtualIndex.Val, flags.Val, isOptimized.Val, unit.Val,
3997                      templateParams.Val, declaration.Val, variables.Val));
3998   return false;
3999 }
4000 
4001 /// ParseDILexicalBlock:
4002 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4003 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4004 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4005   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4006   OPTIONAL(file, MDField, );                                                   \
4007   OPTIONAL(line, LineField, );                                                 \
4008   OPTIONAL(column, ColumnField, );
4009   PARSE_MD_FIELDS();
4010 #undef VISIT_MD_FIELDS
4011 
4012   Result = GET_OR_DISTINCT(
4013       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4014   return false;
4015 }
4016 
4017 /// ParseDILexicalBlockFile:
4018 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4019 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4020 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4021   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4022   OPTIONAL(file, MDField, );                                                   \
4023   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4024   PARSE_MD_FIELDS();
4025 #undef VISIT_MD_FIELDS
4026 
4027   Result = GET_OR_DISTINCT(DILexicalBlockFile,
4028                            (Context, scope.Val, file.Val, discriminator.Val));
4029   return false;
4030 }
4031 
4032 /// ParseDINamespace:
4033 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4034 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4035 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4036   REQUIRED(scope, MDField, );                                                  \
4037   OPTIONAL(file, MDField, );                                                   \
4038   OPTIONAL(name, MDStringField, );                                             \
4039   OPTIONAL(line, LineField, );
4040   PARSE_MD_FIELDS();
4041 #undef VISIT_MD_FIELDS
4042 
4043   Result = GET_OR_DISTINCT(DINamespace,
4044                            (Context, scope.Val, file.Val, name.Val, line.Val));
4045   return false;
4046 }
4047 
4048 /// ParseDIMacro:
4049 ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4050 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4051 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4052   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
4053   REQUIRED(line, LineField, );                                                 \
4054   REQUIRED(name, MDStringField, );                                             \
4055   OPTIONAL(value, MDStringField, );
4056   PARSE_MD_FIELDS();
4057 #undef VISIT_MD_FIELDS
4058 
4059   Result = GET_OR_DISTINCT(DIMacro,
4060                            (Context, type.Val, line.Val, name.Val, value.Val));
4061   return false;
4062 }
4063 
4064 /// ParseDIMacroFile:
4065 ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4066 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4067 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4068   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
4069   REQUIRED(line, LineField, );                                                 \
4070   REQUIRED(file, MDField, );                                                   \
4071   OPTIONAL(nodes, MDField, );
4072   PARSE_MD_FIELDS();
4073 #undef VISIT_MD_FIELDS
4074 
4075   Result = GET_OR_DISTINCT(DIMacroFile,
4076                            (Context, type.Val, line.Val, file.Val, nodes.Val));
4077   return false;
4078 }
4079 
4080 
4081 /// ParseDIModule:
4082 ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4083 ///                 includePath: "/usr/include", isysroot: "/")
4084 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4085 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4086   REQUIRED(scope, MDField, );                                                  \
4087   REQUIRED(name, MDStringField, );                                             \
4088   OPTIONAL(configMacros, MDStringField, );                                     \
4089   OPTIONAL(includePath, MDStringField, );                                      \
4090   OPTIONAL(isysroot, MDStringField, );
4091   PARSE_MD_FIELDS();
4092 #undef VISIT_MD_FIELDS
4093 
4094   Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4095                            configMacros.Val, includePath.Val, isysroot.Val));
4096   return false;
4097 }
4098 
4099 /// ParseDITemplateTypeParameter:
4100 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4101 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4102 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4103   OPTIONAL(name, MDStringField, );                                             \
4104   REQUIRED(type, MDField, );
4105   PARSE_MD_FIELDS();
4106 #undef VISIT_MD_FIELDS
4107 
4108   Result =
4109       GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4110   return false;
4111 }
4112 
4113 /// ParseDITemplateValueParameter:
4114 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4115 ///                                 name: "V", type: !1, value: i32 7)
4116 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4117 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4118   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
4119   OPTIONAL(name, MDStringField, );                                             \
4120   OPTIONAL(type, MDField, );                                                   \
4121   REQUIRED(value, MDField, );
4122   PARSE_MD_FIELDS();
4123 #undef VISIT_MD_FIELDS
4124 
4125   Result = GET_OR_DISTINCT(DITemplateValueParameter,
4126                            (Context, tag.Val, name.Val, type.Val, value.Val));
4127   return false;
4128 }
4129 
4130 /// ParseDIGlobalVariable:
4131 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4132 ///                         file: !1, line: 7, type: !2, isLocal: false,
4133 ///                         isDefinition: true, variable: i32* @foo,
4134 ///                         declaration: !3)
4135 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4136 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4137   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
4138   OPTIONAL(scope, MDField, );                                                  \
4139   OPTIONAL(linkageName, MDStringField, );                                      \
4140   OPTIONAL(file, MDField, );                                                   \
4141   OPTIONAL(line, LineField, );                                                 \
4142   OPTIONAL(type, MDField, );                                                   \
4143   OPTIONAL(isLocal, MDBoolField, );                                            \
4144   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
4145   OPTIONAL(variable, MDConstant, );                                            \
4146   OPTIONAL(declaration, MDField, );
4147   PARSE_MD_FIELDS();
4148 #undef VISIT_MD_FIELDS
4149 
4150   Result = GET_OR_DISTINCT(DIGlobalVariable,
4151                            (Context, scope.Val, name.Val, linkageName.Val,
4152                             file.Val, line.Val, type.Val, isLocal.Val,
4153                             isDefinition.Val, variable.Val, declaration.Val));
4154   return false;
4155 }
4156 
4157 /// ParseDILocalVariable:
4158 ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4159 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7)
4160 ///   ::= !DILocalVariable(scope: !0, name: "foo",
4161 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7)
4162 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4163 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4164   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
4165   OPTIONAL(name, MDStringField, );                                             \
4166   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
4167   OPTIONAL(file, MDField, );                                                   \
4168   OPTIONAL(line, LineField, );                                                 \
4169   OPTIONAL(type, MDField, );                                                   \
4170   OPTIONAL(flags, DIFlagField, );
4171   PARSE_MD_FIELDS();
4172 #undef VISIT_MD_FIELDS
4173 
4174   Result = GET_OR_DISTINCT(DILocalVariable,
4175                            (Context, scope.Val, name.Val, file.Val, line.Val,
4176                             type.Val, arg.Val, flags.Val));
4177   return false;
4178 }
4179 
4180 /// ParseDIExpression:
4181 ///   ::= !DIExpression(0, 7, -1)
4182 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4183   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4184   Lex.Lex();
4185 
4186   if (ParseToken(lltok::lparen, "expected '(' here"))
4187     return true;
4188 
4189   SmallVector<uint64_t, 8> Elements;
4190   if (Lex.getKind() != lltok::rparen)
4191     do {
4192       if (Lex.getKind() == lltok::DwarfOp) {
4193         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4194           Lex.Lex();
4195           Elements.push_back(Op);
4196           continue;
4197         }
4198         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4199       }
4200 
4201       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4202         return TokError("expected unsigned integer");
4203 
4204       auto &U = Lex.getAPSIntVal();
4205       if (U.ugt(UINT64_MAX))
4206         return TokError("element too large, limit is " + Twine(UINT64_MAX));
4207       Elements.push_back(U.getZExtValue());
4208       Lex.Lex();
4209     } while (EatIfPresent(lltok::comma));
4210 
4211   if (ParseToken(lltok::rparen, "expected ')' here"))
4212     return true;
4213 
4214   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4215   return false;
4216 }
4217 
4218 /// ParseDIObjCProperty:
4219 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4220 ///                       getter: "getFoo", attributes: 7, type: !2)
4221 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4222 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4223   OPTIONAL(name, MDStringField, );                                             \
4224   OPTIONAL(file, MDField, );                                                   \
4225   OPTIONAL(line, LineField, );                                                 \
4226   OPTIONAL(setter, MDStringField, );                                           \
4227   OPTIONAL(getter, MDStringField, );                                           \
4228   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
4229   OPTIONAL(type, MDField, );
4230   PARSE_MD_FIELDS();
4231 #undef VISIT_MD_FIELDS
4232 
4233   Result = GET_OR_DISTINCT(DIObjCProperty,
4234                            (Context, name.Val, file.Val, line.Val, setter.Val,
4235                             getter.Val, attributes.Val, type.Val));
4236   return false;
4237 }
4238 
4239 /// ParseDIImportedEntity:
4240 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4241 ///                         line: 7, name: "foo")
4242 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4243 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
4244   REQUIRED(tag, DwarfTagField, );                                              \
4245   REQUIRED(scope, MDField, );                                                  \
4246   OPTIONAL(entity, MDField, );                                                 \
4247   OPTIONAL(line, LineField, );                                                 \
4248   OPTIONAL(name, MDStringField, );
4249   PARSE_MD_FIELDS();
4250 #undef VISIT_MD_FIELDS
4251 
4252   Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4253                                               entity.Val, line.Val, name.Val));
4254   return false;
4255 }
4256 
4257 #undef PARSE_MD_FIELD
4258 #undef NOP_FIELD
4259 #undef REQUIRE_FIELD
4260 #undef DECLARE_FIELD
4261 
4262 /// ParseMetadataAsValue
4263 ///  ::= metadata i32 %local
4264 ///  ::= metadata i32 @global
4265 ///  ::= metadata i32 7
4266 ///  ::= metadata !0
4267 ///  ::= metadata !{...}
4268 ///  ::= metadata !"string"
4269 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4270   // Note: the type 'metadata' has already been parsed.
4271   Metadata *MD;
4272   if (ParseMetadata(MD, &PFS))
4273     return true;
4274 
4275   V = MetadataAsValue::get(Context, MD);
4276   return false;
4277 }
4278 
4279 /// ParseValueAsMetadata
4280 ///  ::= i32 %local
4281 ///  ::= i32 @global
4282 ///  ::= i32 7
4283 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4284                                     PerFunctionState *PFS) {
4285   Type *Ty;
4286   LocTy Loc;
4287   if (ParseType(Ty, TypeMsg, Loc))
4288     return true;
4289   if (Ty->isMetadataTy())
4290     return Error(Loc, "invalid metadata-value-metadata roundtrip");
4291 
4292   Value *V;
4293   if (ParseValue(Ty, V, PFS))
4294     return true;
4295 
4296   MD = ValueAsMetadata::get(V);
4297   return false;
4298 }
4299 
4300 /// ParseMetadata
4301 ///  ::= i32 %local
4302 ///  ::= i32 @global
4303 ///  ::= i32 7
4304 ///  ::= !42
4305 ///  ::= !{...}
4306 ///  ::= !"string"
4307 ///  ::= !DILocation(...)
4308 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4309   if (Lex.getKind() == lltok::MetadataVar) {
4310     MDNode *N;
4311     if (ParseSpecializedMDNode(N))
4312       return true;
4313     MD = N;
4314     return false;
4315   }
4316 
4317   // ValueAsMetadata:
4318   // <type> <value>
4319   if (Lex.getKind() != lltok::exclaim)
4320     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4321 
4322   // '!'.
4323   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4324   Lex.Lex();
4325 
4326   // MDString:
4327   //   ::= '!' STRINGCONSTANT
4328   if (Lex.getKind() == lltok::StringConstant) {
4329     MDString *S;
4330     if (ParseMDString(S))
4331       return true;
4332     MD = S;
4333     return false;
4334   }
4335 
4336   // MDNode:
4337   // !{ ... }
4338   // !7
4339   MDNode *N;
4340   if (ParseMDNodeTail(N))
4341     return true;
4342   MD = N;
4343   return false;
4344 }
4345 
4346 
4347 //===----------------------------------------------------------------------===//
4348 // Function Parsing.
4349 //===----------------------------------------------------------------------===//
4350 
4351 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4352                                    PerFunctionState *PFS) {
4353   if (Ty->isFunctionTy())
4354     return Error(ID.Loc, "functions are not values, refer to them as pointers");
4355 
4356   switch (ID.Kind) {
4357   case ValID::t_LocalID:
4358     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4359     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4360     return V == nullptr;
4361   case ValID::t_LocalName:
4362     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4363     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4364     return V == nullptr;
4365   case ValID::t_InlineAsm: {
4366     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4367       return Error(ID.Loc, "invalid type for inline asm constraint string");
4368     V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4369                        (ID.UIntVal >> 1) & 1,
4370                        (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4371     return false;
4372   }
4373   case ValID::t_GlobalName:
4374     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4375     return V == nullptr;
4376   case ValID::t_GlobalID:
4377     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4378     return V == nullptr;
4379   case ValID::t_APSInt:
4380     if (!Ty->isIntegerTy())
4381       return Error(ID.Loc, "integer constant must have integer type");
4382     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4383     V = ConstantInt::get(Context, ID.APSIntVal);
4384     return false;
4385   case ValID::t_APFloat:
4386     if (!Ty->isFloatingPointTy() ||
4387         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4388       return Error(ID.Loc, "floating point constant invalid for type");
4389 
4390     // The lexer has no type info, so builds all half, float, and double FP
4391     // constants as double.  Fix this here.  Long double does not need this.
4392     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4393       bool Ignored;
4394       if (Ty->isHalfTy())
4395         ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4396                               &Ignored);
4397       else if (Ty->isFloatTy())
4398         ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4399                               &Ignored);
4400     }
4401     V = ConstantFP::get(Context, ID.APFloatVal);
4402 
4403     if (V->getType() != Ty)
4404       return Error(ID.Loc, "floating point constant does not have type '" +
4405                    getTypeString(Ty) + "'");
4406 
4407     return false;
4408   case ValID::t_Null:
4409     if (!Ty->isPointerTy())
4410       return Error(ID.Loc, "null must be a pointer type");
4411     V = ConstantPointerNull::get(cast<PointerType>(Ty));
4412     return false;
4413   case ValID::t_Undef:
4414     // FIXME: LabelTy should not be a first-class type.
4415     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4416       return Error(ID.Loc, "invalid type for undef constant");
4417     V = UndefValue::get(Ty);
4418     return false;
4419   case ValID::t_EmptyArray:
4420     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4421       return Error(ID.Loc, "invalid empty array initializer");
4422     V = UndefValue::get(Ty);
4423     return false;
4424   case ValID::t_Zero:
4425     // FIXME: LabelTy should not be a first-class type.
4426     if (!Ty->isFirstClassType() || Ty->isLabelTy())
4427       return Error(ID.Loc, "invalid type for null constant");
4428     V = Constant::getNullValue(Ty);
4429     return false;
4430   case ValID::t_None:
4431     if (!Ty->isTokenTy())
4432       return Error(ID.Loc, "invalid type for none constant");
4433     V = Constant::getNullValue(Ty);
4434     return false;
4435   case ValID::t_Constant:
4436     if (ID.ConstantVal->getType() != Ty)
4437       return Error(ID.Loc, "constant expression type mismatch");
4438 
4439     V = ID.ConstantVal;
4440     return false;
4441   case ValID::t_ConstantStruct:
4442   case ValID::t_PackedConstantStruct:
4443     if (StructType *ST = dyn_cast<StructType>(Ty)) {
4444       if (ST->getNumElements() != ID.UIntVal)
4445         return Error(ID.Loc,
4446                      "initializer with struct type has wrong # elements");
4447       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4448         return Error(ID.Loc, "packed'ness of initializer and type don't match");
4449 
4450       // Verify that the elements are compatible with the structtype.
4451       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4452         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4453           return Error(ID.Loc, "element " + Twine(i) +
4454                     " of struct initializer doesn't match struct element type");
4455 
4456       V = ConstantStruct::get(
4457           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4458     } else
4459       return Error(ID.Loc, "constant expression type mismatch");
4460     return false;
4461   }
4462   llvm_unreachable("Invalid ValID");
4463 }
4464 
4465 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4466   C = nullptr;
4467   ValID ID;
4468   auto Loc = Lex.getLoc();
4469   if (ParseValID(ID, /*PFS=*/nullptr))
4470     return true;
4471   switch (ID.Kind) {
4472   case ValID::t_APSInt:
4473   case ValID::t_APFloat:
4474   case ValID::t_Undef:
4475   case ValID::t_Constant:
4476   case ValID::t_ConstantStruct:
4477   case ValID::t_PackedConstantStruct: {
4478     Value *V;
4479     if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4480       return true;
4481     assert(isa<Constant>(V) && "Expected a constant value");
4482     C = cast<Constant>(V);
4483     return false;
4484   }
4485   default:
4486     return Error(Loc, "expected a constant value");
4487   }
4488 }
4489 
4490 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4491   V = nullptr;
4492   ValID ID;
4493   return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4494 }
4495 
4496 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4497   Type *Ty = nullptr;
4498   return ParseType(Ty) ||
4499          ParseValue(Ty, V, PFS);
4500 }
4501 
4502 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4503                                       PerFunctionState &PFS) {
4504   Value *V;
4505   Loc = Lex.getLoc();
4506   if (ParseTypeAndValue(V, PFS)) return true;
4507   if (!isa<BasicBlock>(V))
4508     return Error(Loc, "expected a basic block");
4509   BB = cast<BasicBlock>(V);
4510   return false;
4511 }
4512 
4513 
4514 /// FunctionHeader
4515 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4516 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4517 ///       OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4518 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4519   // Parse the linkage.
4520   LocTy LinkageLoc = Lex.getLoc();
4521   unsigned Linkage;
4522 
4523   unsigned Visibility;
4524   unsigned DLLStorageClass;
4525   AttrBuilder RetAttrs;
4526   unsigned CC;
4527   bool HasLinkage;
4528   Type *RetType = nullptr;
4529   LocTy RetTypeLoc = Lex.getLoc();
4530   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4531       ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4532       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4533     return true;
4534 
4535   // Verify that the linkage is ok.
4536   switch ((GlobalValue::LinkageTypes)Linkage) {
4537   case GlobalValue::ExternalLinkage:
4538     break; // always ok.
4539   case GlobalValue::ExternalWeakLinkage:
4540     if (isDefine)
4541       return Error(LinkageLoc, "invalid linkage for function definition");
4542     break;
4543   case GlobalValue::PrivateLinkage:
4544   case GlobalValue::InternalLinkage:
4545   case GlobalValue::AvailableExternallyLinkage:
4546   case GlobalValue::LinkOnceAnyLinkage:
4547   case GlobalValue::LinkOnceODRLinkage:
4548   case GlobalValue::WeakAnyLinkage:
4549   case GlobalValue::WeakODRLinkage:
4550     if (!isDefine)
4551       return Error(LinkageLoc, "invalid linkage for function declaration");
4552     break;
4553   case GlobalValue::AppendingLinkage:
4554   case GlobalValue::CommonLinkage:
4555     return Error(LinkageLoc, "invalid function linkage type");
4556   }
4557 
4558   if (!isValidVisibilityForLinkage(Visibility, Linkage))
4559     return Error(LinkageLoc,
4560                  "symbol with local linkage must have default visibility");
4561 
4562   if (!FunctionType::isValidReturnType(RetType))
4563     return Error(RetTypeLoc, "invalid function return type");
4564 
4565   LocTy NameLoc = Lex.getLoc();
4566 
4567   std::string FunctionName;
4568   if (Lex.getKind() == lltok::GlobalVar) {
4569     FunctionName = Lex.getStrVal();
4570   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
4571     unsigned NameID = Lex.getUIntVal();
4572 
4573     if (NameID != NumberedVals.size())
4574       return TokError("function expected to be numbered '%" +
4575                       Twine(NumberedVals.size()) + "'");
4576   } else {
4577     return TokError("expected function name");
4578   }
4579 
4580   Lex.Lex();
4581 
4582   if (Lex.getKind() != lltok::lparen)
4583     return TokError("expected '(' in function argument list");
4584 
4585   SmallVector<ArgInfo, 8> ArgList;
4586   bool isVarArg;
4587   AttrBuilder FuncAttrs;
4588   std::vector<unsigned> FwdRefAttrGrps;
4589   LocTy BuiltinLoc;
4590   std::string Section;
4591   unsigned Alignment;
4592   std::string GC;
4593   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4594   LocTy UnnamedAddrLoc;
4595   Constant *Prefix = nullptr;
4596   Constant *Prologue = nullptr;
4597   Constant *PersonalityFn = nullptr;
4598   Comdat *C;
4599 
4600   if (ParseArgumentList(ArgList, isVarArg) ||
4601       ParseOptionalUnnamedAddr(UnnamedAddr) ||
4602       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4603                                  BuiltinLoc) ||
4604       (EatIfPresent(lltok::kw_section) &&
4605        ParseStringConstant(Section)) ||
4606       parseOptionalComdat(FunctionName, C) ||
4607       ParseOptionalAlignment(Alignment) ||
4608       (EatIfPresent(lltok::kw_gc) &&
4609        ParseStringConstant(GC)) ||
4610       (EatIfPresent(lltok::kw_prefix) &&
4611        ParseGlobalTypeAndValue(Prefix)) ||
4612       (EatIfPresent(lltok::kw_prologue) &&
4613        ParseGlobalTypeAndValue(Prologue)) ||
4614       (EatIfPresent(lltok::kw_personality) &&
4615        ParseGlobalTypeAndValue(PersonalityFn)))
4616     return true;
4617 
4618   if (FuncAttrs.contains(Attribute::Builtin))
4619     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4620 
4621   // If the alignment was parsed as an attribute, move to the alignment field.
4622   if (FuncAttrs.hasAlignmentAttr()) {
4623     Alignment = FuncAttrs.getAlignment();
4624     FuncAttrs.removeAttribute(Attribute::Alignment);
4625   }
4626 
4627   // Okay, if we got here, the function is syntactically valid.  Convert types
4628   // and do semantic checks.
4629   std::vector<Type*> ParamTypeList;
4630   SmallVector<AttributeSet, 8> Attrs;
4631 
4632   if (RetAttrs.hasAttributes())
4633     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4634                                       AttributeSet::ReturnIndex,
4635                                       RetAttrs));
4636 
4637   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4638     ParamTypeList.push_back(ArgList[i].Ty);
4639     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4640       AttrBuilder B(ArgList[i].Attrs, i + 1);
4641       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4642     }
4643   }
4644 
4645   if (FuncAttrs.hasAttributes())
4646     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4647                                       AttributeSet::FunctionIndex,
4648                                       FuncAttrs));
4649 
4650   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4651 
4652   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4653     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4654 
4655   FunctionType *FT =
4656     FunctionType::get(RetType, ParamTypeList, isVarArg);
4657   PointerType *PFT = PointerType::getUnqual(FT);
4658 
4659   Fn = nullptr;
4660   if (!FunctionName.empty()) {
4661     // If this was a definition of a forward reference, remove the definition
4662     // from the forward reference table and fill in the forward ref.
4663     auto FRVI = ForwardRefVals.find(FunctionName);
4664     if (FRVI != ForwardRefVals.end()) {
4665       Fn = M->getFunction(FunctionName);
4666       if (!Fn)
4667         return Error(FRVI->second.second, "invalid forward reference to "
4668                      "function as global value!");
4669       if (Fn->getType() != PFT)
4670         return Error(FRVI->second.second, "invalid forward reference to "
4671                      "function '" + FunctionName + "' with wrong type!");
4672 
4673       ForwardRefVals.erase(FRVI);
4674     } else if ((Fn = M->getFunction(FunctionName))) {
4675       // Reject redefinitions.
4676       return Error(NameLoc, "invalid redefinition of function '" +
4677                    FunctionName + "'");
4678     } else if (M->getNamedValue(FunctionName)) {
4679       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4680     }
4681 
4682   } else {
4683     // If this is a definition of a forward referenced function, make sure the
4684     // types agree.
4685     auto I = ForwardRefValIDs.find(NumberedVals.size());
4686     if (I != ForwardRefValIDs.end()) {
4687       Fn = cast<Function>(I->second.first);
4688       if (Fn->getType() != PFT)
4689         return Error(NameLoc, "type of definition and forward reference of '@" +
4690                      Twine(NumberedVals.size()) + "' disagree");
4691       ForwardRefValIDs.erase(I);
4692     }
4693   }
4694 
4695   if (!Fn)
4696     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4697   else // Move the forward-reference to the correct spot in the module.
4698     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4699 
4700   if (FunctionName.empty())
4701     NumberedVals.push_back(Fn);
4702 
4703   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4704   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4705   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4706   Fn->setCallingConv(CC);
4707   Fn->setAttributes(PAL);
4708   Fn->setUnnamedAddr(UnnamedAddr);
4709   Fn->setAlignment(Alignment);
4710   Fn->setSection(Section);
4711   Fn->setComdat(C);
4712   Fn->setPersonalityFn(PersonalityFn);
4713   if (!GC.empty()) Fn->setGC(GC);
4714   Fn->setPrefixData(Prefix);
4715   Fn->setPrologueData(Prologue);
4716   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4717 
4718   // Add all of the arguments we parsed to the function.
4719   Function::arg_iterator ArgIt = Fn->arg_begin();
4720   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4721     // If the argument has a name, insert it into the argument symbol table.
4722     if (ArgList[i].Name.empty()) continue;
4723 
4724     // Set the name, if it conflicted, it will be auto-renamed.
4725     ArgIt->setName(ArgList[i].Name);
4726 
4727     if (ArgIt->getName() != ArgList[i].Name)
4728       return Error(ArgList[i].Loc, "redefinition of argument '%" +
4729                    ArgList[i].Name + "'");
4730   }
4731 
4732   if (isDefine)
4733     return false;
4734 
4735   // Check the declaration has no block address forward references.
4736   ValID ID;
4737   if (FunctionName.empty()) {
4738     ID.Kind = ValID::t_GlobalID;
4739     ID.UIntVal = NumberedVals.size() - 1;
4740   } else {
4741     ID.Kind = ValID::t_GlobalName;
4742     ID.StrVal = FunctionName;
4743   }
4744   auto Blocks = ForwardRefBlockAddresses.find(ID);
4745   if (Blocks != ForwardRefBlockAddresses.end())
4746     return Error(Blocks->first.Loc,
4747                  "cannot take blockaddress inside a declaration");
4748   return false;
4749 }
4750 
4751 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4752   ValID ID;
4753   if (FunctionNumber == -1) {
4754     ID.Kind = ValID::t_GlobalName;
4755     ID.StrVal = F.getName();
4756   } else {
4757     ID.Kind = ValID::t_GlobalID;
4758     ID.UIntVal = FunctionNumber;
4759   }
4760 
4761   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4762   if (Blocks == P.ForwardRefBlockAddresses.end())
4763     return false;
4764 
4765   for (const auto &I : Blocks->second) {
4766     const ValID &BBID = I.first;
4767     GlobalValue *GV = I.second;
4768 
4769     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4770            "Expected local id or name");
4771     BasicBlock *BB;
4772     if (BBID.Kind == ValID::t_LocalName)
4773       BB = GetBB(BBID.StrVal, BBID.Loc);
4774     else
4775       BB = GetBB(BBID.UIntVal, BBID.Loc);
4776     if (!BB)
4777       return P.Error(BBID.Loc, "referenced value is not a basic block");
4778 
4779     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4780     GV->eraseFromParent();
4781   }
4782 
4783   P.ForwardRefBlockAddresses.erase(Blocks);
4784   return false;
4785 }
4786 
4787 /// ParseFunctionBody
4788 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
4789 bool LLParser::ParseFunctionBody(Function &Fn) {
4790   if (Lex.getKind() != lltok::lbrace)
4791     return TokError("expected '{' in function body");
4792   Lex.Lex();  // eat the {.
4793 
4794   int FunctionNumber = -1;
4795   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4796 
4797   PerFunctionState PFS(*this, Fn, FunctionNumber);
4798 
4799   // Resolve block addresses and allow basic blocks to be forward-declared
4800   // within this function.
4801   if (PFS.resolveForwardRefBlockAddresses())
4802     return true;
4803   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4804 
4805   // We need at least one basic block.
4806   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4807     return TokError("function body requires at least one basic block");
4808 
4809   while (Lex.getKind() != lltok::rbrace &&
4810          Lex.getKind() != lltok::kw_uselistorder)
4811     if (ParseBasicBlock(PFS)) return true;
4812 
4813   while (Lex.getKind() != lltok::rbrace)
4814     if (ParseUseListOrder(&PFS))
4815       return true;
4816 
4817   // Eat the }.
4818   Lex.Lex();
4819 
4820   // Verify function is ok.
4821   return PFS.FinishFunction();
4822 }
4823 
4824 /// ParseBasicBlock
4825 ///   ::= LabelStr? Instruction*
4826 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4827   // If this basic block starts out with a name, remember it.
4828   std::string Name;
4829   LocTy NameLoc = Lex.getLoc();
4830   if (Lex.getKind() == lltok::LabelStr) {
4831     Name = Lex.getStrVal();
4832     Lex.Lex();
4833   }
4834 
4835   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4836   if (!BB)
4837     return Error(NameLoc,
4838                  "unable to create block named '" + Name + "'");
4839 
4840   std::string NameStr;
4841 
4842   // Parse the instructions in this block until we get a terminator.
4843   Instruction *Inst;
4844   do {
4845     // This instruction may have three possibilities for a name: a) none
4846     // specified, b) name specified "%foo =", c) number specified: "%4 =".
4847     LocTy NameLoc = Lex.getLoc();
4848     int NameID = -1;
4849     NameStr = "";
4850 
4851     if (Lex.getKind() == lltok::LocalVarID) {
4852       NameID = Lex.getUIntVal();
4853       Lex.Lex();
4854       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4855         return true;
4856     } else if (Lex.getKind() == lltok::LocalVar) {
4857       NameStr = Lex.getStrVal();
4858       Lex.Lex();
4859       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4860         return true;
4861     }
4862 
4863     switch (ParseInstruction(Inst, BB, PFS)) {
4864     default: llvm_unreachable("Unknown ParseInstruction result!");
4865     case InstError: return true;
4866     case InstNormal:
4867       BB->getInstList().push_back(Inst);
4868 
4869       // With a normal result, we check to see if the instruction is followed by
4870       // a comma and metadata.
4871       if (EatIfPresent(lltok::comma))
4872         if (ParseInstructionMetadata(*Inst))
4873           return true;
4874       break;
4875     case InstExtraComma:
4876       BB->getInstList().push_back(Inst);
4877 
4878       // If the instruction parser ate an extra comma at the end of it, it
4879       // *must* be followed by metadata.
4880       if (ParseInstructionMetadata(*Inst))
4881         return true;
4882       break;
4883     }
4884 
4885     // Set the name on the instruction.
4886     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4887   } while (!isa<TerminatorInst>(Inst));
4888 
4889   return false;
4890 }
4891 
4892 //===----------------------------------------------------------------------===//
4893 // Instruction Parsing.
4894 //===----------------------------------------------------------------------===//
4895 
4896 /// ParseInstruction - Parse one of the many different instructions.
4897 ///
4898 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4899                                PerFunctionState &PFS) {
4900   lltok::Kind Token = Lex.getKind();
4901   if (Token == lltok::Eof)
4902     return TokError("found end of file when expecting more instructions");
4903   LocTy Loc = Lex.getLoc();
4904   unsigned KeywordVal = Lex.getUIntVal();
4905   Lex.Lex();  // Eat the keyword.
4906 
4907   switch (Token) {
4908   default:                    return Error(Loc, "expected instruction opcode");
4909   // Terminator Instructions.
4910   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4911   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
4912   case lltok::kw_br:          return ParseBr(Inst, PFS);
4913   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
4914   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
4915   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
4916   case lltok::kw_resume:      return ParseResume(Inst, PFS);
4917   case lltok::kw_cleanupret:  return ParseCleanupRet(Inst, PFS);
4918   case lltok::kw_catchret:    return ParseCatchRet(Inst, PFS);
4919   case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4920   case lltok::kw_catchpad:    return ParseCatchPad(Inst, PFS);
4921   case lltok::kw_cleanuppad:  return ParseCleanupPad(Inst, PFS);
4922   // Binary Operators.
4923   case lltok::kw_add:
4924   case lltok::kw_sub:
4925   case lltok::kw_mul:
4926   case lltok::kw_shl: {
4927     bool NUW = EatIfPresent(lltok::kw_nuw);
4928     bool NSW = EatIfPresent(lltok::kw_nsw);
4929     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4930 
4931     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4932 
4933     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4934     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4935     return false;
4936   }
4937   case lltok::kw_fadd:
4938   case lltok::kw_fsub:
4939   case lltok::kw_fmul:
4940   case lltok::kw_fdiv:
4941   case lltok::kw_frem: {
4942     FastMathFlags FMF = EatFastMathFlagsIfPresent();
4943     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4944     if (Res != 0)
4945       return Res;
4946     if (FMF.any())
4947       Inst->setFastMathFlags(FMF);
4948     return 0;
4949   }
4950 
4951   case lltok::kw_sdiv:
4952   case lltok::kw_udiv:
4953   case lltok::kw_lshr:
4954   case lltok::kw_ashr: {
4955     bool Exact = EatIfPresent(lltok::kw_exact);
4956 
4957     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4958     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4959     return false;
4960   }
4961 
4962   case lltok::kw_urem:
4963   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4964   case lltok::kw_and:
4965   case lltok::kw_or:
4966   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
4967   case lltok::kw_icmp:   return ParseCompare(Inst, PFS, KeywordVal);
4968   case lltok::kw_fcmp: {
4969     FastMathFlags FMF = EatFastMathFlagsIfPresent();
4970     int Res = ParseCompare(Inst, PFS, KeywordVal);
4971     if (Res != 0)
4972       return Res;
4973     if (FMF.any())
4974       Inst->setFastMathFlags(FMF);
4975     return 0;
4976   }
4977 
4978   // Casts.
4979   case lltok::kw_trunc:
4980   case lltok::kw_zext:
4981   case lltok::kw_sext:
4982   case lltok::kw_fptrunc:
4983   case lltok::kw_fpext:
4984   case lltok::kw_bitcast:
4985   case lltok::kw_addrspacecast:
4986   case lltok::kw_uitofp:
4987   case lltok::kw_sitofp:
4988   case lltok::kw_fptoui:
4989   case lltok::kw_fptosi:
4990   case lltok::kw_inttoptr:
4991   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
4992   // Other.
4993   case lltok::kw_select:         return ParseSelect(Inst, PFS);
4994   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
4995   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4996   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
4997   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
4998   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
4999   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
5000   // Call.
5001   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
5002   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5003   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5004   case lltok::kw_notail:   return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5005   // Memory.
5006   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
5007   case lltok::kw_load:           return ParseLoad(Inst, PFS);
5008   case lltok::kw_store:          return ParseStore(Inst, PFS);
5009   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
5010   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
5011   case lltok::kw_fence:          return ParseFence(Inst, PFS);
5012   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5013   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
5014   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
5015   }
5016 }
5017 
5018 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5019 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5020   if (Opc == Instruction::FCmp) {
5021     switch (Lex.getKind()) {
5022     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5023     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5024     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5025     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5026     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5027     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5028     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5029     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5030     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5031     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5032     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5033     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5034     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5035     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5036     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5037     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5038     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5039     }
5040   } else {
5041     switch (Lex.getKind()) {
5042     default: return TokError("expected icmp predicate (e.g. 'eq')");
5043     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
5044     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
5045     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5046     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5047     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5048     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5049     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5050     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5051     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5052     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5053     }
5054   }
5055   Lex.Lex();
5056   return false;
5057 }
5058 
5059 //===----------------------------------------------------------------------===//
5060 // Terminator Instructions.
5061 //===----------------------------------------------------------------------===//
5062 
5063 /// ParseRet - Parse a return instruction.
5064 ///   ::= 'ret' void (',' !dbg, !1)*
5065 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
5066 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5067                         PerFunctionState &PFS) {
5068   SMLoc TypeLoc = Lex.getLoc();
5069   Type *Ty = nullptr;
5070   if (ParseType(Ty, true /*void allowed*/)) return true;
5071 
5072   Type *ResType = PFS.getFunction().getReturnType();
5073 
5074   if (Ty->isVoidTy()) {
5075     if (!ResType->isVoidTy())
5076       return Error(TypeLoc, "value doesn't match function result type '" +
5077                    getTypeString(ResType) + "'");
5078 
5079     Inst = ReturnInst::Create(Context);
5080     return false;
5081   }
5082 
5083   Value *RV;
5084   if (ParseValue(Ty, RV, PFS)) return true;
5085 
5086   if (ResType != RV->getType())
5087     return Error(TypeLoc, "value doesn't match function result type '" +
5088                  getTypeString(ResType) + "'");
5089 
5090   Inst = ReturnInst::Create(Context, RV);
5091   return false;
5092 }
5093 
5094 
5095 /// ParseBr
5096 ///   ::= 'br' TypeAndValue
5097 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5098 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5099   LocTy Loc, Loc2;
5100   Value *Op0;
5101   BasicBlock *Op1, *Op2;
5102   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5103 
5104   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5105     Inst = BranchInst::Create(BB);
5106     return false;
5107   }
5108 
5109   if (Op0->getType() != Type::getInt1Ty(Context))
5110     return Error(Loc, "branch condition must have 'i1' type");
5111 
5112   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5113       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5114       ParseToken(lltok::comma, "expected ',' after true destination") ||
5115       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5116     return true;
5117 
5118   Inst = BranchInst::Create(Op1, Op2, Op0);
5119   return false;
5120 }
5121 
5122 /// ParseSwitch
5123 ///  Instruction
5124 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5125 ///  JumpTable
5126 ///    ::= (TypeAndValue ',' TypeAndValue)*
5127 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5128   LocTy CondLoc, BBLoc;
5129   Value *Cond;
5130   BasicBlock *DefaultBB;
5131   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5132       ParseToken(lltok::comma, "expected ',' after switch condition") ||
5133       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5134       ParseToken(lltok::lsquare, "expected '[' with switch table"))
5135     return true;
5136 
5137   if (!Cond->getType()->isIntegerTy())
5138     return Error(CondLoc, "switch condition must have integer type");
5139 
5140   // Parse the jump table pairs.
5141   SmallPtrSet<Value*, 32> SeenCases;
5142   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5143   while (Lex.getKind() != lltok::rsquare) {
5144     Value *Constant;
5145     BasicBlock *DestBB;
5146 
5147     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5148         ParseToken(lltok::comma, "expected ',' after case value") ||
5149         ParseTypeAndBasicBlock(DestBB, PFS))
5150       return true;
5151 
5152     if (!SeenCases.insert(Constant).second)
5153       return Error(CondLoc, "duplicate case value in switch");
5154     if (!isa<ConstantInt>(Constant))
5155       return Error(CondLoc, "case value is not a constant integer");
5156 
5157     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5158   }
5159 
5160   Lex.Lex();  // Eat the ']'.
5161 
5162   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5163   for (unsigned i = 0, e = Table.size(); i != e; ++i)
5164     SI->addCase(Table[i].first, Table[i].second);
5165   Inst = SI;
5166   return false;
5167 }
5168 
5169 /// ParseIndirectBr
5170 ///  Instruction
5171 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5172 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5173   LocTy AddrLoc;
5174   Value *Address;
5175   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5176       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5177       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5178     return true;
5179 
5180   if (!Address->getType()->isPointerTy())
5181     return Error(AddrLoc, "indirectbr address must have pointer type");
5182 
5183   // Parse the destination list.
5184   SmallVector<BasicBlock*, 16> DestList;
5185 
5186   if (Lex.getKind() != lltok::rsquare) {
5187     BasicBlock *DestBB;
5188     if (ParseTypeAndBasicBlock(DestBB, PFS))
5189       return true;
5190     DestList.push_back(DestBB);
5191 
5192     while (EatIfPresent(lltok::comma)) {
5193       if (ParseTypeAndBasicBlock(DestBB, PFS))
5194         return true;
5195       DestList.push_back(DestBB);
5196     }
5197   }
5198 
5199   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5200     return true;
5201 
5202   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5203   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5204     IBI->addDestination(DestList[i]);
5205   Inst = IBI;
5206   return false;
5207 }
5208 
5209 
5210 /// ParseInvoke
5211 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5212 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5213 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5214   LocTy CallLoc = Lex.getLoc();
5215   AttrBuilder RetAttrs, FnAttrs;
5216   std::vector<unsigned> FwdRefAttrGrps;
5217   LocTy NoBuiltinLoc;
5218   unsigned CC;
5219   Type *RetType = nullptr;
5220   LocTy RetTypeLoc;
5221   ValID CalleeID;
5222   SmallVector<ParamInfo, 16> ArgList;
5223   SmallVector<OperandBundleDef, 2> BundleList;
5224 
5225   BasicBlock *NormalBB, *UnwindBB;
5226   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5227       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5228       ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5229       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5230                                  NoBuiltinLoc) ||
5231       ParseOptionalOperandBundles(BundleList, PFS) ||
5232       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5233       ParseTypeAndBasicBlock(NormalBB, PFS) ||
5234       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5235       ParseTypeAndBasicBlock(UnwindBB, PFS))
5236     return true;
5237 
5238   // If RetType is a non-function pointer type, then this is the short syntax
5239   // for the call, which means that RetType is just the return type.  Infer the
5240   // rest of the function argument types from the arguments that are present.
5241   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5242   if (!Ty) {
5243     // Pull out the types of all of the arguments...
5244     std::vector<Type*> ParamTypes;
5245     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5246       ParamTypes.push_back(ArgList[i].V->getType());
5247 
5248     if (!FunctionType::isValidReturnType(RetType))
5249       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5250 
5251     Ty = FunctionType::get(RetType, ParamTypes, false);
5252   }
5253 
5254   CalleeID.FTy = Ty;
5255 
5256   // Look up the callee.
5257   Value *Callee;
5258   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5259     return true;
5260 
5261   // Set up the Attribute for the function.
5262   SmallVector<AttributeSet, 8> Attrs;
5263   if (RetAttrs.hasAttributes())
5264     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5265                                       AttributeSet::ReturnIndex,
5266                                       RetAttrs));
5267 
5268   SmallVector<Value*, 8> Args;
5269 
5270   // Loop through FunctionType's arguments and ensure they are specified
5271   // correctly.  Also, gather any parameter attributes.
5272   FunctionType::param_iterator I = Ty->param_begin();
5273   FunctionType::param_iterator E = Ty->param_end();
5274   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5275     Type *ExpectedTy = nullptr;
5276     if (I != E) {
5277       ExpectedTy = *I++;
5278     } else if (!Ty->isVarArg()) {
5279       return Error(ArgList[i].Loc, "too many arguments specified");
5280     }
5281 
5282     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5283       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5284                    getTypeString(ExpectedTy) + "'");
5285     Args.push_back(ArgList[i].V);
5286     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5287       AttrBuilder B(ArgList[i].Attrs, i + 1);
5288       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5289     }
5290   }
5291 
5292   if (I != E)
5293     return Error(CallLoc, "not enough parameters specified for call");
5294 
5295   if (FnAttrs.hasAttributes()) {
5296     if (FnAttrs.hasAlignmentAttr())
5297       return Error(CallLoc, "invoke instructions may not have an alignment");
5298 
5299     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5300                                       AttributeSet::FunctionIndex,
5301                                       FnAttrs));
5302   }
5303 
5304   // Finish off the Attribute and check them
5305   AttributeSet PAL = AttributeSet::get(Context, Attrs);
5306 
5307   InvokeInst *II =
5308       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5309   II->setCallingConv(CC);
5310   II->setAttributes(PAL);
5311   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5312   Inst = II;
5313   return false;
5314 }
5315 
5316 /// ParseResume
5317 ///   ::= 'resume' TypeAndValue
5318 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5319   Value *Exn; LocTy ExnLoc;
5320   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5321     return true;
5322 
5323   ResumeInst *RI = ResumeInst::Create(Exn);
5324   Inst = RI;
5325   return false;
5326 }
5327 
5328 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5329                                   PerFunctionState &PFS) {
5330   if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5331     return true;
5332 
5333   while (Lex.getKind() != lltok::rsquare) {
5334     // If this isn't the first argument, we need a comma.
5335     if (!Args.empty() &&
5336         ParseToken(lltok::comma, "expected ',' in argument list"))
5337       return true;
5338 
5339     // Parse the argument.
5340     LocTy ArgLoc;
5341     Type *ArgTy = nullptr;
5342     if (ParseType(ArgTy, ArgLoc))
5343       return true;
5344 
5345     Value *V;
5346     if (ArgTy->isMetadataTy()) {
5347       if (ParseMetadataAsValue(V, PFS))
5348         return true;
5349     } else {
5350       if (ParseValue(ArgTy, V, PFS))
5351         return true;
5352     }
5353     Args.push_back(V);
5354   }
5355 
5356   Lex.Lex();  // Lex the ']'.
5357   return false;
5358 }
5359 
5360 /// ParseCleanupRet
5361 ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5362 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5363   Value *CleanupPad = nullptr;
5364 
5365   if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5366     return true;
5367 
5368   if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5369     return true;
5370 
5371   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5372     return true;
5373 
5374   BasicBlock *UnwindBB = nullptr;
5375   if (Lex.getKind() == lltok::kw_to) {
5376     Lex.Lex();
5377     if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5378       return true;
5379   } else {
5380     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5381       return true;
5382     }
5383   }
5384 
5385   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5386   return false;
5387 }
5388 
5389 /// ParseCatchRet
5390 ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
5391 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5392   Value *CatchPad = nullptr;
5393 
5394   if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5395     return true;
5396 
5397   if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5398     return true;
5399 
5400   BasicBlock *BB;
5401   if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5402       ParseTypeAndBasicBlock(BB, PFS))
5403       return true;
5404 
5405   Inst = CatchReturnInst::Create(CatchPad, BB);
5406   return false;
5407 }
5408 
5409 /// ParseCatchSwitch
5410 ///   ::= 'catchswitch' within Parent
5411 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5412   Value *ParentPad;
5413   LocTy BBLoc;
5414 
5415   if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5416     return true;
5417 
5418   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5419       Lex.getKind() != lltok::LocalVarID)
5420     return TokError("expected scope value for catchswitch");
5421 
5422   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5423     return true;
5424 
5425   if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5426     return true;
5427 
5428   SmallVector<BasicBlock *, 32> Table;
5429   do {
5430     BasicBlock *DestBB;
5431     if (ParseTypeAndBasicBlock(DestBB, PFS))
5432       return true;
5433     Table.push_back(DestBB);
5434   } while (EatIfPresent(lltok::comma));
5435 
5436   if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5437     return true;
5438 
5439   if (ParseToken(lltok::kw_unwind,
5440                  "expected 'unwind' after catchswitch scope"))
5441     return true;
5442 
5443   BasicBlock *UnwindBB = nullptr;
5444   if (EatIfPresent(lltok::kw_to)) {
5445     if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5446       return true;
5447   } else {
5448     if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5449       return true;
5450   }
5451 
5452   auto *CatchSwitch =
5453       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5454   for (BasicBlock *DestBB : Table)
5455     CatchSwitch->addHandler(DestBB);
5456   Inst = CatchSwitch;
5457   return false;
5458 }
5459 
5460 /// ParseCatchPad
5461 ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5462 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5463   Value *CatchSwitch = nullptr;
5464 
5465   if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5466     return true;
5467 
5468   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5469     return TokError("expected scope value for catchpad");
5470 
5471   if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5472     return true;
5473 
5474   SmallVector<Value *, 8> Args;
5475   if (ParseExceptionArgs(Args, PFS))
5476     return true;
5477 
5478   Inst = CatchPadInst::Create(CatchSwitch, Args);
5479   return false;
5480 }
5481 
5482 /// ParseCleanupPad
5483 ///   ::= 'cleanuppad' within Parent ParamList
5484 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5485   Value *ParentPad = nullptr;
5486 
5487   if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5488     return true;
5489 
5490   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5491       Lex.getKind() != lltok::LocalVarID)
5492     return TokError("expected scope value for cleanuppad");
5493 
5494   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5495     return true;
5496 
5497   SmallVector<Value *, 8> Args;
5498   if (ParseExceptionArgs(Args, PFS))
5499     return true;
5500 
5501   Inst = CleanupPadInst::Create(ParentPad, Args);
5502   return false;
5503 }
5504 
5505 //===----------------------------------------------------------------------===//
5506 // Binary Operators.
5507 //===----------------------------------------------------------------------===//
5508 
5509 /// ParseArithmetic
5510 ///  ::= ArithmeticOps TypeAndValue ',' Value
5511 ///
5512 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
5513 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5514 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5515                                unsigned Opc, unsigned OperandType) {
5516   LocTy Loc; Value *LHS, *RHS;
5517   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5518       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5519       ParseValue(LHS->getType(), RHS, PFS))
5520     return true;
5521 
5522   bool Valid;
5523   switch (OperandType) {
5524   default: llvm_unreachable("Unknown operand type!");
5525   case 0: // int or FP.
5526     Valid = LHS->getType()->isIntOrIntVectorTy() ||
5527             LHS->getType()->isFPOrFPVectorTy();
5528     break;
5529   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5530   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5531   }
5532 
5533   if (!Valid)
5534     return Error(Loc, "invalid operand type for instruction");
5535 
5536   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5537   return false;
5538 }
5539 
5540 /// ParseLogical
5541 ///  ::= ArithmeticOps TypeAndValue ',' Value {
5542 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5543                             unsigned Opc) {
5544   LocTy Loc; Value *LHS, *RHS;
5545   if (ParseTypeAndValue(LHS, Loc, PFS) ||
5546       ParseToken(lltok::comma, "expected ',' in logical operation") ||
5547       ParseValue(LHS->getType(), RHS, PFS))
5548     return true;
5549 
5550   if (!LHS->getType()->isIntOrIntVectorTy())
5551     return Error(Loc,"instruction requires integer or integer vector operands");
5552 
5553   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5554   return false;
5555 }
5556 
5557 
5558 /// ParseCompare
5559 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
5560 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
5561 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5562                             unsigned Opc) {
5563   // Parse the integer/fp comparison predicate.
5564   LocTy Loc;
5565   unsigned Pred;
5566   Value *LHS, *RHS;
5567   if (ParseCmpPredicate(Pred, Opc) ||
5568       ParseTypeAndValue(LHS, Loc, PFS) ||
5569       ParseToken(lltok::comma, "expected ',' after compare value") ||
5570       ParseValue(LHS->getType(), RHS, PFS))
5571     return true;
5572 
5573   if (Opc == Instruction::FCmp) {
5574     if (!LHS->getType()->isFPOrFPVectorTy())
5575       return Error(Loc, "fcmp requires floating point operands");
5576     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5577   } else {
5578     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5579     if (!LHS->getType()->isIntOrIntVectorTy() &&
5580         !LHS->getType()->getScalarType()->isPointerTy())
5581       return Error(Loc, "icmp requires integer operands");
5582     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5583   }
5584   return false;
5585 }
5586 
5587 //===----------------------------------------------------------------------===//
5588 // Other Instructions.
5589 //===----------------------------------------------------------------------===//
5590 
5591 
5592 /// ParseCast
5593 ///   ::= CastOpc TypeAndValue 'to' Type
5594 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5595                          unsigned Opc) {
5596   LocTy Loc;
5597   Value *Op;
5598   Type *DestTy = nullptr;
5599   if (ParseTypeAndValue(Op, Loc, PFS) ||
5600       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5601       ParseType(DestTy))
5602     return true;
5603 
5604   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5605     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5606     return Error(Loc, "invalid cast opcode for cast from '" +
5607                  getTypeString(Op->getType()) + "' to '" +
5608                  getTypeString(DestTy) + "'");
5609   }
5610   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5611   return false;
5612 }
5613 
5614 /// ParseSelect
5615 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5616 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5617   LocTy Loc;
5618   Value *Op0, *Op1, *Op2;
5619   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5620       ParseToken(lltok::comma, "expected ',' after select condition") ||
5621       ParseTypeAndValue(Op1, PFS) ||
5622       ParseToken(lltok::comma, "expected ',' after select value") ||
5623       ParseTypeAndValue(Op2, PFS))
5624     return true;
5625 
5626   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5627     return Error(Loc, Reason);
5628 
5629   Inst = SelectInst::Create(Op0, Op1, Op2);
5630   return false;
5631 }
5632 
5633 /// ParseVA_Arg
5634 ///   ::= 'va_arg' TypeAndValue ',' Type
5635 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5636   Value *Op;
5637   Type *EltTy = nullptr;
5638   LocTy TypeLoc;
5639   if (ParseTypeAndValue(Op, PFS) ||
5640       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5641       ParseType(EltTy, TypeLoc))
5642     return true;
5643 
5644   if (!EltTy->isFirstClassType())
5645     return Error(TypeLoc, "va_arg requires operand with first class type");
5646 
5647   Inst = new VAArgInst(Op, EltTy);
5648   return false;
5649 }
5650 
5651 /// ParseExtractElement
5652 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
5653 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5654   LocTy Loc;
5655   Value *Op0, *Op1;
5656   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5657       ParseToken(lltok::comma, "expected ',' after extract value") ||
5658       ParseTypeAndValue(Op1, PFS))
5659     return true;
5660 
5661   if (!ExtractElementInst::isValidOperands(Op0, Op1))
5662     return Error(Loc, "invalid extractelement operands");
5663 
5664   Inst = ExtractElementInst::Create(Op0, Op1);
5665   return false;
5666 }
5667 
5668 /// ParseInsertElement
5669 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5670 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5671   LocTy Loc;
5672   Value *Op0, *Op1, *Op2;
5673   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5674       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5675       ParseTypeAndValue(Op1, PFS) ||
5676       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5677       ParseTypeAndValue(Op2, PFS))
5678     return true;
5679 
5680   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5681     return Error(Loc, "invalid insertelement operands");
5682 
5683   Inst = InsertElementInst::Create(Op0, Op1, Op2);
5684   return false;
5685 }
5686 
5687 /// ParseShuffleVector
5688 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5689 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5690   LocTy Loc;
5691   Value *Op0, *Op1, *Op2;
5692   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5693       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5694       ParseTypeAndValue(Op1, PFS) ||
5695       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5696       ParseTypeAndValue(Op2, PFS))
5697     return true;
5698 
5699   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5700     return Error(Loc, "invalid shufflevector operands");
5701 
5702   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5703   return false;
5704 }
5705 
5706 /// ParsePHI
5707 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5708 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5709   Type *Ty = nullptr;  LocTy TypeLoc;
5710   Value *Op0, *Op1;
5711 
5712   if (ParseType(Ty, TypeLoc) ||
5713       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5714       ParseValue(Ty, Op0, PFS) ||
5715       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5716       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5717       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5718     return true;
5719 
5720   bool AteExtraComma = false;
5721   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5722   while (1) {
5723     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5724 
5725     if (!EatIfPresent(lltok::comma))
5726       break;
5727 
5728     if (Lex.getKind() == lltok::MetadataVar) {
5729       AteExtraComma = true;
5730       break;
5731     }
5732 
5733     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5734         ParseValue(Ty, Op0, PFS) ||
5735         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5736         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5737         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5738       return true;
5739   }
5740 
5741   if (!Ty->isFirstClassType())
5742     return Error(TypeLoc, "phi node must have first class type");
5743 
5744   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5745   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5746     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5747   Inst = PN;
5748   return AteExtraComma ? InstExtraComma : InstNormal;
5749 }
5750 
5751 /// ParseLandingPad
5752 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5753 /// Clause
5754 ///   ::= 'catch' TypeAndValue
5755 ///   ::= 'filter'
5756 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5757 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5758   Type *Ty = nullptr; LocTy TyLoc;
5759 
5760   if (ParseType(Ty, TyLoc))
5761     return true;
5762 
5763   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5764   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5765 
5766   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5767     LandingPadInst::ClauseType CT;
5768     if (EatIfPresent(lltok::kw_catch))
5769       CT = LandingPadInst::Catch;
5770     else if (EatIfPresent(lltok::kw_filter))
5771       CT = LandingPadInst::Filter;
5772     else
5773       return TokError("expected 'catch' or 'filter' clause type");
5774 
5775     Value *V;
5776     LocTy VLoc;
5777     if (ParseTypeAndValue(V, VLoc, PFS))
5778       return true;
5779 
5780     // A 'catch' type expects a non-array constant. A filter clause expects an
5781     // array constant.
5782     if (CT == LandingPadInst::Catch) {
5783       if (isa<ArrayType>(V->getType()))
5784         Error(VLoc, "'catch' clause has an invalid type");
5785     } else {
5786       if (!isa<ArrayType>(V->getType()))
5787         Error(VLoc, "'filter' clause has an invalid type");
5788     }
5789 
5790     Constant *CV = dyn_cast<Constant>(V);
5791     if (!CV)
5792       return Error(VLoc, "clause argument must be a constant");
5793     LP->addClause(CV);
5794   }
5795 
5796   Inst = LP.release();
5797   return false;
5798 }
5799 
5800 /// ParseCall
5801 ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
5802 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5803 ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5804 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5805 ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5806 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5807 ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
5808 ///           OptionalAttrs Type Value ParameterList OptionalAttrs
5809 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5810                          CallInst::TailCallKind TCK) {
5811   AttrBuilder RetAttrs, FnAttrs;
5812   std::vector<unsigned> FwdRefAttrGrps;
5813   LocTy BuiltinLoc;
5814   unsigned CC;
5815   Type *RetType = nullptr;
5816   LocTy RetTypeLoc;
5817   ValID CalleeID;
5818   SmallVector<ParamInfo, 16> ArgList;
5819   SmallVector<OperandBundleDef, 2> BundleList;
5820   LocTy CallLoc = Lex.getLoc();
5821 
5822   if (TCK != CallInst::TCK_None &&
5823       ParseToken(lltok::kw_call,
5824                  "expected 'tail call', 'musttail call', or 'notail call'"))
5825     return true;
5826 
5827   FastMathFlags FMF = EatFastMathFlagsIfPresent();
5828 
5829   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5830       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5831       ParseValID(CalleeID) ||
5832       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5833                          PFS.getFunction().isVarArg()) ||
5834       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5835       ParseOptionalOperandBundles(BundleList, PFS))
5836     return true;
5837 
5838   if (FMF.any() && !RetType->isFPOrFPVectorTy())
5839     return Error(CallLoc, "fast-math-flags specified for call without "
5840                           "floating-point scalar or vector return type");
5841 
5842   // If RetType is a non-function pointer type, then this is the short syntax
5843   // for the call, which means that RetType is just the return type.  Infer the
5844   // rest of the function argument types from the arguments that are present.
5845   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5846   if (!Ty) {
5847     // Pull out the types of all of the arguments...
5848     std::vector<Type*> ParamTypes;
5849     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5850       ParamTypes.push_back(ArgList[i].V->getType());
5851 
5852     if (!FunctionType::isValidReturnType(RetType))
5853       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5854 
5855     Ty = FunctionType::get(RetType, ParamTypes, false);
5856   }
5857 
5858   CalleeID.FTy = Ty;
5859 
5860   // Look up the callee.
5861   Value *Callee;
5862   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5863     return true;
5864 
5865   // Set up the Attribute for the function.
5866   SmallVector<AttributeSet, 8> Attrs;
5867   if (RetAttrs.hasAttributes())
5868     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5869                                       AttributeSet::ReturnIndex,
5870                                       RetAttrs));
5871 
5872   SmallVector<Value*, 8> Args;
5873 
5874   // Loop through FunctionType's arguments and ensure they are specified
5875   // correctly.  Also, gather any parameter attributes.
5876   FunctionType::param_iterator I = Ty->param_begin();
5877   FunctionType::param_iterator E = Ty->param_end();
5878   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5879     Type *ExpectedTy = nullptr;
5880     if (I != E) {
5881       ExpectedTy = *I++;
5882     } else if (!Ty->isVarArg()) {
5883       return Error(ArgList[i].Loc, "too many arguments specified");
5884     }
5885 
5886     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5887       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5888                    getTypeString(ExpectedTy) + "'");
5889     Args.push_back(ArgList[i].V);
5890     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5891       AttrBuilder B(ArgList[i].Attrs, i + 1);
5892       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5893     }
5894   }
5895 
5896   if (I != E)
5897     return Error(CallLoc, "not enough parameters specified for call");
5898 
5899   if (FnAttrs.hasAttributes()) {
5900     if (FnAttrs.hasAlignmentAttr())
5901       return Error(CallLoc, "call instructions may not have an alignment");
5902 
5903     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5904                                       AttributeSet::FunctionIndex,
5905                                       FnAttrs));
5906   }
5907 
5908   // Finish off the Attribute and check them
5909   AttributeSet PAL = AttributeSet::get(Context, Attrs);
5910 
5911   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
5912   CI->setTailCallKind(TCK);
5913   CI->setCallingConv(CC);
5914   if (FMF.any())
5915     CI->setFastMathFlags(FMF);
5916   CI->setAttributes(PAL);
5917   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5918   Inst = CI;
5919   return false;
5920 }
5921 
5922 //===----------------------------------------------------------------------===//
5923 // Memory Instructions.
5924 //===----------------------------------------------------------------------===//
5925 
5926 /// ParseAlloc
5927 ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5928 ///       (',' 'align' i32)?
5929 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5930   Value *Size = nullptr;
5931   LocTy SizeLoc, TyLoc;
5932   unsigned Alignment = 0;
5933   Type *Ty = nullptr;
5934 
5935   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5936   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
5937 
5938   if (ParseType(Ty, TyLoc)) return true;
5939 
5940   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5941     return Error(TyLoc, "invalid type for alloca");
5942 
5943   bool AteExtraComma = false;
5944   if (EatIfPresent(lltok::comma)) {
5945     if (Lex.getKind() == lltok::kw_align) {
5946       if (ParseOptionalAlignment(Alignment)) return true;
5947     } else if (Lex.getKind() == lltok::MetadataVar) {
5948       AteExtraComma = true;
5949     } else {
5950       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5951           ParseOptionalCommaAlign(Alignment, AteExtraComma))
5952         return true;
5953     }
5954   }
5955 
5956   if (Size && !Size->getType()->isIntegerTy())
5957     return Error(SizeLoc, "element count must have integer type");
5958 
5959   AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5960   AI->setUsedWithInAlloca(IsInAlloca);
5961   AI->setSwiftError(IsSwiftError);
5962   Inst = AI;
5963   return AteExtraComma ? InstExtraComma : InstNormal;
5964 }
5965 
5966 /// ParseLoad
5967 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5968 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
5969 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5970 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5971   Value *Val; LocTy Loc;
5972   unsigned Alignment = 0;
5973   bool AteExtraComma = false;
5974   bool isAtomic = false;
5975   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
5976   SynchronizationScope Scope = CrossThread;
5977 
5978   if (Lex.getKind() == lltok::kw_atomic) {
5979     isAtomic = true;
5980     Lex.Lex();
5981   }
5982 
5983   bool isVolatile = false;
5984   if (Lex.getKind() == lltok::kw_volatile) {
5985     isVolatile = true;
5986     Lex.Lex();
5987   }
5988 
5989   Type *Ty;
5990   LocTy ExplicitTypeLoc = Lex.getLoc();
5991   if (ParseType(Ty) ||
5992       ParseToken(lltok::comma, "expected comma after load's type") ||
5993       ParseTypeAndValue(Val, Loc, PFS) ||
5994       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5995       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5996     return true;
5997 
5998   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5999     return Error(Loc, "load operand must be a pointer to a first class type");
6000   if (isAtomic && !Alignment)
6001     return Error(Loc, "atomic load must have explicit non-zero alignment");
6002   if (Ordering == AtomicOrdering::Release ||
6003       Ordering == AtomicOrdering::AcquireRelease)
6004     return Error(Loc, "atomic load cannot use Release ordering");
6005 
6006   if (Ty != cast<PointerType>(Val->getType())->getElementType())
6007     return Error(ExplicitTypeLoc,
6008                  "explicit pointee type doesn't match operand's pointee type");
6009 
6010   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
6011   return AteExtraComma ? InstExtraComma : InstNormal;
6012 }
6013 
6014 /// ParseStore
6015 
6016 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6017 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6018 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
6019 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6020   Value *Val, *Ptr; LocTy Loc, PtrLoc;
6021   unsigned Alignment = 0;
6022   bool AteExtraComma = false;
6023   bool isAtomic = false;
6024   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6025   SynchronizationScope Scope = CrossThread;
6026 
6027   if (Lex.getKind() == lltok::kw_atomic) {
6028     isAtomic = true;
6029     Lex.Lex();
6030   }
6031 
6032   bool isVolatile = false;
6033   if (Lex.getKind() == lltok::kw_volatile) {
6034     isVolatile = true;
6035     Lex.Lex();
6036   }
6037 
6038   if (ParseTypeAndValue(Val, Loc, PFS) ||
6039       ParseToken(lltok::comma, "expected ',' after store operand") ||
6040       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6041       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6042       ParseOptionalCommaAlign(Alignment, AteExtraComma))
6043     return true;
6044 
6045   if (!Ptr->getType()->isPointerTy())
6046     return Error(PtrLoc, "store operand must be a pointer");
6047   if (!Val->getType()->isFirstClassType())
6048     return Error(Loc, "store operand must be a first class value");
6049   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6050     return Error(Loc, "stored value and pointer type do not match");
6051   if (isAtomic && !Alignment)
6052     return Error(Loc, "atomic store must have explicit non-zero alignment");
6053   if (Ordering == AtomicOrdering::Acquire ||
6054       Ordering == AtomicOrdering::AcquireRelease)
6055     return Error(Loc, "atomic store cannot use Acquire ordering");
6056 
6057   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
6058   return AteExtraComma ? InstExtraComma : InstNormal;
6059 }
6060 
6061 /// ParseCmpXchg
6062 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6063 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6064 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6065   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6066   bool AteExtraComma = false;
6067   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6068   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6069   SynchronizationScope Scope = CrossThread;
6070   bool isVolatile = false;
6071   bool isWeak = false;
6072 
6073   if (EatIfPresent(lltok::kw_weak))
6074     isWeak = true;
6075 
6076   if (EatIfPresent(lltok::kw_volatile))
6077     isVolatile = true;
6078 
6079   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6080       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6081       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6082       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6083       ParseTypeAndValue(New, NewLoc, PFS) ||
6084       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6085       ParseOrdering(FailureOrdering))
6086     return true;
6087 
6088   if (SuccessOrdering == AtomicOrdering::Unordered ||
6089       FailureOrdering == AtomicOrdering::Unordered)
6090     return TokError("cmpxchg cannot be unordered");
6091   if (isStrongerThan(FailureOrdering, SuccessOrdering))
6092     return TokError("cmpxchg failure argument shall be no stronger than the "
6093                     "success argument");
6094   if (FailureOrdering == AtomicOrdering::Release ||
6095       FailureOrdering == AtomicOrdering::AcquireRelease)
6096     return TokError(
6097         "cmpxchg failure ordering cannot include release semantics");
6098   if (!Ptr->getType()->isPointerTy())
6099     return Error(PtrLoc, "cmpxchg operand must be a pointer");
6100   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6101     return Error(CmpLoc, "compare value and pointer type do not match");
6102   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6103     return Error(NewLoc, "new value and pointer type do not match");
6104   if (!New->getType()->isFirstClassType())
6105     return Error(NewLoc, "cmpxchg operand must be a first class value");
6106   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6107       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
6108   CXI->setVolatile(isVolatile);
6109   CXI->setWeak(isWeak);
6110   Inst = CXI;
6111   return AteExtraComma ? InstExtraComma : InstNormal;
6112 }
6113 
6114 /// ParseAtomicRMW
6115 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6116 ///       'singlethread'? AtomicOrdering
6117 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6118   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6119   bool AteExtraComma = false;
6120   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6121   SynchronizationScope Scope = CrossThread;
6122   bool isVolatile = false;
6123   AtomicRMWInst::BinOp Operation;
6124 
6125   if (EatIfPresent(lltok::kw_volatile))
6126     isVolatile = true;
6127 
6128   switch (Lex.getKind()) {
6129   default: return TokError("expected binary operation in atomicrmw");
6130   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6131   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6132   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6133   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6134   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6135   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6136   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6137   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6138   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6139   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6140   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6141   }
6142   Lex.Lex();  // Eat the operation.
6143 
6144   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6145       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6146       ParseTypeAndValue(Val, ValLoc, PFS) ||
6147       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6148     return true;
6149 
6150   if (Ordering == AtomicOrdering::Unordered)
6151     return TokError("atomicrmw cannot be unordered");
6152   if (!Ptr->getType()->isPointerTy())
6153     return Error(PtrLoc, "atomicrmw operand must be a pointer");
6154   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6155     return Error(ValLoc, "atomicrmw value and pointer type do not match");
6156   if (!Val->getType()->isIntegerTy())
6157     return Error(ValLoc, "atomicrmw operand must be an integer");
6158   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6159   if (Size < 8 || (Size & (Size - 1)))
6160     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6161                          " integer");
6162 
6163   AtomicRMWInst *RMWI =
6164     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6165   RMWI->setVolatile(isVolatile);
6166   Inst = RMWI;
6167   return AteExtraComma ? InstExtraComma : InstNormal;
6168 }
6169 
6170 /// ParseFence
6171 ///   ::= 'fence' 'singlethread'? AtomicOrdering
6172 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6173   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6174   SynchronizationScope Scope = CrossThread;
6175   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6176     return true;
6177 
6178   if (Ordering == AtomicOrdering::Unordered)
6179     return TokError("fence cannot be unordered");
6180   if (Ordering == AtomicOrdering::Monotonic)
6181     return TokError("fence cannot be monotonic");
6182 
6183   Inst = new FenceInst(Context, Ordering, Scope);
6184   return InstNormal;
6185 }
6186 
6187 /// ParseGetElementPtr
6188 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6189 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6190   Value *Ptr = nullptr;
6191   Value *Val = nullptr;
6192   LocTy Loc, EltLoc;
6193 
6194   bool InBounds = EatIfPresent(lltok::kw_inbounds);
6195 
6196   Type *Ty = nullptr;
6197   LocTy ExplicitTypeLoc = Lex.getLoc();
6198   if (ParseType(Ty) ||
6199       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6200       ParseTypeAndValue(Ptr, Loc, PFS))
6201     return true;
6202 
6203   Type *BaseType = Ptr->getType();
6204   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6205   if (!BasePointerType)
6206     return Error(Loc, "base of getelementptr must be a pointer");
6207 
6208   if (Ty != BasePointerType->getElementType())
6209     return Error(ExplicitTypeLoc,
6210                  "explicit pointee type doesn't match operand's pointee type");
6211 
6212   SmallVector<Value*, 16> Indices;
6213   bool AteExtraComma = false;
6214   // GEP returns a vector of pointers if at least one of parameters is a vector.
6215   // All vector parameters should have the same vector width.
6216   unsigned GEPWidth = BaseType->isVectorTy() ?
6217     BaseType->getVectorNumElements() : 0;
6218 
6219   while (EatIfPresent(lltok::comma)) {
6220     if (Lex.getKind() == lltok::MetadataVar) {
6221       AteExtraComma = true;
6222       break;
6223     }
6224     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6225     if (!Val->getType()->getScalarType()->isIntegerTy())
6226       return Error(EltLoc, "getelementptr index must be an integer");
6227 
6228     if (Val->getType()->isVectorTy()) {
6229       unsigned ValNumEl = Val->getType()->getVectorNumElements();
6230       if (GEPWidth && GEPWidth != ValNumEl)
6231         return Error(EltLoc,
6232           "getelementptr vector index has a wrong number of elements");
6233       GEPWidth = ValNumEl;
6234     }
6235     Indices.push_back(Val);
6236   }
6237 
6238   SmallPtrSet<Type*, 4> Visited;
6239   if (!Indices.empty() && !Ty->isSized(&Visited))
6240     return Error(Loc, "base element of getelementptr must be sized");
6241 
6242   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6243     return Error(Loc, "invalid getelementptr indices");
6244   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6245   if (InBounds)
6246     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6247   return AteExtraComma ? InstExtraComma : InstNormal;
6248 }
6249 
6250 /// ParseExtractValue
6251 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
6252 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6253   Value *Val; LocTy Loc;
6254   SmallVector<unsigned, 4> Indices;
6255   bool AteExtraComma;
6256   if (ParseTypeAndValue(Val, Loc, PFS) ||
6257       ParseIndexList(Indices, AteExtraComma))
6258     return true;
6259 
6260   if (!Val->getType()->isAggregateType())
6261     return Error(Loc, "extractvalue operand must be aggregate type");
6262 
6263   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6264     return Error(Loc, "invalid indices for extractvalue");
6265   Inst = ExtractValueInst::Create(Val, Indices);
6266   return AteExtraComma ? InstExtraComma : InstNormal;
6267 }
6268 
6269 /// ParseInsertValue
6270 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6271 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6272   Value *Val0, *Val1; LocTy Loc0, Loc1;
6273   SmallVector<unsigned, 4> Indices;
6274   bool AteExtraComma;
6275   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6276       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6277       ParseTypeAndValue(Val1, Loc1, PFS) ||
6278       ParseIndexList(Indices, AteExtraComma))
6279     return true;
6280 
6281   if (!Val0->getType()->isAggregateType())
6282     return Error(Loc0, "insertvalue operand must be aggregate type");
6283 
6284   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6285   if (!IndexedType)
6286     return Error(Loc0, "invalid indices for insertvalue");
6287   if (IndexedType != Val1->getType())
6288     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6289                            getTypeString(Val1->getType()) + "' instead of '" +
6290                            getTypeString(IndexedType) + "'");
6291   Inst = InsertValueInst::Create(Val0, Val1, Indices);
6292   return AteExtraComma ? InstExtraComma : InstNormal;
6293 }
6294 
6295 //===----------------------------------------------------------------------===//
6296 // Embedded metadata.
6297 //===----------------------------------------------------------------------===//
6298 
6299 /// ParseMDNodeVector
6300 ///   ::= { Element (',' Element)* }
6301 /// Element
6302 ///   ::= 'null' | TypeAndValue
6303 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6304   if (ParseToken(lltok::lbrace, "expected '{' here"))
6305     return true;
6306 
6307   // Check for an empty list.
6308   if (EatIfPresent(lltok::rbrace))
6309     return false;
6310 
6311   do {
6312     // Null is a special case since it is typeless.
6313     if (EatIfPresent(lltok::kw_null)) {
6314       Elts.push_back(nullptr);
6315       continue;
6316     }
6317 
6318     Metadata *MD;
6319     if (ParseMetadata(MD, nullptr))
6320       return true;
6321     Elts.push_back(MD);
6322   } while (EatIfPresent(lltok::comma));
6323 
6324   return ParseToken(lltok::rbrace, "expected end of metadata node");
6325 }
6326 
6327 //===----------------------------------------------------------------------===//
6328 // Use-list order directives.
6329 //===----------------------------------------------------------------------===//
6330 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6331                                 SMLoc Loc) {
6332   if (V->use_empty())
6333     return Error(Loc, "value has no uses");
6334 
6335   unsigned NumUses = 0;
6336   SmallDenseMap<const Use *, unsigned, 16> Order;
6337   for (const Use &U : V->uses()) {
6338     if (++NumUses > Indexes.size())
6339       break;
6340     Order[&U] = Indexes[NumUses - 1];
6341   }
6342   if (NumUses < 2)
6343     return Error(Loc, "value only has one use");
6344   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6345     return Error(Loc, "wrong number of indexes, expected " +
6346                           Twine(std::distance(V->use_begin(), V->use_end())));
6347 
6348   V->sortUseList([&](const Use &L, const Use &R) {
6349     return Order.lookup(&L) < Order.lookup(&R);
6350   });
6351   return false;
6352 }
6353 
6354 /// ParseUseListOrderIndexes
6355 ///   ::= '{' uint32 (',' uint32)+ '}'
6356 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6357   SMLoc Loc = Lex.getLoc();
6358   if (ParseToken(lltok::lbrace, "expected '{' here"))
6359     return true;
6360   if (Lex.getKind() == lltok::rbrace)
6361     return Lex.Error("expected non-empty list of uselistorder indexes");
6362 
6363   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
6364   // indexes should be distinct numbers in the range [0, size-1], and should
6365   // not be in order.
6366   unsigned Offset = 0;
6367   unsigned Max = 0;
6368   bool IsOrdered = true;
6369   assert(Indexes.empty() && "Expected empty order vector");
6370   do {
6371     unsigned Index;
6372     if (ParseUInt32(Index))
6373       return true;
6374 
6375     // Update consistency checks.
6376     Offset += Index - Indexes.size();
6377     Max = std::max(Max, Index);
6378     IsOrdered &= Index == Indexes.size();
6379 
6380     Indexes.push_back(Index);
6381   } while (EatIfPresent(lltok::comma));
6382 
6383   if (ParseToken(lltok::rbrace, "expected '}' here"))
6384     return true;
6385 
6386   if (Indexes.size() < 2)
6387     return Error(Loc, "expected >= 2 uselistorder indexes");
6388   if (Offset != 0 || Max >= Indexes.size())
6389     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6390   if (IsOrdered)
6391     return Error(Loc, "expected uselistorder indexes to change the order");
6392 
6393   return false;
6394 }
6395 
6396 /// ParseUseListOrder
6397 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6398 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6399   SMLoc Loc = Lex.getLoc();
6400   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6401     return true;
6402 
6403   Value *V;
6404   SmallVector<unsigned, 16> Indexes;
6405   if (ParseTypeAndValue(V, PFS) ||
6406       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6407       ParseUseListOrderIndexes(Indexes))
6408     return true;
6409 
6410   return sortUseListOrder(V, Indexes, Loc);
6411 }
6412 
6413 /// ParseUseListOrderBB
6414 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6415 bool LLParser::ParseUseListOrderBB() {
6416   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6417   SMLoc Loc = Lex.getLoc();
6418   Lex.Lex();
6419 
6420   ValID Fn, Label;
6421   SmallVector<unsigned, 16> Indexes;
6422   if (ParseValID(Fn) ||
6423       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6424       ParseValID(Label) ||
6425       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6426       ParseUseListOrderIndexes(Indexes))
6427     return true;
6428 
6429   // Check the function.
6430   GlobalValue *GV;
6431   if (Fn.Kind == ValID::t_GlobalName)
6432     GV = M->getNamedValue(Fn.StrVal);
6433   else if (Fn.Kind == ValID::t_GlobalID)
6434     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6435   else
6436     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6437   if (!GV)
6438     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6439   auto *F = dyn_cast<Function>(GV);
6440   if (!F)
6441     return Error(Fn.Loc, "expected function name in uselistorder_bb");
6442   if (F->isDeclaration())
6443     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6444 
6445   // Check the basic block.
6446   if (Label.Kind == ValID::t_LocalID)
6447     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6448   if (Label.Kind != ValID::t_LocalName)
6449     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6450   Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6451   if (!V)
6452     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6453   if (!isa<BasicBlock>(V))
6454     return Error(Label.Loc, "expected basic block in uselistorder_bb");
6455 
6456   return sortUseListOrder(V, Indexes, Loc);
6457 }
6458