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