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