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