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