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