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