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