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