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