fix parsing of mdstring values.
[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/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 /// Run: module ::= toplevelentity*
31 bool LLParser::Run() {
32   // Prime the lexer.
33   Lex.Lex();
34
35   return ParseTopLevelEntities() ||
36          ValidateEndOfModule();
37 }
38
39 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40 /// module.
41 bool LLParser::ValidateEndOfModule() {
42   // Update auto-upgraded malloc calls to "malloc".
43   // FIXME: Remove in LLVM 3.0.
44   if (MallocF) {
45     MallocF->setName("malloc");
46     // If setName() does not set the name to "malloc", then there is already a 
47     // declaration of "malloc".  In that case, iterate over all calls to MallocF
48     // and get them to call the declared "malloc" instead.
49     if (MallocF->getName() != "malloc") {
50       Constant *RealMallocF = M->getFunction("malloc");
51       if (RealMallocF->getType() != MallocF->getType())
52         RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
53       MallocF->replaceAllUsesWith(RealMallocF);
54       MallocF->eraseFromParent();
55       MallocF = NULL;
56     }
57   }
58   
59   
60   // If there are entries in ForwardRefBlockAddresses at this point, they are
61   // references after the function was defined.  Resolve those now.
62   while (!ForwardRefBlockAddresses.empty()) {
63     // Okay, we are referencing an already-parsed function, resolve them now.
64     Function *TheFn = 0;
65     const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
66     if (Fn.Kind == ValID::t_GlobalName)
67       TheFn = M->getFunction(Fn.StrVal);
68     else if (Fn.UIntVal < NumberedVals.size())
69       TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
70     
71     if (TheFn == 0)
72       return Error(Fn.Loc, "unknown function referenced by blockaddress");
73     
74     // Resolve all these references.
75     if (ResolveForwardRefBlockAddresses(TheFn, 
76                                       ForwardRefBlockAddresses.begin()->second,
77                                         0))
78       return true;
79     
80     ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
81   }
82   
83   
84   if (!ForwardRefTypes.empty())
85     return Error(ForwardRefTypes.begin()->second.second,
86                  "use of undefined type named '" +
87                  ForwardRefTypes.begin()->first + "'");
88   if (!ForwardRefTypeIDs.empty())
89     return Error(ForwardRefTypeIDs.begin()->second.second,
90                  "use of undefined type '%" +
91                  utostr(ForwardRefTypeIDs.begin()->first) + "'");
92
93   if (!ForwardRefVals.empty())
94     return Error(ForwardRefVals.begin()->second.second,
95                  "use of undefined value '@" + ForwardRefVals.begin()->first +
96                  "'");
97
98   if (!ForwardRefValIDs.empty())
99     return Error(ForwardRefValIDs.begin()->second.second,
100                  "use of undefined value '@" +
101                  utostr(ForwardRefValIDs.begin()->first) + "'");
102
103   if (!ForwardRefMDNodes.empty())
104     return Error(ForwardRefMDNodes.begin()->second.second,
105                  "use of undefined metadata '!" +
106                  utostr(ForwardRefMDNodes.begin()->first) + "'");
107
108
109   // Look for intrinsic functions and CallInst that need to be upgraded
110   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
111     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
112
113   // Check debug info intrinsics.
114   CheckDebugInfoIntrinsics(M);
115   return false;
116 }
117
118 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn, 
119                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
120                                                PerFunctionState *PFS) {
121   // Loop over all the references, resolving them.
122   for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
123     BasicBlock *Res;
124     if (PFS) {
125       if (Refs[i].first.Kind == ValID::t_LocalName)
126         Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
127       else
128         Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
129     } else if (Refs[i].first.Kind == ValID::t_LocalID) {
130       return Error(Refs[i].first.Loc,
131        "cannot take address of numeric label after the function is defined");
132     } else {
133       Res = dyn_cast_or_null<BasicBlock>(
134                      TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
135     }
136     
137     if (Res == 0)
138       return Error(Refs[i].first.Loc,
139                    "referenced value is not a basic block");
140     
141     // Get the BlockAddress for this and update references to use it.
142     BlockAddress *BA = BlockAddress::get(TheFn, Res);
143     Refs[i].second->replaceAllUsesWith(BA);
144     Refs[i].second->eraseFromParent();
145   }
146   return false;
147 }
148
149
150 //===----------------------------------------------------------------------===//
151 // Top-Level Entities
152 //===----------------------------------------------------------------------===//
153
154 bool LLParser::ParseTopLevelEntities() {
155   while (1) {
156     switch (Lex.getKind()) {
157     default:         return TokError("expected top-level entity");
158     case lltok::Eof: return false;
159     //case lltok::kw_define:
160     case lltok::kw_declare: if (ParseDeclare()) return true; break;
161     case lltok::kw_define:  if (ParseDefine()) return true; break;
162     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
163     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
164     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
165     case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
166     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
167     case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
168     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
169     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
170     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
171     case lltok::Metadata:   if (ParseStandaloneMetadata()) return true; break;
172     case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
173
174     // The Global variable production with no name can have many different
175     // optional leading prefixes, the production is:
176     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
177     //               OptionalAddrSpace ('constant'|'global') ...
178     case lltok::kw_private :       // OptionalLinkage
179     case lltok::kw_linker_private: // OptionalLinkage
180     case lltok::kw_internal:       // OptionalLinkage
181     case lltok::kw_weak:           // OptionalLinkage
182     case lltok::kw_weak_odr:       // OptionalLinkage
183     case lltok::kw_linkonce:       // OptionalLinkage
184     case lltok::kw_linkonce_odr:   // OptionalLinkage
185     case lltok::kw_appending:      // OptionalLinkage
186     case lltok::kw_dllexport:      // OptionalLinkage
187     case lltok::kw_common:         // OptionalLinkage
188     case lltok::kw_dllimport:      // OptionalLinkage
189     case lltok::kw_extern_weak:    // OptionalLinkage
190     case lltok::kw_external: {     // OptionalLinkage
191       unsigned Linkage, Visibility;
192       if (ParseOptionalLinkage(Linkage) ||
193           ParseOptionalVisibility(Visibility) ||
194           ParseGlobal("", SMLoc(), Linkage, true, Visibility))
195         return true;
196       break;
197     }
198     case lltok::kw_default:       // OptionalVisibility
199     case lltok::kw_hidden:        // OptionalVisibility
200     case lltok::kw_protected: {   // OptionalVisibility
201       unsigned Visibility;
202       if (ParseOptionalVisibility(Visibility) ||
203           ParseGlobal("", SMLoc(), 0, false, Visibility))
204         return true;
205       break;
206     }
207
208     case lltok::kw_thread_local:  // OptionalThreadLocal
209     case lltok::kw_addrspace:     // OptionalAddrSpace
210     case lltok::kw_constant:      // GlobalType
211     case lltok::kw_global:        // GlobalType
212       if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
213       break;
214     }
215   }
216 }
217
218
219 /// toplevelentity
220 ///   ::= 'module' 'asm' STRINGCONSTANT
221 bool LLParser::ParseModuleAsm() {
222   assert(Lex.getKind() == lltok::kw_module);
223   Lex.Lex();
224
225   std::string AsmStr;
226   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
227       ParseStringConstant(AsmStr)) return true;
228
229   const std::string &AsmSoFar = M->getModuleInlineAsm();
230   if (AsmSoFar.empty())
231     M->setModuleInlineAsm(AsmStr);
232   else
233     M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
234   return false;
235 }
236
237 /// toplevelentity
238 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
239 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
240 bool LLParser::ParseTargetDefinition() {
241   assert(Lex.getKind() == lltok::kw_target);
242   std::string Str;
243   switch (Lex.Lex()) {
244   default: return TokError("unknown target property");
245   case lltok::kw_triple:
246     Lex.Lex();
247     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
248         ParseStringConstant(Str))
249       return true;
250     M->setTargetTriple(Str);
251     return false;
252   case lltok::kw_datalayout:
253     Lex.Lex();
254     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
255         ParseStringConstant(Str))
256       return true;
257     M->setDataLayout(Str);
258     return false;
259   }
260 }
261
262 /// toplevelentity
263 ///   ::= 'deplibs' '=' '[' ']'
264 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
265 bool LLParser::ParseDepLibs() {
266   assert(Lex.getKind() == lltok::kw_deplibs);
267   Lex.Lex();
268   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
269       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
270     return true;
271
272   if (EatIfPresent(lltok::rsquare))
273     return false;
274
275   std::string Str;
276   if (ParseStringConstant(Str)) return true;
277   M->addLibrary(Str);
278
279   while (EatIfPresent(lltok::comma)) {
280     if (ParseStringConstant(Str)) return true;
281     M->addLibrary(Str);
282   }
283
284   return ParseToken(lltok::rsquare, "expected ']' at end of list");
285 }
286
287 /// ParseUnnamedType:
288 ///   ::= 'type' type
289 ///   ::= LocalVarID '=' 'type' type
290 bool LLParser::ParseUnnamedType() {
291   unsigned TypeID = NumberedTypes.size();
292
293   // Handle the LocalVarID form.
294   if (Lex.getKind() == lltok::LocalVarID) {
295     if (Lex.getUIntVal() != TypeID)
296       return Error(Lex.getLoc(), "type expected to be numbered '%" +
297                    utostr(TypeID) + "'");
298     Lex.Lex(); // eat LocalVarID;
299
300     if (ParseToken(lltok::equal, "expected '=' after name"))
301       return true;
302   }
303
304   assert(Lex.getKind() == lltok::kw_type);
305   LocTy TypeLoc = Lex.getLoc();
306   Lex.Lex(); // eat kw_type
307
308   PATypeHolder Ty(Type::getVoidTy(Context));
309   if (ParseType(Ty)) return true;
310
311   // See if this type was previously referenced.
312   std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
313     FI = ForwardRefTypeIDs.find(TypeID);
314   if (FI != ForwardRefTypeIDs.end()) {
315     if (FI->second.first.get() == Ty)
316       return Error(TypeLoc, "self referential type is invalid");
317
318     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
319     Ty = FI->second.first.get();
320     ForwardRefTypeIDs.erase(FI);
321   }
322
323   NumberedTypes.push_back(Ty);
324
325   return false;
326 }
327
328 /// toplevelentity
329 ///   ::= LocalVar '=' 'type' type
330 bool LLParser::ParseNamedType() {
331   std::string Name = Lex.getStrVal();
332   LocTy NameLoc = Lex.getLoc();
333   Lex.Lex();  // eat LocalVar.
334
335   PATypeHolder Ty(Type::getVoidTy(Context));
336
337   if (ParseToken(lltok::equal, "expected '=' after name") ||
338       ParseToken(lltok::kw_type, "expected 'type' after name") ||
339       ParseType(Ty))
340     return true;
341
342   // Set the type name, checking for conflicts as we do so.
343   bool AlreadyExists = M->addTypeName(Name, Ty);
344   if (!AlreadyExists) return false;
345
346   // See if this type is a forward reference.  We need to eagerly resolve
347   // types to allow recursive type redefinitions below.
348   std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
349   FI = ForwardRefTypes.find(Name);
350   if (FI != ForwardRefTypes.end()) {
351     if (FI->second.first.get() == Ty)
352       return Error(NameLoc, "self referential type is invalid");
353
354     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
355     Ty = FI->second.first.get();
356     ForwardRefTypes.erase(FI);
357   }
358
359   // Inserting a name that is already defined, get the existing name.
360   const Type *Existing = M->getTypeByName(Name);
361   assert(Existing && "Conflict but no matching type?!");
362
363   // Otherwise, this is an attempt to redefine a type. That's okay if
364   // the redefinition is identical to the original.
365   // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
366   if (Existing == Ty) return false;
367
368   // Any other kind of (non-equivalent) redefinition is an error.
369   return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
370                Ty->getDescription() + "'");
371 }
372
373
374 /// toplevelentity
375 ///   ::= 'declare' FunctionHeader
376 bool LLParser::ParseDeclare() {
377   assert(Lex.getKind() == lltok::kw_declare);
378   Lex.Lex();
379
380   Function *F;
381   return ParseFunctionHeader(F, false);
382 }
383
384 /// toplevelentity
385 ///   ::= 'define' FunctionHeader '{' ...
386 bool LLParser::ParseDefine() {
387   assert(Lex.getKind() == lltok::kw_define);
388   Lex.Lex();
389
390   Function *F;
391   return ParseFunctionHeader(F, true) ||
392          ParseFunctionBody(*F);
393 }
394
395 /// ParseGlobalType
396 ///   ::= 'constant'
397 ///   ::= 'global'
398 bool LLParser::ParseGlobalType(bool &IsConstant) {
399   if (Lex.getKind() == lltok::kw_constant)
400     IsConstant = true;
401   else if (Lex.getKind() == lltok::kw_global)
402     IsConstant = false;
403   else {
404     IsConstant = false;
405     return TokError("expected 'global' or 'constant'");
406   }
407   Lex.Lex();
408   return false;
409 }
410
411 /// ParseUnnamedGlobal:
412 ///   OptionalVisibility ALIAS ...
413 ///   OptionalLinkage OptionalVisibility ...   -> global variable
414 ///   GlobalID '=' OptionalVisibility ALIAS ...
415 ///   GlobalID '=' OptionalLinkage OptionalVisibility ...   -> global variable
416 bool LLParser::ParseUnnamedGlobal() {
417   unsigned VarID = NumberedVals.size();
418   std::string Name;
419   LocTy NameLoc = Lex.getLoc();
420
421   // Handle the GlobalID form.
422   if (Lex.getKind() == lltok::GlobalID) {
423     if (Lex.getUIntVal() != VarID)
424       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
425                    utostr(VarID) + "'");
426     Lex.Lex(); // eat GlobalID;
427
428     if (ParseToken(lltok::equal, "expected '=' after name"))
429       return true;
430   }
431
432   bool HasLinkage;
433   unsigned Linkage, Visibility;
434   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
435       ParseOptionalVisibility(Visibility))
436     return true;
437
438   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
439     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
440   return ParseAlias(Name, NameLoc, Visibility);
441 }
442
443 /// ParseNamedGlobal:
444 ///   GlobalVar '=' OptionalVisibility ALIAS ...
445 ///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
446 bool LLParser::ParseNamedGlobal() {
447   assert(Lex.getKind() == lltok::GlobalVar);
448   LocTy NameLoc = Lex.getLoc();
449   std::string Name = Lex.getStrVal();
450   Lex.Lex();
451
452   bool HasLinkage;
453   unsigned Linkage, Visibility;
454   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
455       ParseOptionalLinkage(Linkage, HasLinkage) ||
456       ParseOptionalVisibility(Visibility))
457     return true;
458
459   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461   return ParseAlias(Name, NameLoc, Visibility);
462 }
463
464 // MDString:
465 //   ::= '!' STRINGCONSTANT
466 bool LLParser::ParseMDString(MDString *&Result) {
467   std::string Str;
468   if (ParseStringConstant(Str)) return true;
469   Result = MDString::get(Context, Str);
470   return false;
471 }
472
473 // MDNode:
474 //   ::= '!' MDNodeNumber
475 bool LLParser::ParseMDNode(MDNode *&Result) {
476   // !{ ..., !42, ... }
477   unsigned MID = 0;
478   if (ParseUInt32(MID)) return true;
479
480   // Check existing MDNode.
481   std::map<unsigned, TrackingVH<MDNode> >::iterator I = MetadataCache.find(MID);
482   if (I != MetadataCache.end()) {
483     Result = I->second;
484     return false;
485   }
486
487   // Check known forward references.
488   std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
489     FI = ForwardRefMDNodes.find(MID);
490   if (FI != ForwardRefMDNodes.end()) {
491     Result = FI->second.first;
492     return false;
493   }
494
495   // Create MDNode forward reference.
496
497   // FIXME: This is not unique enough!
498   std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
499   Value *V = MDString::get(Context, FwdRefName);
500   MDNode *FwdNode = MDNode::get(Context, &V, 1);
501   ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
502   Result = FwdNode;
503   return false;
504 }
505
506 /// ParseNamedMetadata:
507 ///   !foo = !{ !1, !2 }
508 bool LLParser::ParseNamedMetadata() {
509   assert(Lex.getKind() == lltok::NamedOrCustomMD);
510   Lex.Lex();
511   std::string Name = Lex.getStrVal();
512
513   if (ParseToken(lltok::equal, "expected '=' here") ||
514       ParseToken(lltok::Metadata, "Expected '!' here") ||
515       ParseToken(lltok::lbrace, "Expected '{' here"))
516     return true;
517
518   SmallVector<MetadataBase *, 8> Elts;
519   do {
520     if (ParseToken(lltok::Metadata, "Expected '!' here"))
521       return true;
522     
523     // FIXME: This rejects MDStrings.  Are they legal in an named MDNode or not?
524     MDNode *N = 0;
525     if (ParseMDNode(N)) return true;
526     Elts.push_back(N);
527   } while (EatIfPresent(lltok::comma));
528
529   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
530     return true;
531
532   NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
533   return false;
534 }
535
536 /// ParseStandaloneMetadata:
537 ///   !42 = !{...}
538 bool LLParser::ParseStandaloneMetadata() {
539   assert(Lex.getKind() == lltok::Metadata);
540   Lex.Lex();
541   unsigned MetadataID = 0;
542
543   LocTy TyLoc;
544   PATypeHolder Ty(Type::getVoidTy(Context));
545   SmallVector<Value *, 16> Elts;
546   // FIXME: This doesn't make sense here.  Pull braced MD stuff parsing out!
547   if (ParseUInt32(MetadataID) ||
548       ParseToken(lltok::equal, "expected '=' here") ||
549       ParseType(Ty, TyLoc) ||
550       ParseToken(lltok::Metadata, "Expected metadata here") ||
551       ParseToken(lltok::lbrace, "Expected '{' here") ||
552       ParseMDNodeVector(Elts) ||
553       ParseToken(lltok::rbrace, "expected end of metadata node"))
554     return true;
555
556   if (MetadataCache.count(MetadataID))
557     return TokError("Metadata id is already used");
558   
559   MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
560   MetadataCache[MetadataID] = Init;
561   std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
562     FI = ForwardRefMDNodes.find(MetadataID);
563   if (FI != ForwardRefMDNodes.end()) {
564     FI->second.first->replaceAllUsesWith(Init);
565     ForwardRefMDNodes.erase(FI);
566   }
567
568   return false;
569 }
570
571 /// ParseAlias:
572 ///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
573 /// Aliasee
574 ///   ::= TypeAndValue
575 ///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
576 ///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
577 ///
578 /// Everything through visibility has already been parsed.
579 ///
580 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
581                           unsigned Visibility) {
582   assert(Lex.getKind() == lltok::kw_alias);
583   Lex.Lex();
584   unsigned Linkage;
585   LocTy LinkageLoc = Lex.getLoc();
586   if (ParseOptionalLinkage(Linkage))
587     return true;
588
589   if (Linkage != GlobalValue::ExternalLinkage &&
590       Linkage != GlobalValue::WeakAnyLinkage &&
591       Linkage != GlobalValue::WeakODRLinkage &&
592       Linkage != GlobalValue::InternalLinkage &&
593       Linkage != GlobalValue::PrivateLinkage &&
594       Linkage != GlobalValue::LinkerPrivateLinkage)
595     return Error(LinkageLoc, "invalid linkage type for alias");
596
597   Constant *Aliasee;
598   LocTy AliaseeLoc = Lex.getLoc();
599   if (Lex.getKind() != lltok::kw_bitcast &&
600       Lex.getKind() != lltok::kw_getelementptr) {
601     if (ParseGlobalTypeAndValue(Aliasee)) return true;
602   } else {
603     // The bitcast dest type is not present, it is implied by the dest type.
604     ValID ID;
605     if (ParseValID(ID)) return true;
606     if (ID.Kind != ValID::t_Constant)
607       return Error(AliaseeLoc, "invalid aliasee");
608     Aliasee = ID.ConstantVal;
609   }
610
611   if (!isa<PointerType>(Aliasee->getType()))
612     return Error(AliaseeLoc, "alias must have pointer type");
613
614   // Okay, create the alias but do not insert it into the module yet.
615   GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
616                                     (GlobalValue::LinkageTypes)Linkage, Name,
617                                     Aliasee);
618   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
619
620   // See if this value already exists in the symbol table.  If so, it is either
621   // a redefinition or a definition of a forward reference.
622   if (GlobalValue *Val = M->getNamedValue(Name)) {
623     // See if this was a redefinition.  If so, there is no entry in
624     // ForwardRefVals.
625     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
626       I = ForwardRefVals.find(Name);
627     if (I == ForwardRefVals.end())
628       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
629
630     // Otherwise, this was a definition of forward ref.  Verify that types
631     // agree.
632     if (Val->getType() != GA->getType())
633       return Error(NameLoc,
634               "forward reference and definition of alias have different types");
635
636     // If they agree, just RAUW the old value with the alias and remove the
637     // forward ref info.
638     Val->replaceAllUsesWith(GA);
639     Val->eraseFromParent();
640     ForwardRefVals.erase(I);
641   }
642
643   // Insert into the module, we know its name won't collide now.
644   M->getAliasList().push_back(GA);
645   assert(GA->getNameStr() == Name && "Should not be a name conflict!");
646
647   return false;
648 }
649
650 /// ParseGlobal
651 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
652 ///       OptionalAddrSpace GlobalType Type Const
653 ///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
654 ///       OptionalAddrSpace GlobalType Type Const
655 ///
656 /// Everything through visibility has been parsed already.
657 ///
658 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
659                            unsigned Linkage, bool HasLinkage,
660                            unsigned Visibility) {
661   unsigned AddrSpace;
662   bool ThreadLocal, IsConstant;
663   LocTy TyLoc;
664
665   PATypeHolder Ty(Type::getVoidTy(Context));
666   if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
667       ParseOptionalAddrSpace(AddrSpace) ||
668       ParseGlobalType(IsConstant) ||
669       ParseType(Ty, TyLoc))
670     return true;
671
672   // If the linkage is specified and is external, then no initializer is
673   // present.
674   Constant *Init = 0;
675   if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
676                       Linkage != GlobalValue::ExternalWeakLinkage &&
677                       Linkage != GlobalValue::ExternalLinkage)) {
678     if (ParseGlobalValue(Ty, Init))
679       return true;
680   }
681
682   if (isa<FunctionType>(Ty) || Ty->isLabelTy())
683     return Error(TyLoc, "invalid type for global variable");
684
685   GlobalVariable *GV = 0;
686
687   // See if the global was forward referenced, if so, use the global.
688   if (!Name.empty()) {
689     if (GlobalValue *GVal = M->getNamedValue(Name)) {
690       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
691         return Error(NameLoc, "redefinition of global '@" + Name + "'");
692       GV = cast<GlobalVariable>(GVal);
693     }
694   } else {
695     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
696       I = ForwardRefValIDs.find(NumberedVals.size());
697     if (I != ForwardRefValIDs.end()) {
698       GV = cast<GlobalVariable>(I->second.first);
699       ForwardRefValIDs.erase(I);
700     }
701   }
702
703   if (GV == 0) {
704     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
705                             Name, 0, false, AddrSpace);
706   } else {
707     if (GV->getType()->getElementType() != Ty)
708       return Error(TyLoc,
709             "forward reference and definition of global have different types");
710
711     // Move the forward-reference to the correct spot in the module.
712     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
713   }
714
715   if (Name.empty())
716     NumberedVals.push_back(GV);
717
718   // Set the parsed properties on the global.
719   if (Init)
720     GV->setInitializer(Init);
721   GV->setConstant(IsConstant);
722   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
723   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
724   GV->setThreadLocal(ThreadLocal);
725
726   // Parse attributes on the global.
727   while (Lex.getKind() == lltok::comma) {
728     Lex.Lex();
729
730     if (Lex.getKind() == lltok::kw_section) {
731       Lex.Lex();
732       GV->setSection(Lex.getStrVal());
733       if (ParseToken(lltok::StringConstant, "expected global section string"))
734         return true;
735     } else if (Lex.getKind() == lltok::kw_align) {
736       unsigned Alignment;
737       if (ParseOptionalAlignment(Alignment)) return true;
738       GV->setAlignment(Alignment);
739     } else {
740       TokError("unknown global variable property!");
741     }
742   }
743
744   return false;
745 }
746
747
748 //===----------------------------------------------------------------------===//
749 // GlobalValue Reference/Resolution Routines.
750 //===----------------------------------------------------------------------===//
751
752 /// GetGlobalVal - Get a value with the specified name or ID, creating a
753 /// forward reference record if needed.  This can return null if the value
754 /// exists but does not have the right type.
755 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
756                                     LocTy Loc) {
757   const PointerType *PTy = dyn_cast<PointerType>(Ty);
758   if (PTy == 0) {
759     Error(Loc, "global variable reference must have pointer type");
760     return 0;
761   }
762
763   // Look this name up in the normal function symbol table.
764   GlobalValue *Val =
765     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
766
767   // If this is a forward reference for the value, see if we already created a
768   // forward ref record.
769   if (Val == 0) {
770     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
771       I = ForwardRefVals.find(Name);
772     if (I != ForwardRefVals.end())
773       Val = I->second.first;
774   }
775
776   // If we have the value in the symbol table or fwd-ref table, return it.
777   if (Val) {
778     if (Val->getType() == Ty) return Val;
779     Error(Loc, "'@" + Name + "' defined with type '" +
780           Val->getType()->getDescription() + "'");
781     return 0;
782   }
783
784   // Otherwise, create a new forward reference for this value and remember it.
785   GlobalValue *FwdVal;
786   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
787     // Function types can return opaque but functions can't.
788     if (isa<OpaqueType>(FT->getReturnType())) {
789       Error(Loc, "function may not return opaque type");
790       return 0;
791     }
792
793     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
794   } else {
795     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
796                                 GlobalValue::ExternalWeakLinkage, 0, Name);
797   }
798
799   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
800   return FwdVal;
801 }
802
803 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
804   const PointerType *PTy = dyn_cast<PointerType>(Ty);
805   if (PTy == 0) {
806     Error(Loc, "global variable reference must have pointer type");
807     return 0;
808   }
809
810   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
811
812   // If this is a forward reference for the value, see if we already created a
813   // forward ref record.
814   if (Val == 0) {
815     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
816       I = ForwardRefValIDs.find(ID);
817     if (I != ForwardRefValIDs.end())
818       Val = I->second.first;
819   }
820
821   // If we have the value in the symbol table or fwd-ref table, return it.
822   if (Val) {
823     if (Val->getType() == Ty) return Val;
824     Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
825           Val->getType()->getDescription() + "'");
826     return 0;
827   }
828
829   // Otherwise, create a new forward reference for this value and remember it.
830   GlobalValue *FwdVal;
831   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
832     // Function types can return opaque but functions can't.
833     if (isa<OpaqueType>(FT->getReturnType())) {
834       Error(Loc, "function may not return opaque type");
835       return 0;
836     }
837     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
838   } else {
839     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
840                                 GlobalValue::ExternalWeakLinkage, 0, "");
841   }
842
843   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
844   return FwdVal;
845 }
846
847
848 //===----------------------------------------------------------------------===//
849 // Helper Routines.
850 //===----------------------------------------------------------------------===//
851
852 /// ParseToken - If the current token has the specified kind, eat it and return
853 /// success.  Otherwise, emit the specified error and return failure.
854 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
855   if (Lex.getKind() != T)
856     return TokError(ErrMsg);
857   Lex.Lex();
858   return false;
859 }
860
861 /// ParseStringConstant
862 ///   ::= StringConstant
863 bool LLParser::ParseStringConstant(std::string &Result) {
864   if (Lex.getKind() != lltok::StringConstant)
865     return TokError("expected string constant");
866   Result = Lex.getStrVal();
867   Lex.Lex();
868   return false;
869 }
870
871 /// ParseUInt32
872 ///   ::= uint32
873 bool LLParser::ParseUInt32(unsigned &Val) {
874   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
875     return TokError("expected integer");
876   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
877   if (Val64 != unsigned(Val64))
878     return TokError("expected 32-bit integer (too large)");
879   Val = Val64;
880   Lex.Lex();
881   return false;
882 }
883
884
885 /// ParseOptionalAddrSpace
886 ///   := /*empty*/
887 ///   := 'addrspace' '(' uint32 ')'
888 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
889   AddrSpace = 0;
890   if (!EatIfPresent(lltok::kw_addrspace))
891     return false;
892   return ParseToken(lltok::lparen, "expected '(' in address space") ||
893          ParseUInt32(AddrSpace) ||
894          ParseToken(lltok::rparen, "expected ')' in address space");
895 }
896
897 /// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
898 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
899 /// 2: function attr.
900 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
901 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
902   Attrs = Attribute::None;
903   LocTy AttrLoc = Lex.getLoc();
904
905   while (1) {
906     switch (Lex.getKind()) {
907     case lltok::kw_sext:
908     case lltok::kw_zext:
909       // Treat these as signext/zeroext if they occur in the argument list after
910       // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
911       // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
912       // expr.
913       // FIXME: REMOVE THIS IN LLVM 3.0
914       if (AttrKind == 3) {
915         if (Lex.getKind() == lltok::kw_sext)
916           Attrs |= Attribute::SExt;
917         else
918           Attrs |= Attribute::ZExt;
919         break;
920       }
921       // FALL THROUGH.
922     default:  // End of attributes.
923       if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
924         return Error(AttrLoc, "invalid use of function-only attribute");
925
926       if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
927         return Error(AttrLoc, "invalid use of parameter-only attribute");
928
929       return false;
930     case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
931     case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
932     case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
933     case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
934     case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
935     case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
936     case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
937     case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
938
939     case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
940     case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
941     case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
942     case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
943     case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
944     case lltok::kw_inlinehint:      Attrs |= Attribute::InlineHint; break;
945     case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
946     case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
947     case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
948     case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
949     case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
950     case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
951     case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
952
953     case lltok::kw_align: {
954       unsigned Alignment;
955       if (ParseOptionalAlignment(Alignment))
956         return true;
957       Attrs |= Attribute::constructAlignmentFromInt(Alignment);
958       continue;
959     }
960     }
961     Lex.Lex();
962   }
963 }
964
965 /// ParseOptionalLinkage
966 ///   ::= /*empty*/
967 ///   ::= 'private'
968 ///   ::= 'linker_private'
969 ///   ::= 'internal'
970 ///   ::= 'weak'
971 ///   ::= 'weak_odr'
972 ///   ::= 'linkonce'
973 ///   ::= 'linkonce_odr'
974 ///   ::= 'appending'
975 ///   ::= 'dllexport'
976 ///   ::= 'common'
977 ///   ::= 'dllimport'
978 ///   ::= 'extern_weak'
979 ///   ::= 'external'
980 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
981   HasLinkage = false;
982   switch (Lex.getKind()) {
983   default:                       Res=GlobalValue::ExternalLinkage; return false;
984   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
985   case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
986   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
987   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
988   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
989   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
990   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
991   case lltok::kw_available_externally:
992     Res = GlobalValue::AvailableExternallyLinkage;
993     break;
994   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
995   case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
996   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
997   case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
998   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
999   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1000   }
1001   Lex.Lex();
1002   HasLinkage = true;
1003   return false;
1004 }
1005
1006 /// ParseOptionalVisibility
1007 ///   ::= /*empty*/
1008 ///   ::= 'default'
1009 ///   ::= 'hidden'
1010 ///   ::= 'protected'
1011 ///
1012 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1013   switch (Lex.getKind()) {
1014   default:                  Res = GlobalValue::DefaultVisibility; return false;
1015   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1016   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1017   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1018   }
1019   Lex.Lex();
1020   return false;
1021 }
1022
1023 /// ParseOptionalCallingConv
1024 ///   ::= /*empty*/
1025 ///   ::= 'ccc'
1026 ///   ::= 'fastcc'
1027 ///   ::= 'coldcc'
1028 ///   ::= 'x86_stdcallcc'
1029 ///   ::= 'x86_fastcallcc'
1030 ///   ::= 'arm_apcscc'
1031 ///   ::= 'arm_aapcscc'
1032 ///   ::= 'arm_aapcs_vfpcc'
1033 ///   ::= 'msp430_intrcc'
1034 ///   ::= 'cc' UINT
1035 ///
1036 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1037   switch (Lex.getKind()) {
1038   default:                       CC = CallingConv::C; return false;
1039   case lltok::kw_ccc:            CC = CallingConv::C; break;
1040   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1041   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1042   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1043   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1044   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1045   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1046   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1047   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1048   case lltok::kw_cc: {
1049       unsigned ArbitraryCC;
1050       Lex.Lex();
1051       if (ParseUInt32(ArbitraryCC)) {
1052         return true;
1053       } else
1054         CC = static_cast<CallingConv::ID>(ArbitraryCC);
1055         return false;
1056     }
1057     break;
1058   }
1059
1060   Lex.Lex();
1061   return false;
1062 }
1063
1064 /// ParseOptionalCustomMetadata
1065 ///   ::= /* empty */
1066 ///   ::= !dbg !42 (',' !dbg !57)*
1067 bool LLParser::ParseOptionalCustomMetadata() {
1068   if (Lex.getKind() != lltok::NamedOrCustomMD)
1069     return false;
1070
1071   while (1) {
1072     std::string Name = Lex.getStrVal();
1073     Lex.Lex();
1074
1075     if (Lex.getKind() != lltok::Metadata)
1076       return TokError("expected '!' here");
1077     Lex.Lex();
1078
1079     MDNode *Node;
1080     if (ParseMDNode(Node)) return true;
1081
1082     unsigned MDK = M->getMDKindID(Name.c_str());
1083     MDsOnInst.push_back(std::make_pair(MDK, Node));
1084
1085     // If this is the end of the list, we're done.
1086     if (!EatIfPresent(lltok::comma))
1087       return false;
1088
1089     // The next value must be a custom metadata id.
1090     if (Lex.getKind() != lltok::NamedOrCustomMD)
1091       return TokError("expected more custom metadata ids");
1092   }
1093 }
1094
1095 /// ParseOptionalAlignment
1096 ///   ::= /* empty */
1097 ///   ::= 'align' 4
1098 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1099   Alignment = 0;
1100   if (!EatIfPresent(lltok::kw_align))
1101     return false;
1102   LocTy AlignLoc = Lex.getLoc();
1103   if (ParseUInt32(Alignment)) return true;
1104   if (!isPowerOf2_32(Alignment))
1105     return Error(AlignLoc, "alignment is not a power of two");
1106   return false;
1107 }
1108
1109 /// ParseOptionalInfo
1110 ///   ::= OptionalInfo (',' OptionalInfo)+
1111 bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1112
1113   // FIXME: Handle customized metadata info attached with an instruction.
1114   do {
1115       if (Lex.getKind() == lltok::NamedOrCustomMD) {
1116       if (ParseOptionalCustomMetadata()) return true;
1117     } else if (Lex.getKind() == lltok::kw_align) {
1118       if (ParseOptionalAlignment(Alignment)) return true;
1119     } else
1120       return true;
1121   } while (EatIfPresent(lltok::comma));
1122
1123   return false;
1124 }
1125
1126
1127 /// ParseIndexList
1128 ///    ::=  (',' uint32)+
1129 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1130   if (Lex.getKind() != lltok::comma)
1131     return TokError("expected ',' as start of index list");
1132
1133   while (EatIfPresent(lltok::comma)) {
1134     if (Lex.getKind() == lltok::NamedOrCustomMD)
1135       break;
1136     unsigned Idx;
1137     if (ParseUInt32(Idx)) return true;
1138     Indices.push_back(Idx);
1139   }
1140
1141   return false;
1142 }
1143
1144 //===----------------------------------------------------------------------===//
1145 // Type Parsing.
1146 //===----------------------------------------------------------------------===//
1147
1148 /// ParseType - Parse and resolve a full type.
1149 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1150   LocTy TypeLoc = Lex.getLoc();
1151   if (ParseTypeRec(Result)) return true;
1152
1153   // Verify no unresolved uprefs.
1154   if (!UpRefs.empty())
1155     return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1156
1157   if (!AllowVoid && Result.get()->isVoidTy())
1158     return Error(TypeLoc, "void type only allowed for function results");
1159
1160   return false;
1161 }
1162
1163 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1164 /// called.  It loops through the UpRefs vector, which is a list of the
1165 /// currently active types.  For each type, if the up-reference is contained in
1166 /// the newly completed type, we decrement the level count.  When the level
1167 /// count reaches zero, the up-referenced type is the type that is passed in:
1168 /// thus we can complete the cycle.
1169 ///
1170 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1171   // If Ty isn't abstract, or if there are no up-references in it, then there is
1172   // nothing to resolve here.
1173   if (!ty->isAbstract() || UpRefs.empty()) return ty;
1174
1175   PATypeHolder Ty(ty);
1176 #if 0
1177   dbgs() << "Type '" << Ty->getDescription()
1178          << "' newly formed.  Resolving upreferences.\n"
1179          << UpRefs.size() << " upreferences active!\n";
1180 #endif
1181
1182   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1183   // to zero), we resolve them all together before we resolve them to Ty.  At
1184   // the end of the loop, if there is anything to resolve to Ty, it will be in
1185   // this variable.
1186   OpaqueType *TypeToResolve = 0;
1187
1188   for (unsigned i = 0; i != UpRefs.size(); ++i) {
1189     // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1190     bool ContainsType =
1191       std::find(Ty->subtype_begin(), Ty->subtype_end(),
1192                 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1193
1194 #if 0
1195     dbgs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1196            << UpRefs[i].LastContainedTy->getDescription() << ") = "
1197            << (ContainsType ? "true" : "false")
1198            << " level=" << UpRefs[i].NestingLevel << "\n";
1199 #endif
1200     if (!ContainsType)
1201       continue;
1202
1203     // Decrement level of upreference
1204     unsigned Level = --UpRefs[i].NestingLevel;
1205     UpRefs[i].LastContainedTy = Ty;
1206
1207     // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1208     if (Level != 0)
1209       continue;
1210
1211 #if 0
1212     dbgs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1213 #endif
1214     if (!TypeToResolve)
1215       TypeToResolve = UpRefs[i].UpRefTy;
1216     else
1217       UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1218     UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1219     --i;                                // Do not skip the next element.
1220   }
1221
1222   if (TypeToResolve)
1223     TypeToResolve->refineAbstractTypeTo(Ty);
1224
1225   return Ty;
1226 }
1227
1228
1229 /// ParseTypeRec - The recursive function used to process the internal
1230 /// implementation details of types.
1231 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1232   switch (Lex.getKind()) {
1233   default:
1234     return TokError("expected type");
1235   case lltok::Type:
1236     // TypeRec ::= 'float' | 'void' (etc)
1237     Result = Lex.getTyVal();
1238     Lex.Lex();
1239     break;
1240   case lltok::kw_opaque:
1241     // TypeRec ::= 'opaque'
1242     Result = OpaqueType::get(Context);
1243     Lex.Lex();
1244     break;
1245   case lltok::lbrace:
1246     // TypeRec ::= '{' ... '}'
1247     if (ParseStructType(Result, false))
1248       return true;
1249     break;
1250   case lltok::lsquare:
1251     // TypeRec ::= '[' ... ']'
1252     Lex.Lex(); // eat the lsquare.
1253     if (ParseArrayVectorType(Result, false))
1254       return true;
1255     break;
1256   case lltok::less: // Either vector or packed struct.
1257     // TypeRec ::= '<' ... '>'
1258     Lex.Lex();
1259     if (Lex.getKind() == lltok::lbrace) {
1260       if (ParseStructType(Result, true) ||
1261           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1262         return true;
1263     } else if (ParseArrayVectorType(Result, true))
1264       return true;
1265     break;
1266   case lltok::LocalVar:
1267   case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1268     // TypeRec ::= %foo
1269     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1270       Result = T;
1271     } else {
1272       Result = OpaqueType::get(Context);
1273       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1274                                             std::make_pair(Result,
1275                                                            Lex.getLoc())));
1276       M->addTypeName(Lex.getStrVal(), Result.get());
1277     }
1278     Lex.Lex();
1279     break;
1280
1281   case lltok::LocalVarID:
1282     // TypeRec ::= %4
1283     if (Lex.getUIntVal() < NumberedTypes.size())
1284       Result = NumberedTypes[Lex.getUIntVal()];
1285     else {
1286       std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1287         I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1288       if (I != ForwardRefTypeIDs.end())
1289         Result = I->second.first;
1290       else {
1291         Result = OpaqueType::get(Context);
1292         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1293                                                 std::make_pair(Result,
1294                                                                Lex.getLoc())));
1295       }
1296     }
1297     Lex.Lex();
1298     break;
1299   case lltok::backslash: {
1300     // TypeRec ::= '\' 4
1301     Lex.Lex();
1302     unsigned Val;
1303     if (ParseUInt32(Val)) return true;
1304     OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1305     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1306     Result = OT;
1307     break;
1308   }
1309   }
1310
1311   // Parse the type suffixes.
1312   while (1) {
1313     switch (Lex.getKind()) {
1314     // End of type.
1315     default: return false;
1316
1317     // TypeRec ::= TypeRec '*'
1318     case lltok::star:
1319       if (Result.get()->isLabelTy())
1320         return TokError("basic block pointers are invalid");
1321       if (Result.get()->isVoidTy())
1322         return TokError("pointers to void are invalid; use i8* instead");
1323       if (!PointerType::isValidElementType(Result.get()))
1324         return TokError("pointer to this type is invalid");
1325       Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1326       Lex.Lex();
1327       break;
1328
1329     // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1330     case lltok::kw_addrspace: {
1331       if (Result.get()->isLabelTy())
1332         return TokError("basic block pointers are invalid");
1333       if (Result.get()->isVoidTy())
1334         return TokError("pointers to void are invalid; use i8* instead");
1335       if (!PointerType::isValidElementType(Result.get()))
1336         return TokError("pointer to this type is invalid");
1337       unsigned AddrSpace;
1338       if (ParseOptionalAddrSpace(AddrSpace) ||
1339           ParseToken(lltok::star, "expected '*' in address space"))
1340         return true;
1341
1342       Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1343       break;
1344     }
1345
1346     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1347     case lltok::lparen:
1348       if (ParseFunctionType(Result))
1349         return true;
1350       break;
1351     }
1352   }
1353 }
1354
1355 /// ParseParameterList
1356 ///    ::= '(' ')'
1357 ///    ::= '(' Arg (',' Arg)* ')'
1358 ///  Arg
1359 ///    ::= Type OptionalAttributes Value OptionalAttributes
1360 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1361                                   PerFunctionState &PFS) {
1362   if (ParseToken(lltok::lparen, "expected '(' in call"))
1363     return true;
1364
1365   while (Lex.getKind() != lltok::rparen) {
1366     // If this isn't the first argument, we need a comma.
1367     if (!ArgList.empty() &&
1368         ParseToken(lltok::comma, "expected ',' in argument list"))
1369       return true;
1370
1371     // Parse the argument.
1372     LocTy ArgLoc;
1373     PATypeHolder ArgTy(Type::getVoidTy(Context));
1374     unsigned ArgAttrs1 = Attribute::None;
1375     unsigned ArgAttrs2 = Attribute::None;
1376     Value *V;
1377     if (ParseType(ArgTy, ArgLoc))
1378       return true;
1379
1380     // Otherwise, handle normal operands.
1381     if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1382         ParseValue(ArgTy, V, PFS) ||
1383         // FIXME: Should not allow attributes after the argument, remove this
1384         // in LLVM 3.0.
1385         ParseOptionalAttrs(ArgAttrs2, 3))
1386       return true;
1387     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1388   }
1389
1390   Lex.Lex();  // Lex the ')'.
1391   return false;
1392 }
1393
1394
1395
1396 /// ParseArgumentList - Parse the argument list for a function type or function
1397 /// prototype.  If 'inType' is true then we are parsing a FunctionType.
1398 ///   ::= '(' ArgTypeListI ')'
1399 /// ArgTypeListI
1400 ///   ::= /*empty*/
1401 ///   ::= '...'
1402 ///   ::= ArgTypeList ',' '...'
1403 ///   ::= ArgType (',' ArgType)*
1404 ///
1405 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1406                                  bool &isVarArg, bool inType) {
1407   isVarArg = false;
1408   assert(Lex.getKind() == lltok::lparen);
1409   Lex.Lex(); // eat the (.
1410
1411   if (Lex.getKind() == lltok::rparen) {
1412     // empty
1413   } else if (Lex.getKind() == lltok::dotdotdot) {
1414     isVarArg = true;
1415     Lex.Lex();
1416   } else {
1417     LocTy TypeLoc = Lex.getLoc();
1418     PATypeHolder ArgTy(Type::getVoidTy(Context));
1419     unsigned Attrs;
1420     std::string Name;
1421
1422     // If we're parsing a type, use ParseTypeRec, because we allow recursive
1423     // types (such as a function returning a pointer to itself).  If parsing a
1424     // function prototype, we require fully resolved types.
1425     if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1426         ParseOptionalAttrs(Attrs, 0)) return true;
1427
1428     if (ArgTy->isVoidTy())
1429       return Error(TypeLoc, "argument can not have void type");
1430
1431     if (Lex.getKind() == lltok::LocalVar ||
1432         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1433       Name = Lex.getStrVal();
1434       Lex.Lex();
1435     }
1436
1437     if (!FunctionType::isValidArgumentType(ArgTy))
1438       return Error(TypeLoc, "invalid type for function argument");
1439
1440     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1441
1442     while (EatIfPresent(lltok::comma)) {
1443       // Handle ... at end of arg list.
1444       if (EatIfPresent(lltok::dotdotdot)) {
1445         isVarArg = true;
1446         break;
1447       }
1448
1449       // Otherwise must be an argument type.
1450       TypeLoc = Lex.getLoc();
1451       if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1452           ParseOptionalAttrs(Attrs, 0)) return true;
1453
1454       if (ArgTy->isVoidTy())
1455         return Error(TypeLoc, "argument can not have void type");
1456
1457       if (Lex.getKind() == lltok::LocalVar ||
1458           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1459         Name = Lex.getStrVal();
1460         Lex.Lex();
1461       } else {
1462         Name = "";
1463       }
1464
1465       if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1466         return Error(TypeLoc, "invalid type for function argument");
1467
1468       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1469     }
1470   }
1471
1472   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1473 }
1474
1475 /// ParseFunctionType
1476 ///  ::= Type ArgumentList OptionalAttrs
1477 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1478   assert(Lex.getKind() == lltok::lparen);
1479
1480   if (!FunctionType::isValidReturnType(Result))
1481     return TokError("invalid function return type");
1482
1483   std::vector<ArgInfo> ArgList;
1484   bool isVarArg;
1485   unsigned Attrs;
1486   if (ParseArgumentList(ArgList, isVarArg, true) ||
1487       // FIXME: Allow, but ignore attributes on function types!
1488       // FIXME: Remove in LLVM 3.0
1489       ParseOptionalAttrs(Attrs, 2))
1490     return true;
1491
1492   // Reject names on the arguments lists.
1493   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1494     if (!ArgList[i].Name.empty())
1495       return Error(ArgList[i].Loc, "argument name invalid in function type");
1496     if (!ArgList[i].Attrs != 0) {
1497       // Allow but ignore attributes on function types; this permits
1498       // auto-upgrade.
1499       // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1500     }
1501   }
1502
1503   std::vector<const Type*> ArgListTy;
1504   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1505     ArgListTy.push_back(ArgList[i].Type);
1506
1507   Result = HandleUpRefs(FunctionType::get(Result.get(),
1508                                                 ArgListTy, isVarArg));
1509   return false;
1510 }
1511
1512 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1513 ///   TypeRec
1514 ///     ::= '{' '}'
1515 ///     ::= '{' TypeRec (',' TypeRec)* '}'
1516 ///     ::= '<' '{' '}' '>'
1517 ///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1518 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1519   assert(Lex.getKind() == lltok::lbrace);
1520   Lex.Lex(); // Consume the '{'
1521
1522   if (EatIfPresent(lltok::rbrace)) {
1523     Result = StructType::get(Context, Packed);
1524     return false;
1525   }
1526
1527   std::vector<PATypeHolder> ParamsList;
1528   LocTy EltTyLoc = Lex.getLoc();
1529   if (ParseTypeRec(Result)) return true;
1530   ParamsList.push_back(Result);
1531
1532   if (Result->isVoidTy())
1533     return Error(EltTyLoc, "struct element can not have void type");
1534   if (!StructType::isValidElementType(Result))
1535     return Error(EltTyLoc, "invalid element type for struct");
1536
1537   while (EatIfPresent(lltok::comma)) {
1538     EltTyLoc = Lex.getLoc();
1539     if (ParseTypeRec(Result)) return true;
1540
1541     if (Result->isVoidTy())
1542       return Error(EltTyLoc, "struct element can not have void type");
1543     if (!StructType::isValidElementType(Result))
1544       return Error(EltTyLoc, "invalid element type for struct");
1545
1546     ParamsList.push_back(Result);
1547   }
1548
1549   if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1550     return true;
1551
1552   std::vector<const Type*> ParamsListTy;
1553   for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1554     ParamsListTy.push_back(ParamsList[i].get());
1555   Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1556   return false;
1557 }
1558
1559 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1560 /// token has already been consumed.
1561 ///   TypeRec
1562 ///     ::= '[' APSINTVAL 'x' Types ']'
1563 ///     ::= '<' APSINTVAL 'x' Types '>'
1564 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1565   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1566       Lex.getAPSIntVal().getBitWidth() > 64)
1567     return TokError("expected number in address space");
1568
1569   LocTy SizeLoc = Lex.getLoc();
1570   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1571   Lex.Lex();
1572
1573   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1574       return true;
1575
1576   LocTy TypeLoc = Lex.getLoc();
1577   PATypeHolder EltTy(Type::getVoidTy(Context));
1578   if (ParseTypeRec(EltTy)) return true;
1579
1580   if (EltTy->isVoidTy())
1581     return Error(TypeLoc, "array and vector element type cannot be void");
1582
1583   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1584                  "expected end of sequential type"))
1585     return true;
1586
1587   if (isVector) {
1588     if (Size == 0)
1589       return Error(SizeLoc, "zero element vector is illegal");
1590     if ((unsigned)Size != Size)
1591       return Error(SizeLoc, "size too large for vector");
1592     if (!VectorType::isValidElementType(EltTy))
1593       return Error(TypeLoc, "vector element type must be fp or integer");
1594     Result = VectorType::get(EltTy, unsigned(Size));
1595   } else {
1596     if (!ArrayType::isValidElementType(EltTy))
1597       return Error(TypeLoc, "invalid array element type");
1598     Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1599   }
1600   return false;
1601 }
1602
1603 //===----------------------------------------------------------------------===//
1604 // Function Semantic Analysis.
1605 //===----------------------------------------------------------------------===//
1606
1607 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1608                                              int functionNumber)
1609   : P(p), F(f), FunctionNumber(functionNumber) {
1610
1611   // Insert unnamed arguments into the NumberedVals list.
1612   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1613        AI != E; ++AI)
1614     if (!AI->hasName())
1615       NumberedVals.push_back(AI);
1616 }
1617
1618 LLParser::PerFunctionState::~PerFunctionState() {
1619   // If there were any forward referenced non-basicblock values, delete them.
1620   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1621        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1622     if (!isa<BasicBlock>(I->second.first)) {
1623       I->second.first->replaceAllUsesWith(
1624                            UndefValue::get(I->second.first->getType()));
1625       delete I->second.first;
1626       I->second.first = 0;
1627     }
1628
1629   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1630        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1631     if (!isa<BasicBlock>(I->second.first)) {
1632       I->second.first->replaceAllUsesWith(
1633                            UndefValue::get(I->second.first->getType()));
1634       delete I->second.first;
1635       I->second.first = 0;
1636     }
1637 }
1638
1639 bool LLParser::PerFunctionState::FinishFunction() {
1640   // Check to see if someone took the address of labels in this block.
1641   if (!P.ForwardRefBlockAddresses.empty()) {
1642     ValID FunctionID;
1643     if (!F.getName().empty()) {
1644       FunctionID.Kind = ValID::t_GlobalName;
1645       FunctionID.StrVal = F.getName();
1646     } else {
1647       FunctionID.Kind = ValID::t_GlobalID;
1648       FunctionID.UIntVal = FunctionNumber;
1649     }
1650   
1651     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1652       FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1653     if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1654       // Resolve all these references.
1655       if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1656         return true;
1657       
1658       P.ForwardRefBlockAddresses.erase(FRBAI);
1659     }
1660   }
1661   
1662   if (!ForwardRefVals.empty())
1663     return P.Error(ForwardRefVals.begin()->second.second,
1664                    "use of undefined value '%" + ForwardRefVals.begin()->first +
1665                    "'");
1666   if (!ForwardRefValIDs.empty())
1667     return P.Error(ForwardRefValIDs.begin()->second.second,
1668                    "use of undefined value '%" +
1669                    utostr(ForwardRefValIDs.begin()->first) + "'");
1670   return false;
1671 }
1672
1673
1674 /// GetVal - Get a value with the specified name or ID, creating a
1675 /// forward reference record if needed.  This can return null if the value
1676 /// exists but does not have the right type.
1677 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1678                                           const Type *Ty, LocTy Loc) {
1679   // Look this name up in the normal function symbol table.
1680   Value *Val = F.getValueSymbolTable().lookup(Name);
1681
1682   // If this is a forward reference for the value, see if we already created a
1683   // forward ref record.
1684   if (Val == 0) {
1685     std::map<std::string, std::pair<Value*, LocTy> >::iterator
1686       I = ForwardRefVals.find(Name);
1687     if (I != ForwardRefVals.end())
1688       Val = I->second.first;
1689   }
1690
1691   // If we have the value in the symbol table or fwd-ref table, return it.
1692   if (Val) {
1693     if (Val->getType() == Ty) return Val;
1694     if (Ty->isLabelTy())
1695       P.Error(Loc, "'%" + Name + "' is not a basic block");
1696     else
1697       P.Error(Loc, "'%" + Name + "' defined with type '" +
1698               Val->getType()->getDescription() + "'");
1699     return 0;
1700   }
1701
1702   // Don't make placeholders with invalid type.
1703   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1704       Ty != Type::getLabelTy(F.getContext())) {
1705     P.Error(Loc, "invalid use of a non-first-class type");
1706     return 0;
1707   }
1708
1709   // Otherwise, create a new forward reference for this value and remember it.
1710   Value *FwdVal;
1711   if (Ty->isLabelTy())
1712     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1713   else
1714     FwdVal = new Argument(Ty, Name);
1715
1716   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1717   return FwdVal;
1718 }
1719
1720 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1721                                           LocTy Loc) {
1722   // Look this name up in the normal function symbol table.
1723   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1724
1725   // If this is a forward reference for the value, see if we already created a
1726   // forward ref record.
1727   if (Val == 0) {
1728     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1729       I = ForwardRefValIDs.find(ID);
1730     if (I != ForwardRefValIDs.end())
1731       Val = I->second.first;
1732   }
1733
1734   // If we have the value in the symbol table or fwd-ref table, return it.
1735   if (Val) {
1736     if (Val->getType() == Ty) return Val;
1737     if (Ty->isLabelTy())
1738       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1739     else
1740       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1741               Val->getType()->getDescription() + "'");
1742     return 0;
1743   }
1744
1745   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1746       Ty != Type::getLabelTy(F.getContext())) {
1747     P.Error(Loc, "invalid use of a non-first-class type");
1748     return 0;
1749   }
1750
1751   // Otherwise, create a new forward reference for this value and remember it.
1752   Value *FwdVal;
1753   if (Ty->isLabelTy())
1754     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1755   else
1756     FwdVal = new Argument(Ty);
1757
1758   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1759   return FwdVal;
1760 }
1761
1762 /// SetInstName - After an instruction is parsed and inserted into its
1763 /// basic block, this installs its name.
1764 bool LLParser::PerFunctionState::SetInstName(int NameID,
1765                                              const std::string &NameStr,
1766                                              LocTy NameLoc, Instruction *Inst) {
1767   // If this instruction has void type, it cannot have a name or ID specified.
1768   if (Inst->getType()->isVoidTy()) {
1769     if (NameID != -1 || !NameStr.empty())
1770       return P.Error(NameLoc, "instructions returning void cannot have a name");
1771     return false;
1772   }
1773
1774   // If this was a numbered instruction, verify that the instruction is the
1775   // expected value and resolve any forward references.
1776   if (NameStr.empty()) {
1777     // If neither a name nor an ID was specified, just use the next ID.
1778     if (NameID == -1)
1779       NameID = NumberedVals.size();
1780
1781     if (unsigned(NameID) != NumberedVals.size())
1782       return P.Error(NameLoc, "instruction expected to be numbered '%" +
1783                      utostr(NumberedVals.size()) + "'");
1784
1785     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1786       ForwardRefValIDs.find(NameID);
1787     if (FI != ForwardRefValIDs.end()) {
1788       if (FI->second.first->getType() != Inst->getType())
1789         return P.Error(NameLoc, "instruction forward referenced with type '" +
1790                        FI->second.first->getType()->getDescription() + "'");
1791       FI->second.first->replaceAllUsesWith(Inst);
1792       delete FI->second.first;
1793       ForwardRefValIDs.erase(FI);
1794     }
1795
1796     NumberedVals.push_back(Inst);
1797     return false;
1798   }
1799
1800   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1801   std::map<std::string, std::pair<Value*, LocTy> >::iterator
1802     FI = ForwardRefVals.find(NameStr);
1803   if (FI != ForwardRefVals.end()) {
1804     if (FI->second.first->getType() != Inst->getType())
1805       return P.Error(NameLoc, "instruction forward referenced with type '" +
1806                      FI->second.first->getType()->getDescription() + "'");
1807     FI->second.first->replaceAllUsesWith(Inst);
1808     delete FI->second.first;
1809     ForwardRefVals.erase(FI);
1810   }
1811
1812   // Set the name on the instruction.
1813   Inst->setName(NameStr);
1814
1815   if (Inst->getNameStr() != NameStr)
1816     return P.Error(NameLoc, "multiple definition of local value named '" +
1817                    NameStr + "'");
1818   return false;
1819 }
1820
1821 /// GetBB - Get a basic block with the specified name or ID, creating a
1822 /// forward reference record if needed.
1823 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1824                                               LocTy Loc) {
1825   return cast_or_null<BasicBlock>(GetVal(Name,
1826                                         Type::getLabelTy(F.getContext()), Loc));
1827 }
1828
1829 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1830   return cast_or_null<BasicBlock>(GetVal(ID,
1831                                         Type::getLabelTy(F.getContext()), Loc));
1832 }
1833
1834 /// DefineBB - Define the specified basic block, which is either named or
1835 /// unnamed.  If there is an error, this returns null otherwise it returns
1836 /// the block being defined.
1837 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1838                                                  LocTy Loc) {
1839   BasicBlock *BB;
1840   if (Name.empty())
1841     BB = GetBB(NumberedVals.size(), Loc);
1842   else
1843     BB = GetBB(Name, Loc);
1844   if (BB == 0) return 0; // Already diagnosed error.
1845
1846   // Move the block to the end of the function.  Forward ref'd blocks are
1847   // inserted wherever they happen to be referenced.
1848   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1849
1850   // Remove the block from forward ref sets.
1851   if (Name.empty()) {
1852     ForwardRefValIDs.erase(NumberedVals.size());
1853     NumberedVals.push_back(BB);
1854   } else {
1855     // BB forward references are already in the function symbol table.
1856     ForwardRefVals.erase(Name);
1857   }
1858
1859   return BB;
1860 }
1861
1862 //===----------------------------------------------------------------------===//
1863 // Constants.
1864 //===----------------------------------------------------------------------===//
1865
1866 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1867 /// type implied.  For example, if we parse "4" we don't know what integer type
1868 /// it has.  The value will later be combined with its type and checked for
1869 /// sanity.
1870 bool LLParser::ParseValID(ValID &ID) {
1871   ID.Loc = Lex.getLoc();
1872   switch (Lex.getKind()) {
1873   default: return TokError("expected value token");
1874   case lltok::GlobalID:  // @42
1875     ID.UIntVal = Lex.getUIntVal();
1876     ID.Kind = ValID::t_GlobalID;
1877     break;
1878   case lltok::GlobalVar:  // @foo
1879     ID.StrVal = Lex.getStrVal();
1880     ID.Kind = ValID::t_GlobalName;
1881     break;
1882   case lltok::LocalVarID:  // %42
1883     ID.UIntVal = Lex.getUIntVal();
1884     ID.Kind = ValID::t_LocalID;
1885     break;
1886   case lltok::LocalVar:  // %foo
1887   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1888     ID.StrVal = Lex.getStrVal();
1889     ID.Kind = ValID::t_LocalName;
1890     break;
1891   case lltok::Metadata:   // !{...} MDNode, !"foo" MDString
1892     Lex.Lex();
1893     
1894     // FIXME: This doesn't belong here.
1895     if (EatIfPresent(lltok::lbrace)) {
1896       SmallVector<Value*, 16> Elts;
1897       if (ParseMDNodeVector(Elts) ||
1898           ParseToken(lltok::rbrace, "expected end of metadata node"))
1899         return true;
1900
1901       ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
1902       ID.Kind = ValID::t_MDNode;
1903       return false;
1904     }
1905
1906     // Standalone metadata reference
1907     // !{ ..., !42, ... }
1908     if (Lex.getKind() == lltok::APSInt) {
1909       if (ParseMDNode(ID.MDNodeVal)) return true;
1910       ID.Kind = ValID::t_MDNode;
1911       return false;
1912     }
1913     
1914     // MDString:
1915     //   ::= '!' STRINGCONSTANT
1916     if (ParseMDString(ID.MDStringVal)) return true;
1917     ID.Kind = ValID::t_MDString;
1918     return false;
1919   case lltok::APSInt:
1920     ID.APSIntVal = Lex.getAPSIntVal();
1921     ID.Kind = ValID::t_APSInt;
1922     break;
1923   case lltok::APFloat:
1924     ID.APFloatVal = Lex.getAPFloatVal();
1925     ID.Kind = ValID::t_APFloat;
1926     break;
1927   case lltok::kw_true:
1928     ID.ConstantVal = ConstantInt::getTrue(Context);
1929     ID.Kind = ValID::t_Constant;
1930     break;
1931   case lltok::kw_false:
1932     ID.ConstantVal = ConstantInt::getFalse(Context);
1933     ID.Kind = ValID::t_Constant;
1934     break;
1935   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1936   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1937   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1938
1939   case lltok::lbrace: {
1940     // ValID ::= '{' ConstVector '}'
1941     Lex.Lex();
1942     SmallVector<Constant*, 16> Elts;
1943     if (ParseGlobalValueVector(Elts) ||
1944         ParseToken(lltok::rbrace, "expected end of struct constant"))
1945       return true;
1946
1947     ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1948                                          Elts.size(), false);
1949     ID.Kind = ValID::t_Constant;
1950     return false;
1951   }
1952   case lltok::less: {
1953     // ValID ::= '<' ConstVector '>'         --> Vector.
1954     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1955     Lex.Lex();
1956     bool isPackedStruct = EatIfPresent(lltok::lbrace);
1957
1958     SmallVector<Constant*, 16> Elts;
1959     LocTy FirstEltLoc = Lex.getLoc();
1960     if (ParseGlobalValueVector(Elts) ||
1961         (isPackedStruct &&
1962          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1963         ParseToken(lltok::greater, "expected end of constant"))
1964       return true;
1965
1966     if (isPackedStruct) {
1967       ID.ConstantVal =
1968         ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1969       ID.Kind = ValID::t_Constant;
1970       return false;
1971     }
1972
1973     if (Elts.empty())
1974       return Error(ID.Loc, "constant vector must not be empty");
1975
1976     if (!Elts[0]->getType()->isInteger() &&
1977         !Elts[0]->getType()->isFloatingPoint())
1978       return Error(FirstEltLoc,
1979                    "vector elements must have integer or floating point type");
1980
1981     // Verify that all the vector elements have the same type.
1982     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1983       if (Elts[i]->getType() != Elts[0]->getType())
1984         return Error(FirstEltLoc,
1985                      "vector element #" + utostr(i) +
1986                     " is not of type '" + Elts[0]->getType()->getDescription());
1987
1988     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1989     ID.Kind = ValID::t_Constant;
1990     return false;
1991   }
1992   case lltok::lsquare: {   // Array Constant
1993     Lex.Lex();
1994     SmallVector<Constant*, 16> Elts;
1995     LocTy FirstEltLoc = Lex.getLoc();
1996     if (ParseGlobalValueVector(Elts) ||
1997         ParseToken(lltok::rsquare, "expected end of array constant"))
1998       return true;
1999
2000     // Handle empty element.
2001     if (Elts.empty()) {
2002       // Use undef instead of an array because it's inconvenient to determine
2003       // the element type at this point, there being no elements to examine.
2004       ID.Kind = ValID::t_EmptyArray;
2005       return false;
2006     }
2007
2008     if (!Elts[0]->getType()->isFirstClassType())
2009       return Error(FirstEltLoc, "invalid array element type: " +
2010                    Elts[0]->getType()->getDescription());
2011
2012     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2013
2014     // Verify all elements are correct type!
2015     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2016       if (Elts[i]->getType() != Elts[0]->getType())
2017         return Error(FirstEltLoc,
2018                      "array element #" + utostr(i) +
2019                      " is not of type '" +Elts[0]->getType()->getDescription());
2020     }
2021
2022     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2023     ID.Kind = ValID::t_Constant;
2024     return false;
2025   }
2026   case lltok::kw_c:  // c "foo"
2027     Lex.Lex();
2028     ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2029     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2030     ID.Kind = ValID::t_Constant;
2031     return false;
2032
2033   case lltok::kw_asm: {
2034     // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2035     bool HasSideEffect, AlignStack;
2036     Lex.Lex();
2037     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2038         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2039         ParseStringConstant(ID.StrVal) ||
2040         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2041         ParseToken(lltok::StringConstant, "expected constraint string"))
2042       return true;
2043     ID.StrVal2 = Lex.getStrVal();
2044     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2045     ID.Kind = ValID::t_InlineAsm;
2046     return false;
2047   }
2048
2049   case lltok::kw_blockaddress: {
2050     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2051     Lex.Lex();
2052
2053     ValID Fn, Label;
2054     LocTy FnLoc, LabelLoc;
2055     
2056     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2057         ParseValID(Fn) ||
2058         ParseToken(lltok::comma, "expected comma in block address expression")||
2059         ParseValID(Label) ||
2060         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2061       return true;
2062     
2063     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2064       return Error(Fn.Loc, "expected function name in blockaddress");
2065     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2066       return Error(Label.Loc, "expected basic block name in blockaddress");
2067     
2068     // Make a global variable as a placeholder for this reference.
2069     GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2070                                            false, GlobalValue::InternalLinkage,
2071                                                 0, "");
2072     ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2073     ID.ConstantVal = FwdRef;
2074     ID.Kind = ValID::t_Constant;
2075     return false;
2076   }
2077       
2078   case lltok::kw_trunc:
2079   case lltok::kw_zext:
2080   case lltok::kw_sext:
2081   case lltok::kw_fptrunc:
2082   case lltok::kw_fpext:
2083   case lltok::kw_bitcast:
2084   case lltok::kw_uitofp:
2085   case lltok::kw_sitofp:
2086   case lltok::kw_fptoui:
2087   case lltok::kw_fptosi:
2088   case lltok::kw_inttoptr:
2089   case lltok::kw_ptrtoint: {
2090     unsigned Opc = Lex.getUIntVal();
2091     PATypeHolder DestTy(Type::getVoidTy(Context));
2092     Constant *SrcVal;
2093     Lex.Lex();
2094     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2095         ParseGlobalTypeAndValue(SrcVal) ||
2096         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2097         ParseType(DestTy) ||
2098         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2099       return true;
2100     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2101       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2102                    SrcVal->getType()->getDescription() + "' to '" +
2103                    DestTy->getDescription() + "'");
2104     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2105                                                  SrcVal, DestTy);
2106     ID.Kind = ValID::t_Constant;
2107     return false;
2108   }
2109   case lltok::kw_extractvalue: {
2110     Lex.Lex();
2111     Constant *Val;
2112     SmallVector<unsigned, 4> Indices;
2113     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2114         ParseGlobalTypeAndValue(Val) ||
2115         ParseIndexList(Indices) ||
2116         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2117       return true;
2118     if (Lex.getKind() == lltok::NamedOrCustomMD)
2119       if (ParseOptionalCustomMetadata()) return true;
2120
2121     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2122       return Error(ID.Loc, "extractvalue operand must be array or struct");
2123     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2124                                           Indices.end()))
2125       return Error(ID.Loc, "invalid indices for extractvalue");
2126     ID.ConstantVal =
2127       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2128     ID.Kind = ValID::t_Constant;
2129     return false;
2130   }
2131   case lltok::kw_insertvalue: {
2132     Lex.Lex();
2133     Constant *Val0, *Val1;
2134     SmallVector<unsigned, 4> Indices;
2135     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2136         ParseGlobalTypeAndValue(Val0) ||
2137         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2138         ParseGlobalTypeAndValue(Val1) ||
2139         ParseIndexList(Indices) ||
2140         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2141       return true;
2142     if (Lex.getKind() == lltok::NamedOrCustomMD)
2143       if (ParseOptionalCustomMetadata()) return true;
2144     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2145       return Error(ID.Loc, "extractvalue operand must be array or struct");
2146     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2147                                           Indices.end()))
2148       return Error(ID.Loc, "invalid indices for insertvalue");
2149     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2150                        Indices.data(), Indices.size());
2151     ID.Kind = ValID::t_Constant;
2152     return false;
2153   }
2154   case lltok::kw_icmp:
2155   case lltok::kw_fcmp: {
2156     unsigned PredVal, Opc = Lex.getUIntVal();
2157     Constant *Val0, *Val1;
2158     Lex.Lex();
2159     if (ParseCmpPredicate(PredVal, Opc) ||
2160         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2161         ParseGlobalTypeAndValue(Val0) ||
2162         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2163         ParseGlobalTypeAndValue(Val1) ||
2164         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2165       return true;
2166
2167     if (Val0->getType() != Val1->getType())
2168       return Error(ID.Loc, "compare operands must have the same type");
2169
2170     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2171
2172     if (Opc == Instruction::FCmp) {
2173       if (!Val0->getType()->isFPOrFPVector())
2174         return Error(ID.Loc, "fcmp requires floating point operands");
2175       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2176     } else {
2177       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2178       if (!Val0->getType()->isIntOrIntVector() &&
2179           !isa<PointerType>(Val0->getType()))
2180         return Error(ID.Loc, "icmp requires pointer or integer operands");
2181       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2182     }
2183     ID.Kind = ValID::t_Constant;
2184     return false;
2185   }
2186
2187   // Binary Operators.
2188   case lltok::kw_add:
2189   case lltok::kw_fadd:
2190   case lltok::kw_sub:
2191   case lltok::kw_fsub:
2192   case lltok::kw_mul:
2193   case lltok::kw_fmul:
2194   case lltok::kw_udiv:
2195   case lltok::kw_sdiv:
2196   case lltok::kw_fdiv:
2197   case lltok::kw_urem:
2198   case lltok::kw_srem:
2199   case lltok::kw_frem: {
2200     bool NUW = false;
2201     bool NSW = false;
2202     bool Exact = false;
2203     unsigned Opc = Lex.getUIntVal();
2204     Constant *Val0, *Val1;
2205     Lex.Lex();
2206     LocTy ModifierLoc = Lex.getLoc();
2207     if (Opc == Instruction::Add ||
2208         Opc == Instruction::Sub ||
2209         Opc == Instruction::Mul) {
2210       if (EatIfPresent(lltok::kw_nuw))
2211         NUW = true;
2212       if (EatIfPresent(lltok::kw_nsw)) {
2213         NSW = true;
2214         if (EatIfPresent(lltok::kw_nuw))
2215           NUW = true;
2216       }
2217     } else if (Opc == Instruction::SDiv) {
2218       if (EatIfPresent(lltok::kw_exact))
2219         Exact = true;
2220     }
2221     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2222         ParseGlobalTypeAndValue(Val0) ||
2223         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2224         ParseGlobalTypeAndValue(Val1) ||
2225         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2226       return true;
2227     if (Val0->getType() != Val1->getType())
2228       return Error(ID.Loc, "operands of constexpr must have same type");
2229     if (!Val0->getType()->isIntOrIntVector()) {
2230       if (NUW)
2231         return Error(ModifierLoc, "nuw only applies to integer operations");
2232       if (NSW)
2233         return Error(ModifierLoc, "nsw only applies to integer operations");
2234     }
2235     // API compatibility: Accept either integer or floating-point types with
2236     // add, sub, and mul.
2237     if (!Val0->getType()->isIntOrIntVector() &&
2238         !Val0->getType()->isFPOrFPVector())
2239       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2240     unsigned Flags = 0;
2241     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2242     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2243     if (Exact) Flags |= SDivOperator::IsExact;
2244     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2245     ID.ConstantVal = C;
2246     ID.Kind = ValID::t_Constant;
2247     return false;
2248   }
2249
2250   // Logical Operations
2251   case lltok::kw_shl:
2252   case lltok::kw_lshr:
2253   case lltok::kw_ashr:
2254   case lltok::kw_and:
2255   case lltok::kw_or:
2256   case lltok::kw_xor: {
2257     unsigned Opc = Lex.getUIntVal();
2258     Constant *Val0, *Val1;
2259     Lex.Lex();
2260     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2261         ParseGlobalTypeAndValue(Val0) ||
2262         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2263         ParseGlobalTypeAndValue(Val1) ||
2264         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2265       return true;
2266     if (Val0->getType() != Val1->getType())
2267       return Error(ID.Loc, "operands of constexpr must have same type");
2268     if (!Val0->getType()->isIntOrIntVector())
2269       return Error(ID.Loc,
2270                    "constexpr requires integer or integer vector operands");
2271     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2272     ID.Kind = ValID::t_Constant;
2273     return false;
2274   }
2275
2276   case lltok::kw_getelementptr:
2277   case lltok::kw_shufflevector:
2278   case lltok::kw_insertelement:
2279   case lltok::kw_extractelement:
2280   case lltok::kw_select: {
2281     unsigned Opc = Lex.getUIntVal();
2282     SmallVector<Constant*, 16> Elts;
2283     bool InBounds = false;
2284     Lex.Lex();
2285     if (Opc == Instruction::GetElementPtr)
2286       InBounds = EatIfPresent(lltok::kw_inbounds);
2287     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2288         ParseGlobalValueVector(Elts) ||
2289         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2290       return true;
2291
2292     if (Opc == Instruction::GetElementPtr) {
2293       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2294         return Error(ID.Loc, "getelementptr requires pointer operand");
2295
2296       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2297                                              (Value**)(Elts.data() + 1),
2298                                              Elts.size() - 1))
2299         return Error(ID.Loc, "invalid indices for getelementptr");
2300       ID.ConstantVal = InBounds ?
2301         ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2302                                                Elts.data() + 1,
2303                                                Elts.size() - 1) :
2304         ConstantExpr::getGetElementPtr(Elts[0],
2305                                        Elts.data() + 1, Elts.size() - 1);
2306     } else if (Opc == Instruction::Select) {
2307       if (Elts.size() != 3)
2308         return Error(ID.Loc, "expected three operands to select");
2309       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2310                                                               Elts[2]))
2311         return Error(ID.Loc, Reason);
2312       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2313     } else if (Opc == Instruction::ShuffleVector) {
2314       if (Elts.size() != 3)
2315         return Error(ID.Loc, "expected three operands to shufflevector");
2316       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2317         return Error(ID.Loc, "invalid operands to shufflevector");
2318       ID.ConstantVal =
2319                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2320     } else if (Opc == Instruction::ExtractElement) {
2321       if (Elts.size() != 2)
2322         return Error(ID.Loc, "expected two operands to extractelement");
2323       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2324         return Error(ID.Loc, "invalid extractelement operands");
2325       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2326     } else {
2327       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2328       if (Elts.size() != 3)
2329       return Error(ID.Loc, "expected three operands to insertelement");
2330       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2331         return Error(ID.Loc, "invalid insertelement operands");
2332       ID.ConstantVal =
2333                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2334     }
2335
2336     ID.Kind = ValID::t_Constant;
2337     return false;
2338   }
2339   }
2340
2341   Lex.Lex();
2342   return false;
2343 }
2344
2345 /// ParseGlobalValue - Parse a global value with the specified type.
2346 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2347   V = 0;
2348   ValID ID;
2349   return ParseValID(ID) ||
2350          ConvertGlobalValIDToValue(Ty, ID, V);
2351 }
2352
2353 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2354 /// constant.
2355 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2356                                          Constant *&V) {
2357   if (isa<FunctionType>(Ty))
2358     return Error(ID.Loc, "functions are not values, refer to them as pointers");
2359
2360   switch (ID.Kind) {
2361   default: llvm_unreachable("Unknown ValID!");
2362   case ValID::t_MDNode:
2363   case ValID::t_MDString:
2364     return Error(ID.Loc, "invalid use of metadata");
2365   case ValID::t_LocalID:
2366   case ValID::t_LocalName:
2367     return Error(ID.Loc, "invalid use of function-local name");
2368   case ValID::t_InlineAsm:
2369     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2370   case ValID::t_GlobalName:
2371     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2372     return V == 0;
2373   case ValID::t_GlobalID:
2374     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2375     return V == 0;
2376   case ValID::t_APSInt:
2377     if (!isa<IntegerType>(Ty))
2378       return Error(ID.Loc, "integer constant must have integer type");
2379     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2380     V = ConstantInt::get(Context, ID.APSIntVal);
2381     return false;
2382   case ValID::t_APFloat:
2383     if (!Ty->isFloatingPoint() ||
2384         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2385       return Error(ID.Loc, "floating point constant invalid for type");
2386
2387     // The lexer has no type info, so builds all float and double FP constants
2388     // as double.  Fix this here.  Long double does not need this.
2389     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2390         Ty->isFloatTy()) {
2391       bool Ignored;
2392       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2393                             &Ignored);
2394     }
2395     V = ConstantFP::get(Context, ID.APFloatVal);
2396
2397     if (V->getType() != Ty)
2398       return Error(ID.Loc, "floating point constant does not have type '" +
2399                    Ty->getDescription() + "'");
2400
2401     return false;
2402   case ValID::t_Null:
2403     if (!isa<PointerType>(Ty))
2404       return Error(ID.Loc, "null must be a pointer type");
2405     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2406     return false;
2407   case ValID::t_Undef:
2408     // FIXME: LabelTy should not be a first-class type.
2409     if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2410         !isa<OpaqueType>(Ty))
2411       return Error(ID.Loc, "invalid type for undef constant");
2412     V = UndefValue::get(Ty);
2413     return false;
2414   case ValID::t_EmptyArray:
2415     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2416       return Error(ID.Loc, "invalid empty array initializer");
2417     V = UndefValue::get(Ty);
2418     return false;
2419   case ValID::t_Zero:
2420     // FIXME: LabelTy should not be a first-class type.
2421     if (!Ty->isFirstClassType() || Ty->isLabelTy())
2422       return Error(ID.Loc, "invalid type for null constant");
2423     V = Constant::getNullValue(Ty);
2424     return false;
2425   case ValID::t_Constant:
2426     if (ID.ConstantVal->getType() != Ty)
2427       return Error(ID.Loc, "constant expression type mismatch");
2428     V = ID.ConstantVal;
2429     return false;
2430   }
2431 }
2432
2433 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2434   PATypeHolder Type(Type::getVoidTy(Context));
2435   return ParseType(Type) ||
2436          ParseGlobalValue(Type, V);
2437 }
2438
2439 /// ParseGlobalValueVector
2440 ///   ::= /*empty*/
2441 ///   ::= TypeAndValue (',' TypeAndValue)*
2442 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2443   // Empty list.
2444   if (Lex.getKind() == lltok::rbrace ||
2445       Lex.getKind() == lltok::rsquare ||
2446       Lex.getKind() == lltok::greater ||
2447       Lex.getKind() == lltok::rparen)
2448     return false;
2449
2450   Constant *C;
2451   if (ParseGlobalTypeAndValue(C)) return true;
2452   Elts.push_back(C);
2453
2454   while (EatIfPresent(lltok::comma)) {
2455     if (ParseGlobalTypeAndValue(C)) return true;
2456     Elts.push_back(C);
2457   }
2458
2459   return false;
2460 }
2461
2462
2463 //===----------------------------------------------------------------------===//
2464 // Function Parsing.
2465 //===----------------------------------------------------------------------===//
2466
2467 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2468                                    PerFunctionState &PFS) {
2469   switch (ID.Kind) {
2470   case ValID::t_LocalID: V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); break;
2471   case ValID::t_LocalName: V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); break;
2472   case ValID::t_MDNode: V = ID.MDNodeVal; break;
2473   case ValID::t_MDString: V = ID.MDStringVal; break;
2474   case ValID::t_InlineAsm: {
2475     const PointerType *PTy = dyn_cast<PointerType>(Ty);
2476     const FunctionType *FTy = 
2477       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2478     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2479       return Error(ID.Loc, "invalid type for inline asm constraint string");
2480     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2481     return false;
2482   }
2483   default: {
2484     Constant *C;
2485     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2486     V = C;
2487     return false;
2488   }
2489   }
2490
2491   return V == 0;
2492 }
2493
2494 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2495   V = 0;
2496   ValID ID;
2497   return ParseValID(ID) ||
2498          ConvertValIDToValue(Ty, ID, V, PFS);
2499 }
2500
2501 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2502   PATypeHolder T(Type::getVoidTy(Context));
2503   return ParseType(T) ||
2504          ParseValue(T, V, PFS);
2505 }
2506
2507 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2508                                       PerFunctionState &PFS) {
2509   Value *V;
2510   Loc = Lex.getLoc();
2511   if (ParseTypeAndValue(V, PFS)) return true;
2512   if (!isa<BasicBlock>(V))
2513     return Error(Loc, "expected a basic block");
2514   BB = cast<BasicBlock>(V);
2515   return false;
2516 }
2517
2518
2519 /// FunctionHeader
2520 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2521 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2522 ///       OptionalAlign OptGC
2523 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2524   // Parse the linkage.
2525   LocTy LinkageLoc = Lex.getLoc();
2526   unsigned Linkage;
2527
2528   unsigned Visibility, RetAttrs;
2529   CallingConv::ID CC;
2530   PATypeHolder RetType(Type::getVoidTy(Context));
2531   LocTy RetTypeLoc = Lex.getLoc();
2532   if (ParseOptionalLinkage(Linkage) ||
2533       ParseOptionalVisibility(Visibility) ||
2534       ParseOptionalCallingConv(CC) ||
2535       ParseOptionalAttrs(RetAttrs, 1) ||
2536       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2537     return true;
2538
2539   // Verify that the linkage is ok.
2540   switch ((GlobalValue::LinkageTypes)Linkage) {
2541   case GlobalValue::ExternalLinkage:
2542     break; // always ok.
2543   case GlobalValue::DLLImportLinkage:
2544   case GlobalValue::ExternalWeakLinkage:
2545     if (isDefine)
2546       return Error(LinkageLoc, "invalid linkage for function definition");
2547     break;
2548   case GlobalValue::PrivateLinkage:
2549   case GlobalValue::LinkerPrivateLinkage:
2550   case GlobalValue::InternalLinkage:
2551   case GlobalValue::AvailableExternallyLinkage:
2552   case GlobalValue::LinkOnceAnyLinkage:
2553   case GlobalValue::LinkOnceODRLinkage:
2554   case GlobalValue::WeakAnyLinkage:
2555   case GlobalValue::WeakODRLinkage:
2556   case GlobalValue::DLLExportLinkage:
2557     if (!isDefine)
2558       return Error(LinkageLoc, "invalid linkage for function declaration");
2559     break;
2560   case GlobalValue::AppendingLinkage:
2561   case GlobalValue::GhostLinkage:
2562   case GlobalValue::CommonLinkage:
2563     return Error(LinkageLoc, "invalid function linkage type");
2564   }
2565
2566   if (!FunctionType::isValidReturnType(RetType) ||
2567       isa<OpaqueType>(RetType))
2568     return Error(RetTypeLoc, "invalid function return type");
2569
2570   LocTy NameLoc = Lex.getLoc();
2571
2572   std::string FunctionName;
2573   if (Lex.getKind() == lltok::GlobalVar) {
2574     FunctionName = Lex.getStrVal();
2575   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2576     unsigned NameID = Lex.getUIntVal();
2577
2578     if (NameID != NumberedVals.size())
2579       return TokError("function expected to be numbered '%" +
2580                       utostr(NumberedVals.size()) + "'");
2581   } else {
2582     return TokError("expected function name");
2583   }
2584
2585   Lex.Lex();
2586
2587   if (Lex.getKind() != lltok::lparen)
2588     return TokError("expected '(' in function argument list");
2589
2590   std::vector<ArgInfo> ArgList;
2591   bool isVarArg;
2592   unsigned FuncAttrs;
2593   std::string Section;
2594   unsigned Alignment;
2595   std::string GC;
2596
2597   if (ParseArgumentList(ArgList, isVarArg, false) ||
2598       ParseOptionalAttrs(FuncAttrs, 2) ||
2599       (EatIfPresent(lltok::kw_section) &&
2600        ParseStringConstant(Section)) ||
2601       ParseOptionalAlignment(Alignment) ||
2602       (EatIfPresent(lltok::kw_gc) &&
2603        ParseStringConstant(GC)))
2604     return true;
2605
2606   // If the alignment was parsed as an attribute, move to the alignment field.
2607   if (FuncAttrs & Attribute::Alignment) {
2608     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2609     FuncAttrs &= ~Attribute::Alignment;
2610   }
2611
2612   // Okay, if we got here, the function is syntactically valid.  Convert types
2613   // and do semantic checks.
2614   std::vector<const Type*> ParamTypeList;
2615   SmallVector<AttributeWithIndex, 8> Attrs;
2616   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2617   // attributes.
2618   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2619   if (FuncAttrs & ObsoleteFuncAttrs) {
2620     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2621     FuncAttrs &= ~ObsoleteFuncAttrs;
2622   }
2623
2624   if (RetAttrs != Attribute::None)
2625     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2626
2627   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2628     ParamTypeList.push_back(ArgList[i].Type);
2629     if (ArgList[i].Attrs != Attribute::None)
2630       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2631   }
2632
2633   if (FuncAttrs != Attribute::None)
2634     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2635
2636   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2637
2638   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2639       RetType != Type::getVoidTy(Context))
2640     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2641
2642   const FunctionType *FT =
2643     FunctionType::get(RetType, ParamTypeList, isVarArg);
2644   const PointerType *PFT = PointerType::getUnqual(FT);
2645
2646   Fn = 0;
2647   if (!FunctionName.empty()) {
2648     // If this was a definition of a forward reference, remove the definition
2649     // from the forward reference table and fill in the forward ref.
2650     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2651       ForwardRefVals.find(FunctionName);
2652     if (FRVI != ForwardRefVals.end()) {
2653       Fn = M->getFunction(FunctionName);
2654       ForwardRefVals.erase(FRVI);
2655     } else if ((Fn = M->getFunction(FunctionName))) {
2656       // If this function already exists in the symbol table, then it is
2657       // multiply defined.  We accept a few cases for old backwards compat.
2658       // FIXME: Remove this stuff for LLVM 3.0.
2659       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2660           (!Fn->isDeclaration() && isDefine)) {
2661         // If the redefinition has different type or different attributes,
2662         // reject it.  If both have bodies, reject it.
2663         return Error(NameLoc, "invalid redefinition of function '" +
2664                      FunctionName + "'");
2665       } else if (Fn->isDeclaration()) {
2666         // Make sure to strip off any argument names so we can't get conflicts.
2667         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2668              AI != AE; ++AI)
2669           AI->setName("");
2670       }
2671     } else if (M->getNamedValue(FunctionName)) {
2672       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2673     }
2674
2675   } else {
2676     // If this is a definition of a forward referenced function, make sure the
2677     // types agree.
2678     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2679       = ForwardRefValIDs.find(NumberedVals.size());
2680     if (I != ForwardRefValIDs.end()) {
2681       Fn = cast<Function>(I->second.first);
2682       if (Fn->getType() != PFT)
2683         return Error(NameLoc, "type of definition and forward reference of '@" +
2684                      utostr(NumberedVals.size()) +"' disagree");
2685       ForwardRefValIDs.erase(I);
2686     }
2687   }
2688
2689   if (Fn == 0)
2690     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2691   else // Move the forward-reference to the correct spot in the module.
2692     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2693
2694   if (FunctionName.empty())
2695     NumberedVals.push_back(Fn);
2696
2697   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2698   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2699   Fn->setCallingConv(CC);
2700   Fn->setAttributes(PAL);
2701   Fn->setAlignment(Alignment);
2702   Fn->setSection(Section);
2703   if (!GC.empty()) Fn->setGC(GC.c_str());
2704
2705   // Add all of the arguments we parsed to the function.
2706   Function::arg_iterator ArgIt = Fn->arg_begin();
2707   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2708     // If we run out of arguments in the Function prototype, exit early.
2709     // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2710     if (ArgIt == Fn->arg_end()) break;
2711     
2712     // If the argument has a name, insert it into the argument symbol table.
2713     if (ArgList[i].Name.empty()) continue;
2714
2715     // Set the name, if it conflicted, it will be auto-renamed.
2716     ArgIt->setName(ArgList[i].Name);
2717
2718     if (ArgIt->getNameStr() != ArgList[i].Name)
2719       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2720                    ArgList[i].Name + "'");
2721   }
2722
2723   return false;
2724 }
2725
2726
2727 /// ParseFunctionBody
2728 ///   ::= '{' BasicBlock+ '}'
2729 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2730 ///
2731 bool LLParser::ParseFunctionBody(Function &Fn) {
2732   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2733     return TokError("expected '{' in function body");
2734   Lex.Lex();  // eat the {.
2735
2736   int FunctionNumber = -1;
2737   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2738   
2739   PerFunctionState PFS(*this, Fn, FunctionNumber);
2740
2741   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2742     if (ParseBasicBlock(PFS)) return true;
2743
2744   // Eat the }.
2745   Lex.Lex();
2746
2747   // Verify function is ok.
2748   return PFS.FinishFunction();
2749 }
2750
2751 /// ParseBasicBlock
2752 ///   ::= LabelStr? Instruction*
2753 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2754   // If this basic block starts out with a name, remember it.
2755   std::string Name;
2756   LocTy NameLoc = Lex.getLoc();
2757   if (Lex.getKind() == lltok::LabelStr) {
2758     Name = Lex.getStrVal();
2759     Lex.Lex();
2760   }
2761
2762   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2763   if (BB == 0) return true;
2764
2765   std::string NameStr;
2766
2767   // Parse the instructions in this block until we get a terminator.
2768   Instruction *Inst;
2769   do {
2770     // This instruction may have three possibilities for a name: a) none
2771     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2772     LocTy NameLoc = Lex.getLoc();
2773     int NameID = -1;
2774     NameStr = "";
2775
2776     if (Lex.getKind() == lltok::LocalVarID) {
2777       NameID = Lex.getUIntVal();
2778       Lex.Lex();
2779       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2780         return true;
2781     } else if (Lex.getKind() == lltok::LocalVar ||
2782                // FIXME: REMOVE IN LLVM 3.0
2783                Lex.getKind() == lltok::StringConstant) {
2784       NameStr = Lex.getStrVal();
2785       Lex.Lex();
2786       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2787         return true;
2788     }
2789
2790     if (ParseInstruction(Inst, BB, PFS)) return true;
2791     if (EatIfPresent(lltok::comma))
2792       ParseOptionalCustomMetadata();
2793
2794     // Set metadata attached with this instruction.
2795     for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2796            MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2797       Inst->setMetadata(MDI->first, MDI->second);
2798     MDsOnInst.clear();
2799
2800     BB->getInstList().push_back(Inst);
2801
2802     // Set the name on the instruction.
2803     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2804   } while (!isa<TerminatorInst>(Inst));
2805
2806   return false;
2807 }
2808
2809 //===----------------------------------------------------------------------===//
2810 // Instruction Parsing.
2811 //===----------------------------------------------------------------------===//
2812
2813 /// ParseInstruction - Parse one of the many different instructions.
2814 ///
2815 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2816                                 PerFunctionState &PFS) {
2817   lltok::Kind Token = Lex.getKind();
2818   if (Token == lltok::Eof)
2819     return TokError("found end of file when expecting more instructions");
2820   LocTy Loc = Lex.getLoc();
2821   unsigned KeywordVal = Lex.getUIntVal();
2822   Lex.Lex();  // Eat the keyword.
2823
2824   switch (Token) {
2825   default:                    return Error(Loc, "expected instruction opcode");
2826   // Terminator Instructions.
2827   case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
2828   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2829   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2830   case lltok::kw_br:          return ParseBr(Inst, PFS);
2831   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2832   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
2833   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2834   // Binary Operators.
2835   case lltok::kw_add:
2836   case lltok::kw_sub:
2837   case lltok::kw_mul: {
2838     bool NUW = false;
2839     bool NSW = false;
2840     LocTy ModifierLoc = Lex.getLoc();
2841     if (EatIfPresent(lltok::kw_nuw))
2842       NUW = true;
2843     if (EatIfPresent(lltok::kw_nsw)) {
2844       NSW = true;
2845       if (EatIfPresent(lltok::kw_nuw))
2846         NUW = true;
2847     }
2848     // API compatibility: Accept either integer or floating-point types.
2849     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2850     if (!Result) {
2851       if (!Inst->getType()->isIntOrIntVector()) {
2852         if (NUW)
2853           return Error(ModifierLoc, "nuw only applies to integer operations");
2854         if (NSW)
2855           return Error(ModifierLoc, "nsw only applies to integer operations");
2856       }
2857       if (NUW)
2858         cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2859       if (NSW)
2860         cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2861     }
2862     return Result;
2863   }
2864   case lltok::kw_fadd:
2865   case lltok::kw_fsub:
2866   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2867
2868   case lltok::kw_sdiv: {
2869     bool Exact = false;
2870     if (EatIfPresent(lltok::kw_exact))
2871       Exact = true;
2872     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2873     if (!Result)
2874       if (Exact)
2875         cast<BinaryOperator>(Inst)->setIsExact(true);
2876     return Result;
2877   }
2878
2879   case lltok::kw_udiv:
2880   case lltok::kw_urem:
2881   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2882   case lltok::kw_fdiv:
2883   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2884   case lltok::kw_shl:
2885   case lltok::kw_lshr:
2886   case lltok::kw_ashr:
2887   case lltok::kw_and:
2888   case lltok::kw_or:
2889   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2890   case lltok::kw_icmp:
2891   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2892   // Casts.
2893   case lltok::kw_trunc:
2894   case lltok::kw_zext:
2895   case lltok::kw_sext:
2896   case lltok::kw_fptrunc:
2897   case lltok::kw_fpext:
2898   case lltok::kw_bitcast:
2899   case lltok::kw_uitofp:
2900   case lltok::kw_sitofp:
2901   case lltok::kw_fptoui:
2902   case lltok::kw_fptosi:
2903   case lltok::kw_inttoptr:
2904   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2905   // Other.
2906   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2907   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2908   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2909   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2910   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2911   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2912   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2913   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2914   // Memory.
2915   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
2916   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, BB, false);
2917   case lltok::kw_free:           return ParseFree(Inst, PFS, BB);
2918   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2919   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2920   case lltok::kw_volatile:
2921     if (EatIfPresent(lltok::kw_load))
2922       return ParseLoad(Inst, PFS, true);
2923     else if (EatIfPresent(lltok::kw_store))
2924       return ParseStore(Inst, PFS, true);
2925     else
2926       return TokError("expected 'load' or 'store'");
2927   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2928   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2929   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2930   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2931   }
2932 }
2933
2934 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2935 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2936   if (Opc == Instruction::FCmp) {
2937     switch (Lex.getKind()) {
2938     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2939     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2940     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2941     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2942     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2943     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2944     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2945     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2946     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2947     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2948     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2949     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2950     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2951     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2952     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2953     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2954     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2955     }
2956   } else {
2957     switch (Lex.getKind()) {
2958     default: TokError("expected icmp predicate (e.g. 'eq')");
2959     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2960     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2961     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2962     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2963     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2964     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2965     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2966     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2967     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2968     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2969     }
2970   }
2971   Lex.Lex();
2972   return false;
2973 }
2974
2975 //===----------------------------------------------------------------------===//
2976 // Terminator Instructions.
2977 //===----------------------------------------------------------------------===//
2978
2979 /// ParseRet - Parse a return instruction.
2980 ///   ::= 'ret' void (',' !dbg, !1)*
2981 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
2982 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  (',' !dbg, !1)*
2983 ///         [[obsolete: LLVM 3.0]]
2984 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2985                         PerFunctionState &PFS) {
2986   PATypeHolder Ty(Type::getVoidTy(Context));
2987   if (ParseType(Ty, true /*void allowed*/)) return true;
2988
2989   if (Ty->isVoidTy()) {
2990     Inst = ReturnInst::Create(Context);
2991     return false;
2992   }
2993
2994   Value *RV;
2995   if (ParseValue(Ty, RV, PFS)) return true;
2996
2997   if (EatIfPresent(lltok::comma)) {
2998     // Parse optional custom metadata, e.g. !dbg
2999     if (Lex.getKind() == lltok::NamedOrCustomMD) {
3000       if (ParseOptionalCustomMetadata()) return true;
3001     } else {
3002       // The normal case is one return value.
3003       // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3004       // use of 'ret {i32,i32} {i32 1, i32 2}'
3005       SmallVector<Value*, 8> RVs;
3006       RVs.push_back(RV);
3007
3008       do {
3009         // If optional custom metadata, e.g. !dbg is seen then this is the 
3010         // end of MRV.
3011         if (Lex.getKind() == lltok::NamedOrCustomMD)
3012           break;
3013         if (ParseTypeAndValue(RV, PFS)) return true;
3014         RVs.push_back(RV);
3015       } while (EatIfPresent(lltok::comma));
3016
3017       RV = UndefValue::get(PFS.getFunction().getReturnType());
3018       for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3019         Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3020         BB->getInstList().push_back(I);
3021         RV = I;
3022       }
3023     }
3024   }
3025
3026   Inst = ReturnInst::Create(Context, RV);
3027   return false;
3028 }
3029
3030
3031 /// ParseBr
3032 ///   ::= 'br' TypeAndValue
3033 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3034 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3035   LocTy Loc, Loc2;
3036   Value *Op0;
3037   BasicBlock *Op1, *Op2;
3038   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3039
3040   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3041     Inst = BranchInst::Create(BB);
3042     return false;
3043   }
3044
3045   if (Op0->getType() != Type::getInt1Ty(Context))
3046     return Error(Loc, "branch condition must have 'i1' type");
3047
3048   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3049       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3050       ParseToken(lltok::comma, "expected ',' after true destination") ||
3051       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3052     return true;
3053
3054   Inst = BranchInst::Create(Op1, Op2, Op0);
3055   return false;
3056 }
3057
3058 /// ParseSwitch
3059 ///  Instruction
3060 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3061 ///  JumpTable
3062 ///    ::= (TypeAndValue ',' TypeAndValue)*
3063 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3064   LocTy CondLoc, BBLoc;
3065   Value *Cond;
3066   BasicBlock *DefaultBB;
3067   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3068       ParseToken(lltok::comma, "expected ',' after switch condition") ||
3069       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3070       ParseToken(lltok::lsquare, "expected '[' with switch table"))
3071     return true;
3072
3073   if (!isa<IntegerType>(Cond->getType()))
3074     return Error(CondLoc, "switch condition must have integer type");
3075
3076   // Parse the jump table pairs.
3077   SmallPtrSet<Value*, 32> SeenCases;
3078   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3079   while (Lex.getKind() != lltok::rsquare) {
3080     Value *Constant;
3081     BasicBlock *DestBB;
3082
3083     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3084         ParseToken(lltok::comma, "expected ',' after case value") ||
3085         ParseTypeAndBasicBlock(DestBB, PFS))
3086       return true;
3087     
3088     if (!SeenCases.insert(Constant))
3089       return Error(CondLoc, "duplicate case value in switch");
3090     if (!isa<ConstantInt>(Constant))
3091       return Error(CondLoc, "case value is not a constant integer");
3092
3093     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3094   }
3095
3096   Lex.Lex();  // Eat the ']'.
3097
3098   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3099   for (unsigned i = 0, e = Table.size(); i != e; ++i)
3100     SI->addCase(Table[i].first, Table[i].second);
3101   Inst = SI;
3102   return false;
3103 }
3104
3105 /// ParseIndirectBr
3106 ///  Instruction
3107 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3108 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3109   LocTy AddrLoc;
3110   Value *Address;
3111   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3112       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3113       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3114     return true;
3115   
3116   if (!isa<PointerType>(Address->getType()))
3117     return Error(AddrLoc, "indirectbr address must have pointer type");
3118   
3119   // Parse the destination list.
3120   SmallVector<BasicBlock*, 16> DestList;
3121   
3122   if (Lex.getKind() != lltok::rsquare) {
3123     BasicBlock *DestBB;
3124     if (ParseTypeAndBasicBlock(DestBB, PFS))
3125       return true;
3126     DestList.push_back(DestBB);
3127     
3128     while (EatIfPresent(lltok::comma)) {
3129       if (ParseTypeAndBasicBlock(DestBB, PFS))
3130         return true;
3131       DestList.push_back(DestBB);
3132     }
3133   }
3134   
3135   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3136     return true;
3137
3138   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3139   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3140     IBI->addDestination(DestList[i]);
3141   Inst = IBI;
3142   return false;
3143 }
3144
3145
3146 /// ParseInvoke
3147 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3148 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3149 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3150   LocTy CallLoc = Lex.getLoc();
3151   unsigned RetAttrs, FnAttrs;
3152   CallingConv::ID CC;
3153   PATypeHolder RetType(Type::getVoidTy(Context));
3154   LocTy RetTypeLoc;
3155   ValID CalleeID;
3156   SmallVector<ParamInfo, 16> ArgList;
3157
3158   BasicBlock *NormalBB, *UnwindBB;
3159   if (ParseOptionalCallingConv(CC) ||
3160       ParseOptionalAttrs(RetAttrs, 1) ||
3161       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3162       ParseValID(CalleeID) ||
3163       ParseParameterList(ArgList, PFS) ||
3164       ParseOptionalAttrs(FnAttrs, 2) ||
3165       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3166       ParseTypeAndBasicBlock(NormalBB, PFS) ||
3167       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3168       ParseTypeAndBasicBlock(UnwindBB, PFS))
3169     return true;
3170
3171   // If RetType is a non-function pointer type, then this is the short syntax
3172   // for the call, which means that RetType is just the return type.  Infer the
3173   // rest of the function argument types from the arguments that are present.
3174   const PointerType *PFTy = 0;
3175   const FunctionType *Ty = 0;
3176   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3177       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3178     // Pull out the types of all of the arguments...
3179     std::vector<const Type*> ParamTypes;
3180     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3181       ParamTypes.push_back(ArgList[i].V->getType());
3182
3183     if (!FunctionType::isValidReturnType(RetType))
3184       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3185
3186     Ty = FunctionType::get(RetType, ParamTypes, false);
3187     PFTy = PointerType::getUnqual(Ty);
3188   }
3189
3190   // Look up the callee.
3191   Value *Callee;
3192   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3193
3194   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3195   // function attributes.
3196   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3197   if (FnAttrs & ObsoleteFuncAttrs) {
3198     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3199     FnAttrs &= ~ObsoleteFuncAttrs;
3200   }
3201
3202   // Set up the Attributes for the function.
3203   SmallVector<AttributeWithIndex, 8> Attrs;
3204   if (RetAttrs != Attribute::None)
3205     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3206
3207   SmallVector<Value*, 8> Args;
3208
3209   // Loop through FunctionType's arguments and ensure they are specified
3210   // correctly.  Also, gather any parameter attributes.
3211   FunctionType::param_iterator I = Ty->param_begin();
3212   FunctionType::param_iterator E = Ty->param_end();
3213   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3214     const Type *ExpectedTy = 0;
3215     if (I != E) {
3216       ExpectedTy = *I++;
3217     } else if (!Ty->isVarArg()) {
3218       return Error(ArgList[i].Loc, "too many arguments specified");
3219     }
3220
3221     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3222       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3223                    ExpectedTy->getDescription() + "'");
3224     Args.push_back(ArgList[i].V);
3225     if (ArgList[i].Attrs != Attribute::None)
3226       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3227   }
3228
3229   if (I != E)
3230     return Error(CallLoc, "not enough parameters specified for call");
3231
3232   if (FnAttrs != Attribute::None)
3233     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3234
3235   // Finish off the Attributes and check them
3236   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3237
3238   InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3239                                       Args.begin(), Args.end());
3240   II->setCallingConv(CC);
3241   II->setAttributes(PAL);
3242   Inst = II;
3243   return false;
3244 }
3245
3246
3247
3248 //===----------------------------------------------------------------------===//
3249 // Binary Operators.
3250 //===----------------------------------------------------------------------===//
3251
3252 /// ParseArithmetic
3253 ///  ::= ArithmeticOps TypeAndValue ',' Value
3254 ///
3255 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3256 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3257 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3258                                unsigned Opc, unsigned OperandType) {
3259   LocTy Loc; Value *LHS, *RHS;
3260   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3261       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3262       ParseValue(LHS->getType(), RHS, PFS))
3263     return true;
3264
3265   bool Valid;
3266   switch (OperandType) {
3267   default: llvm_unreachable("Unknown operand type!");
3268   case 0: // int or FP.
3269     Valid = LHS->getType()->isIntOrIntVector() ||
3270             LHS->getType()->isFPOrFPVector();
3271     break;
3272   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3273   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3274   }
3275
3276   if (!Valid)
3277     return Error(Loc, "invalid operand type for instruction");
3278
3279   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3280   return false;
3281 }
3282
3283 /// ParseLogical
3284 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3285 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3286                             unsigned Opc) {
3287   LocTy Loc; Value *LHS, *RHS;
3288   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3289       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3290       ParseValue(LHS->getType(), RHS, PFS))
3291     return true;
3292
3293   if (!LHS->getType()->isIntOrIntVector())
3294     return Error(Loc,"instruction requires integer or integer vector operands");
3295
3296   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3297   return false;
3298 }
3299
3300
3301 /// ParseCompare
3302 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3303 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3304 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3305                             unsigned Opc) {
3306   // Parse the integer/fp comparison predicate.
3307   LocTy Loc;
3308   unsigned Pred;
3309   Value *LHS, *RHS;
3310   if (ParseCmpPredicate(Pred, Opc) ||
3311       ParseTypeAndValue(LHS, Loc, PFS) ||
3312       ParseToken(lltok::comma, "expected ',' after compare value") ||
3313       ParseValue(LHS->getType(), RHS, PFS))
3314     return true;
3315
3316   if (Opc == Instruction::FCmp) {
3317     if (!LHS->getType()->isFPOrFPVector())
3318       return Error(Loc, "fcmp requires floating point operands");
3319     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3320   } else {
3321     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3322     if (!LHS->getType()->isIntOrIntVector() &&
3323         !isa<PointerType>(LHS->getType()))
3324       return Error(Loc, "icmp requires integer operands");
3325     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3326   }
3327   return false;
3328 }
3329
3330 //===----------------------------------------------------------------------===//
3331 // Other Instructions.
3332 //===----------------------------------------------------------------------===//
3333
3334
3335 /// ParseCast
3336 ///   ::= CastOpc TypeAndValue 'to' Type
3337 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3338                          unsigned Opc) {
3339   LocTy Loc;  Value *Op;
3340   PATypeHolder DestTy(Type::getVoidTy(Context));
3341   if (ParseTypeAndValue(Op, Loc, PFS) ||
3342       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3343       ParseType(DestTy))
3344     return true;
3345
3346   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3347     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3348     return Error(Loc, "invalid cast opcode for cast from '" +
3349                  Op->getType()->getDescription() + "' to '" +
3350                  DestTy->getDescription() + "'");
3351   }
3352   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3353   return false;
3354 }
3355
3356 /// ParseSelect
3357 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3358 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3359   LocTy Loc;
3360   Value *Op0, *Op1, *Op2;
3361   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3362       ParseToken(lltok::comma, "expected ',' after select condition") ||
3363       ParseTypeAndValue(Op1, PFS) ||
3364       ParseToken(lltok::comma, "expected ',' after select value") ||
3365       ParseTypeAndValue(Op2, PFS))
3366     return true;
3367
3368   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3369     return Error(Loc, Reason);
3370
3371   Inst = SelectInst::Create(Op0, Op1, Op2);
3372   return false;
3373 }
3374
3375 /// ParseVA_Arg
3376 ///   ::= 'va_arg' TypeAndValue ',' Type
3377 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3378   Value *Op;
3379   PATypeHolder EltTy(Type::getVoidTy(Context));
3380   LocTy TypeLoc;
3381   if (ParseTypeAndValue(Op, PFS) ||
3382       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3383       ParseType(EltTy, TypeLoc))
3384     return true;
3385
3386   if (!EltTy->isFirstClassType())
3387     return Error(TypeLoc, "va_arg requires operand with first class type");
3388
3389   Inst = new VAArgInst(Op, EltTy);
3390   return false;
3391 }
3392
3393 /// ParseExtractElement
3394 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3395 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3396   LocTy Loc;
3397   Value *Op0, *Op1;
3398   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3399       ParseToken(lltok::comma, "expected ',' after extract value") ||
3400       ParseTypeAndValue(Op1, PFS))
3401     return true;
3402
3403   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3404     return Error(Loc, "invalid extractelement operands");
3405
3406   Inst = ExtractElementInst::Create(Op0, Op1);
3407   return false;
3408 }
3409
3410 /// ParseInsertElement
3411 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3412 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3413   LocTy Loc;
3414   Value *Op0, *Op1, *Op2;
3415   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3416       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3417       ParseTypeAndValue(Op1, PFS) ||
3418       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3419       ParseTypeAndValue(Op2, PFS))
3420     return true;
3421
3422   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3423     return Error(Loc, "invalid insertelement operands");
3424
3425   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3426   return false;
3427 }
3428
3429 /// ParseShuffleVector
3430 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3431 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3432   LocTy Loc;
3433   Value *Op0, *Op1, *Op2;
3434   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3435       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3436       ParseTypeAndValue(Op1, PFS) ||
3437       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3438       ParseTypeAndValue(Op2, PFS))
3439     return true;
3440
3441   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3442     return Error(Loc, "invalid extractelement operands");
3443
3444   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3445   return false;
3446 }
3447
3448 /// ParsePHI
3449 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3450 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3451   PATypeHolder Ty(Type::getVoidTy(Context));
3452   Value *Op0, *Op1;
3453   LocTy TypeLoc = Lex.getLoc();
3454
3455   if (ParseType(Ty) ||
3456       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3457       ParseValue(Ty, Op0, PFS) ||
3458       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3459       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3460       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3461     return true;
3462
3463   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3464   while (1) {
3465     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3466
3467     if (!EatIfPresent(lltok::comma))
3468       break;
3469
3470     if (Lex.getKind() == lltok::NamedOrCustomMD)
3471       break;
3472
3473     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3474         ParseValue(Ty, Op0, PFS) ||
3475         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3476         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3477         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3478       return true;
3479   }
3480
3481   if (Lex.getKind() == lltok::NamedOrCustomMD)
3482     if (ParseOptionalCustomMetadata()) return true;
3483
3484   if (!Ty->isFirstClassType())
3485     return Error(TypeLoc, "phi node must have first class type");
3486
3487   PHINode *PN = PHINode::Create(Ty);
3488   PN->reserveOperandSpace(PHIVals.size());
3489   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3490     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3491   Inst = PN;
3492   return false;
3493 }
3494
3495 /// ParseCall
3496 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3497 ///       ParameterList OptionalAttrs
3498 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3499                          bool isTail) {
3500   unsigned RetAttrs, FnAttrs;
3501   CallingConv::ID CC;
3502   PATypeHolder RetType(Type::getVoidTy(Context));
3503   LocTy RetTypeLoc;
3504   ValID CalleeID;
3505   SmallVector<ParamInfo, 16> ArgList;
3506   LocTy CallLoc = Lex.getLoc();
3507
3508   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3509       ParseOptionalCallingConv(CC) ||
3510       ParseOptionalAttrs(RetAttrs, 1) ||
3511       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3512       ParseValID(CalleeID) ||
3513       ParseParameterList(ArgList, PFS) ||
3514       ParseOptionalAttrs(FnAttrs, 2))
3515     return true;
3516
3517   // If RetType is a non-function pointer type, then this is the short syntax
3518   // for the call, which means that RetType is just the return type.  Infer the
3519   // rest of the function argument types from the arguments that are present.
3520   const PointerType *PFTy = 0;
3521   const FunctionType *Ty = 0;
3522   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3523       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3524     // Pull out the types of all of the arguments...
3525     std::vector<const Type*> ParamTypes;
3526     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3527       ParamTypes.push_back(ArgList[i].V->getType());
3528
3529     if (!FunctionType::isValidReturnType(RetType))
3530       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3531
3532     Ty = FunctionType::get(RetType, ParamTypes, false);
3533     PFTy = PointerType::getUnqual(Ty);
3534   }
3535
3536   // Look up the callee.
3537   Value *Callee;
3538   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3539
3540   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3541   // function attributes.
3542   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3543   if (FnAttrs & ObsoleteFuncAttrs) {
3544     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3545     FnAttrs &= ~ObsoleteFuncAttrs;
3546   }
3547
3548   // Set up the Attributes for the function.
3549   SmallVector<AttributeWithIndex, 8> Attrs;
3550   if (RetAttrs != Attribute::None)
3551     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3552
3553   SmallVector<Value*, 8> Args;
3554
3555   // Loop through FunctionType's arguments and ensure they are specified
3556   // correctly.  Also, gather any parameter attributes.
3557   FunctionType::param_iterator I = Ty->param_begin();
3558   FunctionType::param_iterator E = Ty->param_end();
3559   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3560     const Type *ExpectedTy = 0;
3561     if (I != E) {
3562       ExpectedTy = *I++;
3563     } else if (!Ty->isVarArg()) {
3564       return Error(ArgList[i].Loc, "too many arguments specified");
3565     }
3566
3567     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3568       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3569                    ExpectedTy->getDescription() + "'");
3570     Args.push_back(ArgList[i].V);
3571     if (ArgList[i].Attrs != Attribute::None)
3572       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3573   }
3574
3575   if (I != E)
3576     return Error(CallLoc, "not enough parameters specified for call");
3577
3578   if (FnAttrs != Attribute::None)
3579     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3580
3581   // Finish off the Attributes and check them
3582   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3583
3584   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3585   CI->setTailCall(isTail);
3586   CI->setCallingConv(CC);
3587   CI->setAttributes(PAL);
3588   Inst = CI;
3589   return false;
3590 }
3591
3592 //===----------------------------------------------------------------------===//
3593 // Memory Instructions.
3594 //===----------------------------------------------------------------------===//
3595
3596 /// ParseAlloc
3597 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3598 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3599 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3600                           BasicBlock* BB, bool isAlloca) {
3601   PATypeHolder Ty(Type::getVoidTy(Context));
3602   Value *Size = 0;
3603   LocTy SizeLoc;
3604   unsigned Alignment = 0;
3605   if (ParseType(Ty)) return true;
3606
3607   if (EatIfPresent(lltok::comma)) {
3608     if (Lex.getKind() == lltok::kw_align 
3609         || Lex.getKind() == lltok::NamedOrCustomMD) {
3610       if (ParseOptionalInfo(Alignment)) return true;
3611     } else {
3612       if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3613       if (EatIfPresent(lltok::comma))
3614         if (ParseOptionalInfo(Alignment)) return true;
3615     }
3616   }
3617
3618   if (Size && Size->getType() != Type::getInt32Ty(Context))
3619     return Error(SizeLoc, "element count must be i32");
3620
3621   if (isAlloca) {
3622     Inst = new AllocaInst(Ty, Size, Alignment);
3623     return false;
3624   }
3625
3626   // Autoupgrade old malloc instruction to malloc call.
3627   // FIXME: Remove in LLVM 3.0.
3628   const Type *IntPtrTy = Type::getInt32Ty(Context);
3629   Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3630   AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
3631   if (!MallocF)
3632     // Prototype malloc as "void *(int32)".
3633     // This function is renamed as "malloc" in ValidateEndOfModule().
3634     MallocF = cast<Function>(
3635        M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3636   Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
3637   return false;
3638 }
3639
3640 /// ParseFree
3641 ///   ::= 'free' TypeAndValue
3642 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3643                          BasicBlock* BB) {
3644   Value *Val; LocTy Loc;
3645   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3646   if (!isa<PointerType>(Val->getType()))
3647     return Error(Loc, "operand to free must be a pointer");
3648   Inst = CallInst::CreateFree(Val, BB);
3649   return false;
3650 }
3651
3652 /// ParseLoad
3653 ///   ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3654 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3655                          bool isVolatile) {
3656   Value *Val; LocTy Loc;
3657   unsigned Alignment = 0;
3658   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3659
3660   if (EatIfPresent(lltok::comma))
3661     if (ParseOptionalInfo(Alignment)) return true;
3662
3663   if (!isa<PointerType>(Val->getType()) ||
3664       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3665     return Error(Loc, "load operand must be a pointer to a first class type");
3666
3667   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3668   return false;
3669 }
3670
3671 /// ParseStore
3672 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3673 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3674                           bool isVolatile) {
3675   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3676   unsigned Alignment = 0;
3677   if (ParseTypeAndValue(Val, Loc, PFS) ||
3678       ParseToken(lltok::comma, "expected ',' after store operand") ||
3679       ParseTypeAndValue(Ptr, PtrLoc, PFS))
3680     return true;
3681
3682   if (EatIfPresent(lltok::comma))
3683     if (ParseOptionalInfo(Alignment)) return true;
3684
3685   if (!isa<PointerType>(Ptr->getType()))
3686     return Error(PtrLoc, "store operand must be a pointer");
3687   if (!Val->getType()->isFirstClassType())
3688     return Error(Loc, "store operand must be a first class value");
3689   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3690     return Error(Loc, "stored value and pointer type do not match");
3691
3692   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3693   return false;
3694 }
3695
3696 /// ParseGetResult
3697 ///   ::= 'getresult' TypeAndValue ',' i32
3698 /// FIXME: Remove support for getresult in LLVM 3.0
3699 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3700   Value *Val; LocTy ValLoc, EltLoc;
3701   unsigned Element;
3702   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3703       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3704       ParseUInt32(Element, EltLoc))
3705     return true;
3706
3707   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3708     return Error(ValLoc, "getresult inst requires an aggregate operand");
3709   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3710     return Error(EltLoc, "invalid getresult index for value");
3711   Inst = ExtractValueInst::Create(Val, Element);
3712   return false;
3713 }
3714
3715 /// ParseGetElementPtr
3716 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3717 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3718   Value *Ptr, *Val; LocTy Loc, EltLoc;
3719
3720   bool InBounds = EatIfPresent(lltok::kw_inbounds);
3721
3722   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3723
3724   if (!isa<PointerType>(Ptr->getType()))
3725     return Error(Loc, "base of getelementptr must be a pointer");
3726
3727   SmallVector<Value*, 16> Indices;
3728   while (EatIfPresent(lltok::comma)) {
3729     if (Lex.getKind() == lltok::NamedOrCustomMD)
3730       break;
3731     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3732     if (!isa<IntegerType>(Val->getType()))
3733       return Error(EltLoc, "getelementptr index must be an integer");
3734     Indices.push_back(Val);
3735   }
3736   if (Lex.getKind() == lltok::NamedOrCustomMD)
3737     if (ParseOptionalCustomMetadata()) return true;
3738
3739   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3740                                          Indices.begin(), Indices.end()))
3741     return Error(Loc, "invalid getelementptr indices");
3742   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3743   if (InBounds)
3744     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3745   return false;
3746 }
3747
3748 /// ParseExtractValue
3749 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3750 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3751   Value *Val; LocTy Loc;
3752   SmallVector<unsigned, 4> Indices;
3753   if (ParseTypeAndValue(Val, Loc, PFS) ||
3754       ParseIndexList(Indices))
3755     return true;
3756   if (Lex.getKind() == lltok::NamedOrCustomMD)
3757     if (ParseOptionalCustomMetadata()) return true;
3758
3759   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3760     return Error(Loc, "extractvalue operand must be array or struct");
3761
3762   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3763                                         Indices.end()))
3764     return Error(Loc, "invalid indices for extractvalue");
3765   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3766   return false;
3767 }
3768
3769 /// ParseInsertValue
3770 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3771 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3772   Value *Val0, *Val1; LocTy Loc0, Loc1;
3773   SmallVector<unsigned, 4> Indices;
3774   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3775       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3776       ParseTypeAndValue(Val1, Loc1, PFS) ||
3777       ParseIndexList(Indices))
3778     return true;
3779   if (Lex.getKind() == lltok::NamedOrCustomMD)
3780     if (ParseOptionalCustomMetadata()) return true;
3781
3782   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3783     return Error(Loc0, "extractvalue operand must be array or struct");
3784
3785   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3786                                         Indices.end()))
3787     return Error(Loc0, "invalid indices for insertvalue");
3788   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3789   return false;
3790 }
3791
3792 //===----------------------------------------------------------------------===//
3793 // Embedded metadata.
3794 //===----------------------------------------------------------------------===//
3795
3796 /// ParseMDNodeVector
3797 ///   ::= Element (',' Element)*
3798 /// Element
3799 ///   ::= 'null' | TypeAndValue
3800 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3801   do {
3802     Value *V = 0;
3803     // FIXME: REWRITE.
3804     if (Lex.getKind() == lltok::kw_null) {
3805       Lex.Lex();
3806       V = 0;
3807     } else {
3808       PATypeHolder Ty(Type::getVoidTy(Context));
3809       if (ParseType(Ty)) return true;
3810       if (Lex.getKind() == lltok::Metadata) {
3811         Lex.Lex();
3812         MDNode *Node = 0;
3813         if (!ParseMDNode(Node))
3814           V = Node;
3815         else {
3816           MDString *MDS = 0;
3817           if (ParseMDString(MDS)) return true;
3818           V = MDS;
3819         }
3820       } else {
3821         Constant *C;
3822         if (ParseGlobalValue(Ty, C)) return true;
3823         V = C;
3824       }
3825     }
3826     Elts.push_back(V);
3827   } while (EatIfPresent(lltok::comma));
3828
3829   return false;
3830 }