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