0b35335965bab56eb12886f76b27fd4621506773
[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_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
909     case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
910     case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
911     case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
912     case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
913     case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
914     case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
915         
916     case lltok::kw_align: {
917       unsigned Alignment;
918       if (ParseOptionalAlignment(Alignment))
919         return true;
920       Attrs |= Attribute::constructAlignmentFromInt(Alignment);
921       continue;
922     }
923     }
924     Lex.Lex();
925   }
926 }
927
928 /// ParseOptionalLinkage
929 ///   ::= /*empty*/
930 ///   ::= 'private'
931 ///   ::= 'linker_private'
932 ///   ::= 'internal'
933 ///   ::= 'weak'
934 ///   ::= 'weak_odr'
935 ///   ::= 'linkonce'
936 ///   ::= 'linkonce_odr'
937 ///   ::= 'appending'
938 ///   ::= 'dllexport'
939 ///   ::= 'common'
940 ///   ::= 'dllimport'
941 ///   ::= 'extern_weak'
942 ///   ::= 'external'
943 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
944   HasLinkage = false;
945   switch (Lex.getKind()) {
946   default:                       Res=GlobalValue::ExternalLinkage; return false;
947   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
948   case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
949   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
950   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
951   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
952   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
953   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
954   case lltok::kw_available_externally:
955     Res = GlobalValue::AvailableExternallyLinkage;
956     break;
957   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
958   case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
959   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
960   case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
961   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
962   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
963   }
964   Lex.Lex();
965   HasLinkage = true;
966   return false;
967 }
968
969 /// ParseOptionalVisibility
970 ///   ::= /*empty*/
971 ///   ::= 'default'
972 ///   ::= 'hidden'
973 ///   ::= 'protected'
974 /// 
975 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
976   switch (Lex.getKind()) {
977   default:                  Res = GlobalValue::DefaultVisibility; return false;
978   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
979   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
980   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
981   }
982   Lex.Lex();
983   return false;
984 }
985
986 /// ParseOptionalCallingConv
987 ///   ::= /*empty*/
988 ///   ::= 'ccc'
989 ///   ::= 'fastcc'
990 ///   ::= 'coldcc'
991 ///   ::= 'x86_stdcallcc'
992 ///   ::= 'x86_fastcallcc'
993 ///   ::= 'arm_apcscc'
994 ///   ::= 'arm_aapcscc'
995 ///   ::= 'arm_aapcs_vfpcc'
996 ///   ::= 'cc' UINT
997 ///
998 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
999   switch (Lex.getKind()) {
1000   default:                       CC = CallingConv::C; return false;
1001   case lltok::kw_ccc:            CC = CallingConv::C; break;
1002   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1003   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1004   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1005   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1006   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1007   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1008   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1009   case lltok::kw_cc:             Lex.Lex(); return ParseUInt32(CC);
1010   }
1011   Lex.Lex();
1012   return false;
1013 }
1014
1015 /// ParseOptionalAlignment
1016 ///   ::= /* empty */
1017 ///   ::= 'align' 4
1018 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1019   Alignment = 0;
1020   if (!EatIfPresent(lltok::kw_align))
1021     return false;
1022   LocTy AlignLoc = Lex.getLoc();
1023   if (ParseUInt32(Alignment)) return true;
1024   if (!isPowerOf2_32(Alignment))
1025     return Error(AlignLoc, "alignment is not a power of two");
1026   return false;
1027 }
1028
1029 /// ParseOptionalCommaAlignment
1030 ///   ::= /* empty */
1031 ///   ::= ',' 'align' 4
1032 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1033   Alignment = 0;
1034   if (!EatIfPresent(lltok::comma))
1035     return false;
1036   return ParseToken(lltok::kw_align, "expected 'align'") ||
1037          ParseUInt32(Alignment);
1038 }
1039
1040 /// ParseIndexList
1041 ///    ::=  (',' uint32)+
1042 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1043   if (Lex.getKind() != lltok::comma)
1044     return TokError("expected ',' as start of index list");
1045   
1046   while (EatIfPresent(lltok::comma)) {
1047     unsigned Idx;
1048     if (ParseUInt32(Idx)) return true;
1049     Indices.push_back(Idx);
1050   }
1051   
1052   return false;
1053 }
1054
1055 //===----------------------------------------------------------------------===//
1056 // Type Parsing.
1057 //===----------------------------------------------------------------------===//
1058
1059 /// ParseType - Parse and resolve a full type.
1060 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1061   LocTy TypeLoc = Lex.getLoc();
1062   if (ParseTypeRec(Result)) return true;
1063   
1064   // Verify no unresolved uprefs.
1065   if (!UpRefs.empty())
1066     return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1067   
1068   if (!AllowVoid && Result.get() == Type::getVoidTy(Context))
1069     return Error(TypeLoc, "void type only allowed for function results");
1070   
1071   return false;
1072 }
1073
1074 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1075 /// called.  It loops through the UpRefs vector, which is a list of the
1076 /// currently active types.  For each type, if the up-reference is contained in
1077 /// the newly completed type, we decrement the level count.  When the level
1078 /// count reaches zero, the up-referenced type is the type that is passed in:
1079 /// thus we can complete the cycle.
1080 ///
1081 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1082   // If Ty isn't abstract, or if there are no up-references in it, then there is
1083   // nothing to resolve here.
1084   if (!ty->isAbstract() || UpRefs.empty()) return ty;
1085   
1086   PATypeHolder Ty(ty);
1087 #if 0
1088   errs() << "Type '" << Ty->getDescription()
1089          << "' newly formed.  Resolving upreferences.\n"
1090          << UpRefs.size() << " upreferences active!\n";
1091 #endif
1092   
1093   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1094   // to zero), we resolve them all together before we resolve them to Ty.  At
1095   // the end of the loop, if there is anything to resolve to Ty, it will be in
1096   // this variable.
1097   OpaqueType *TypeToResolve = 0;
1098   
1099   for (unsigned i = 0; i != UpRefs.size(); ++i) {
1100     // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1101     bool ContainsType =
1102       std::find(Ty->subtype_begin(), Ty->subtype_end(),
1103                 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1104     
1105 #if 0
1106     errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1107            << UpRefs[i].LastContainedTy->getDescription() << ") = "
1108            << (ContainsType ? "true" : "false")
1109            << " level=" << UpRefs[i].NestingLevel << "\n";
1110 #endif
1111     if (!ContainsType)
1112       continue;
1113     
1114     // Decrement level of upreference
1115     unsigned Level = --UpRefs[i].NestingLevel;
1116     UpRefs[i].LastContainedTy = Ty;
1117     
1118     // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1119     if (Level != 0)
1120       continue;
1121     
1122 #if 0
1123     errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1124 #endif
1125     if (!TypeToResolve)
1126       TypeToResolve = UpRefs[i].UpRefTy;
1127     else
1128       UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1129     UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1130     --i;                                // Do not skip the next element.
1131   }
1132   
1133   if (TypeToResolve)
1134     TypeToResolve->refineAbstractTypeTo(Ty);
1135   
1136   return Ty;
1137 }
1138
1139
1140 /// ParseTypeRec - The recursive function used to process the internal
1141 /// implementation details of types.
1142 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1143   switch (Lex.getKind()) {
1144   default:
1145     return TokError("expected type");
1146   case lltok::Type:
1147     // TypeRec ::= 'float' | 'void' (etc)
1148     Result = Lex.getTyVal();
1149     Lex.Lex(); 
1150     break;
1151   case lltok::kw_opaque:
1152     // TypeRec ::= 'opaque'
1153     Result = OpaqueType::get(Context);
1154     Lex.Lex();
1155     break;
1156   case lltok::lbrace:
1157     // TypeRec ::= '{' ... '}'
1158     if (ParseStructType(Result, false))
1159       return true;
1160     break;
1161   case lltok::lsquare:
1162     // TypeRec ::= '[' ... ']'
1163     Lex.Lex(); // eat the lsquare.
1164     if (ParseArrayVectorType(Result, false))
1165       return true;
1166     break;
1167   case lltok::less: // Either vector or packed struct.
1168     // TypeRec ::= '<' ... '>'
1169     Lex.Lex();
1170     if (Lex.getKind() == lltok::lbrace) {
1171       if (ParseStructType(Result, true) ||
1172           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1173         return true;
1174     } else if (ParseArrayVectorType(Result, true))
1175       return true;
1176     break;
1177   case lltok::LocalVar:
1178   case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1179     // TypeRec ::= %foo
1180     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1181       Result = T;
1182     } else {
1183       Result = OpaqueType::get(Context);
1184       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1185                                             std::make_pair(Result,
1186                                                            Lex.getLoc())));
1187       M->addTypeName(Lex.getStrVal(), Result.get());
1188     }
1189     Lex.Lex();
1190     break;
1191       
1192   case lltok::LocalVarID:
1193     // TypeRec ::= %4
1194     if (Lex.getUIntVal() < NumberedTypes.size())
1195       Result = NumberedTypes[Lex.getUIntVal()];
1196     else {
1197       std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1198         I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1199       if (I != ForwardRefTypeIDs.end())
1200         Result = I->second.first;
1201       else {
1202         Result = OpaqueType::get(Context);
1203         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1204                                                 std::make_pair(Result,
1205                                                                Lex.getLoc())));
1206       }
1207     }
1208     Lex.Lex();
1209     break;
1210   case lltok::backslash: {
1211     // TypeRec ::= '\' 4
1212     Lex.Lex();
1213     unsigned Val;
1214     if (ParseUInt32(Val)) return true;
1215     OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1216     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1217     Result = OT;
1218     break;
1219   }
1220   }
1221   
1222   // Parse the type suffixes. 
1223   while (1) {
1224     switch (Lex.getKind()) {
1225     // End of type.
1226     default: return false;    
1227
1228     // TypeRec ::= TypeRec '*'
1229     case lltok::star:
1230       if (Result.get() == Type::getLabelTy(Context))
1231         return TokError("basic block pointers are invalid");
1232       if (Result.get() == Type::getVoidTy(Context))
1233         return TokError("pointers to void are invalid; use i8* instead");
1234       if (!PointerType::isValidElementType(Result.get()))
1235         return TokError("pointer to this type is invalid");
1236       Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1237       Lex.Lex();
1238       break;
1239
1240     // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1241     case lltok::kw_addrspace: {
1242       if (Result.get() == Type::getLabelTy(Context))
1243         return TokError("basic block pointers are invalid");
1244       if (Result.get() == Type::getVoidTy(Context))
1245         return TokError("pointers to void are invalid; use i8* instead");
1246       if (!PointerType::isValidElementType(Result.get()))
1247         return TokError("pointer to this type is invalid");
1248       unsigned AddrSpace;
1249       if (ParseOptionalAddrSpace(AddrSpace) ||
1250           ParseToken(lltok::star, "expected '*' in address space"))
1251         return true;
1252
1253       Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1254       break;
1255     }
1256         
1257     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1258     case lltok::lparen:
1259       if (ParseFunctionType(Result))
1260         return true;
1261       break;
1262     }
1263   }
1264 }
1265
1266 /// ParseParameterList
1267 ///    ::= '(' ')'
1268 ///    ::= '(' Arg (',' Arg)* ')'
1269 ///  Arg
1270 ///    ::= Type OptionalAttributes Value OptionalAttributes
1271 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1272                                   PerFunctionState &PFS) {
1273   if (ParseToken(lltok::lparen, "expected '(' in call"))
1274     return true;
1275   
1276   while (Lex.getKind() != lltok::rparen) {
1277     // If this isn't the first argument, we need a comma.
1278     if (!ArgList.empty() &&
1279         ParseToken(lltok::comma, "expected ',' in argument list"))
1280       return true;
1281     
1282     // Parse the argument.
1283     LocTy ArgLoc;
1284     PATypeHolder ArgTy(Type::getVoidTy(Context));
1285     unsigned ArgAttrs1, ArgAttrs2;
1286     Value *V;
1287     if (ParseType(ArgTy, ArgLoc) ||
1288         ParseOptionalAttrs(ArgAttrs1, 0) ||
1289         ParseValue(ArgTy, V, PFS) ||
1290         // FIXME: Should not allow attributes after the argument, remove this in
1291         // LLVM 3.0.
1292         ParseOptionalAttrs(ArgAttrs2, 3))
1293       return true;
1294     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1295   }
1296
1297   Lex.Lex();  // Lex the ')'.
1298   return false;
1299 }
1300
1301
1302
1303 /// ParseArgumentList - Parse the argument list for a function type or function
1304 /// prototype.  If 'inType' is true then we are parsing a FunctionType.
1305 ///   ::= '(' ArgTypeListI ')'
1306 /// ArgTypeListI
1307 ///   ::= /*empty*/
1308 ///   ::= '...'
1309 ///   ::= ArgTypeList ',' '...'
1310 ///   ::= ArgType (',' ArgType)*
1311 ///
1312 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1313                                  bool &isVarArg, bool inType) {
1314   isVarArg = false;
1315   assert(Lex.getKind() == lltok::lparen);
1316   Lex.Lex(); // eat the (.
1317   
1318   if (Lex.getKind() == lltok::rparen) {
1319     // empty
1320   } else if (Lex.getKind() == lltok::dotdotdot) {
1321     isVarArg = true;
1322     Lex.Lex();
1323   } else {
1324     LocTy TypeLoc = Lex.getLoc();
1325     PATypeHolder ArgTy(Type::getVoidTy(Context));
1326     unsigned Attrs;
1327     std::string Name;
1328     
1329     // If we're parsing a type, use ParseTypeRec, because we allow recursive
1330     // types (such as a function returning a pointer to itself).  If parsing a
1331     // function prototype, we require fully resolved types.
1332     if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1333         ParseOptionalAttrs(Attrs, 0)) return true;
1334     
1335     if (ArgTy == Type::getVoidTy(Context))
1336       return Error(TypeLoc, "argument can not have void type");
1337     
1338     if (Lex.getKind() == lltok::LocalVar ||
1339         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1340       Name = Lex.getStrVal();
1341       Lex.Lex();
1342     }
1343
1344     if (!FunctionType::isValidArgumentType(ArgTy))
1345       return Error(TypeLoc, "invalid type for function argument");
1346     
1347     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1348     
1349     while (EatIfPresent(lltok::comma)) {
1350       // Handle ... at end of arg list.
1351       if (EatIfPresent(lltok::dotdotdot)) {
1352         isVarArg = true;
1353         break;
1354       }
1355       
1356       // Otherwise must be an argument type.
1357       TypeLoc = Lex.getLoc();
1358       if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1359           ParseOptionalAttrs(Attrs, 0)) return true;
1360
1361       if (ArgTy == Type::getVoidTy(Context))
1362         return Error(TypeLoc, "argument can not have void type");
1363
1364       if (Lex.getKind() == lltok::LocalVar ||
1365           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1366         Name = Lex.getStrVal();
1367         Lex.Lex();
1368       } else {
1369         Name = "";
1370       }
1371
1372       if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1373         return Error(TypeLoc, "invalid type for function argument");
1374       
1375       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1376     }
1377   }
1378   
1379   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1380 }
1381   
1382 /// ParseFunctionType
1383 ///  ::= Type ArgumentList OptionalAttrs
1384 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1385   assert(Lex.getKind() == lltok::lparen);
1386
1387   if (!FunctionType::isValidReturnType(Result))
1388     return TokError("invalid function return type");
1389   
1390   std::vector<ArgInfo> ArgList;
1391   bool isVarArg;
1392   unsigned Attrs;
1393   if (ParseArgumentList(ArgList, isVarArg, true) ||
1394       // FIXME: Allow, but ignore attributes on function types!
1395       // FIXME: Remove in LLVM 3.0
1396       ParseOptionalAttrs(Attrs, 2))
1397     return true;
1398   
1399   // Reject names on the arguments lists.
1400   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1401     if (!ArgList[i].Name.empty())
1402       return Error(ArgList[i].Loc, "argument name invalid in function type");
1403     if (!ArgList[i].Attrs != 0) {
1404       // Allow but ignore attributes on function types; this permits
1405       // auto-upgrade.
1406       // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1407     }
1408   }
1409   
1410   std::vector<const Type*> ArgListTy;
1411   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1412     ArgListTy.push_back(ArgList[i].Type);
1413     
1414   Result = HandleUpRefs(FunctionType::get(Result.get(),
1415                                                 ArgListTy, isVarArg));
1416   return false;
1417 }
1418
1419 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1420 ///   TypeRec
1421 ///     ::= '{' '}'
1422 ///     ::= '{' TypeRec (',' TypeRec)* '}'
1423 ///     ::= '<' '{' '}' '>'
1424 ///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1425 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1426   assert(Lex.getKind() == lltok::lbrace);
1427   Lex.Lex(); // Consume the '{'
1428   
1429   if (EatIfPresent(lltok::rbrace)) {
1430     Result = StructType::get(Context, Packed);
1431     return false;
1432   }
1433
1434   std::vector<PATypeHolder> ParamsList;
1435   LocTy EltTyLoc = Lex.getLoc();
1436   if (ParseTypeRec(Result)) return true;
1437   ParamsList.push_back(Result);
1438   
1439   if (Result == Type::getVoidTy(Context))
1440     return Error(EltTyLoc, "struct element can not have void type");
1441   if (!StructType::isValidElementType(Result))
1442     return Error(EltTyLoc, "invalid element type for struct");
1443   
1444   while (EatIfPresent(lltok::comma)) {
1445     EltTyLoc = Lex.getLoc();
1446     if (ParseTypeRec(Result)) return true;
1447     
1448     if (Result == Type::getVoidTy(Context))
1449       return Error(EltTyLoc, "struct element can not have void type");
1450     if (!StructType::isValidElementType(Result))
1451       return Error(EltTyLoc, "invalid element type for struct");
1452     
1453     ParamsList.push_back(Result);
1454   }
1455   
1456   if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1457     return true;
1458   
1459   std::vector<const Type*> ParamsListTy;
1460   for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1461     ParamsListTy.push_back(ParamsList[i].get());
1462   Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1463   return false;
1464 }
1465
1466 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1467 /// token has already been consumed.
1468 ///   TypeRec 
1469 ///     ::= '[' APSINTVAL 'x' Types ']'
1470 ///     ::= '<' APSINTVAL 'x' Types '>'
1471 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1472   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1473       Lex.getAPSIntVal().getBitWidth() > 64)
1474     return TokError("expected number in address space");
1475   
1476   LocTy SizeLoc = Lex.getLoc();
1477   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1478   Lex.Lex();
1479       
1480   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1481       return true;
1482
1483   LocTy TypeLoc = Lex.getLoc();
1484   PATypeHolder EltTy(Type::getVoidTy(Context));
1485   if (ParseTypeRec(EltTy)) return true;
1486   
1487   if (EltTy == Type::getVoidTy(Context))
1488     return Error(TypeLoc, "array and vector element type cannot be void");
1489
1490   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1491                  "expected end of sequential type"))
1492     return true;
1493   
1494   if (isVector) {
1495     if (Size == 0)
1496       return Error(SizeLoc, "zero element vector is illegal");
1497     if ((unsigned)Size != Size)
1498       return Error(SizeLoc, "size too large for vector");
1499     if (!VectorType::isValidElementType(EltTy))
1500       return Error(TypeLoc, "vector element type must be fp or integer");
1501     Result = VectorType::get(EltTy, unsigned(Size));
1502   } else {
1503     if (!ArrayType::isValidElementType(EltTy))
1504       return Error(TypeLoc, "invalid array element type");
1505     Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1506   }
1507   return false;
1508 }
1509
1510 //===----------------------------------------------------------------------===//
1511 // Function Semantic Analysis.
1512 //===----------------------------------------------------------------------===//
1513
1514 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1515   : P(p), F(f) {
1516
1517   // Insert unnamed arguments into the NumberedVals list.
1518   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1519        AI != E; ++AI)
1520     if (!AI->hasName())
1521       NumberedVals.push_back(AI);
1522 }
1523
1524 LLParser::PerFunctionState::~PerFunctionState() {
1525   // If there were any forward referenced non-basicblock values, delete them.
1526   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1527        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1528     if (!isa<BasicBlock>(I->second.first)) {
1529       I->second.first->replaceAllUsesWith(
1530                            UndefValue::get(I->second.first->getType()));
1531       delete I->second.first;
1532       I->second.first = 0;
1533     }
1534   
1535   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1536        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1537     if (!isa<BasicBlock>(I->second.first)) {
1538       I->second.first->replaceAllUsesWith(
1539                            UndefValue::get(I->second.first->getType()));
1540       delete I->second.first;
1541       I->second.first = 0;
1542     }
1543 }
1544
1545 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1546   if (!ForwardRefVals.empty())
1547     return P.Error(ForwardRefVals.begin()->second.second,
1548                    "use of undefined value '%" + ForwardRefVals.begin()->first +
1549                    "'");
1550   if (!ForwardRefValIDs.empty())
1551     return P.Error(ForwardRefValIDs.begin()->second.second,
1552                    "use of undefined value '%" +
1553                    utostr(ForwardRefValIDs.begin()->first) + "'");
1554   return false;
1555 }
1556
1557
1558 /// GetVal - Get a value with the specified name or ID, creating a
1559 /// forward reference record if needed.  This can return null if the value
1560 /// exists but does not have the right type.
1561 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1562                                           const Type *Ty, LocTy Loc) {
1563   // Look this name up in the normal function symbol table.
1564   Value *Val = F.getValueSymbolTable().lookup(Name);
1565   
1566   // If this is a forward reference for the value, see if we already created a
1567   // forward ref record.
1568   if (Val == 0) {
1569     std::map<std::string, std::pair<Value*, LocTy> >::iterator
1570       I = ForwardRefVals.find(Name);
1571     if (I != ForwardRefVals.end())
1572       Val = I->second.first;
1573   }
1574     
1575   // If we have the value in the symbol table or fwd-ref table, return it.
1576   if (Val) {
1577     if (Val->getType() == Ty) return Val;
1578     if (Ty == Type::getLabelTy(F.getContext()))
1579       P.Error(Loc, "'%" + Name + "' is not a basic block");
1580     else
1581       P.Error(Loc, "'%" + Name + "' defined with type '" +
1582               Val->getType()->getDescription() + "'");
1583     return 0;
1584   }
1585   
1586   // Don't make placeholders with invalid type.
1587   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1588       Ty != Type::getLabelTy(F.getContext())) {
1589     P.Error(Loc, "invalid use of a non-first-class type");
1590     return 0;
1591   }
1592   
1593   // Otherwise, create a new forward reference for this value and remember it.
1594   Value *FwdVal;
1595   if (Ty == Type::getLabelTy(F.getContext())) 
1596     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1597   else
1598     FwdVal = new Argument(Ty, Name);
1599   
1600   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1601   return FwdVal;
1602 }
1603
1604 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1605                                           LocTy Loc) {
1606   // Look this name up in the normal function symbol table.
1607   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1608   
1609   // If this is a forward reference for the value, see if we already created a
1610   // forward ref record.
1611   if (Val == 0) {
1612     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1613       I = ForwardRefValIDs.find(ID);
1614     if (I != ForwardRefValIDs.end())
1615       Val = I->second.first;
1616   }
1617   
1618   // If we have the value in the symbol table or fwd-ref table, return it.
1619   if (Val) {
1620     if (Val->getType() == Ty) return Val;
1621     if (Ty == Type::getLabelTy(F.getContext()))
1622       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1623     else
1624       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1625               Val->getType()->getDescription() + "'");
1626     return 0;
1627   }
1628   
1629   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1630       Ty != Type::getLabelTy(F.getContext())) {
1631     P.Error(Loc, "invalid use of a non-first-class type");
1632     return 0;
1633   }
1634   
1635   // Otherwise, create a new forward reference for this value and remember it.
1636   Value *FwdVal;
1637   if (Ty == Type::getLabelTy(F.getContext())) 
1638     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1639   else
1640     FwdVal = new Argument(Ty);
1641   
1642   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1643   return FwdVal;
1644 }
1645
1646 /// SetInstName - After an instruction is parsed and inserted into its
1647 /// basic block, this installs its name.
1648 bool LLParser::PerFunctionState::SetInstName(int NameID,
1649                                              const std::string &NameStr,
1650                                              LocTy NameLoc, Instruction *Inst) {
1651   // If this instruction has void type, it cannot have a name or ID specified.
1652   if (Inst->getType() == Type::getVoidTy(F.getContext())) {
1653     if (NameID != -1 || !NameStr.empty())
1654       return P.Error(NameLoc, "instructions returning void cannot have a name");
1655     return false;
1656   }
1657   
1658   // If this was a numbered instruction, verify that the instruction is the
1659   // expected value and resolve any forward references.
1660   if (NameStr.empty()) {
1661     // If neither a name nor an ID was specified, just use the next ID.
1662     if (NameID == -1)
1663       NameID = NumberedVals.size();
1664     
1665     if (unsigned(NameID) != NumberedVals.size())
1666       return P.Error(NameLoc, "instruction expected to be numbered '%" +
1667                      utostr(NumberedVals.size()) + "'");
1668     
1669     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1670       ForwardRefValIDs.find(NameID);
1671     if (FI != ForwardRefValIDs.end()) {
1672       if (FI->second.first->getType() != Inst->getType())
1673         return P.Error(NameLoc, "instruction forward referenced with type '" + 
1674                        FI->second.first->getType()->getDescription() + "'");
1675       FI->second.first->replaceAllUsesWith(Inst);
1676       ForwardRefValIDs.erase(FI);
1677     }
1678
1679     NumberedVals.push_back(Inst);
1680     return false;
1681   }
1682
1683   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1684   std::map<std::string, std::pair<Value*, LocTy> >::iterator
1685     FI = ForwardRefVals.find(NameStr);
1686   if (FI != ForwardRefVals.end()) {
1687     if (FI->second.first->getType() != Inst->getType())
1688       return P.Error(NameLoc, "instruction forward referenced with type '" + 
1689                      FI->second.first->getType()->getDescription() + "'");
1690     FI->second.first->replaceAllUsesWith(Inst);
1691     ForwardRefVals.erase(FI);
1692   }
1693   
1694   // Set the name on the instruction.
1695   Inst->setName(NameStr);
1696   
1697   if (Inst->getNameStr() != NameStr)
1698     return P.Error(NameLoc, "multiple definition of local value named '" + 
1699                    NameStr + "'");
1700   return false;
1701 }
1702
1703 /// GetBB - Get a basic block with the specified name or ID, creating a
1704 /// forward reference record if needed.
1705 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1706                                               LocTy Loc) {
1707   return cast_or_null<BasicBlock>(GetVal(Name,
1708                                         Type::getLabelTy(F.getContext()), Loc));
1709 }
1710
1711 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1712   return cast_or_null<BasicBlock>(GetVal(ID,
1713                                         Type::getLabelTy(F.getContext()), Loc));
1714 }
1715
1716 /// DefineBB - Define the specified basic block, which is either named or
1717 /// unnamed.  If there is an error, this returns null otherwise it returns
1718 /// the block being defined.
1719 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1720                                                  LocTy Loc) {
1721   BasicBlock *BB;
1722   if (Name.empty())
1723     BB = GetBB(NumberedVals.size(), Loc);
1724   else
1725     BB = GetBB(Name, Loc);
1726   if (BB == 0) return 0; // Already diagnosed error.
1727   
1728   // Move the block to the end of the function.  Forward ref'd blocks are
1729   // inserted wherever they happen to be referenced.
1730   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1731   
1732   // Remove the block from forward ref sets.
1733   if (Name.empty()) {
1734     ForwardRefValIDs.erase(NumberedVals.size());
1735     NumberedVals.push_back(BB);
1736   } else {
1737     // BB forward references are already in the function symbol table.
1738     ForwardRefVals.erase(Name);
1739   }
1740   
1741   return BB;
1742 }
1743
1744 //===----------------------------------------------------------------------===//
1745 // Constants.
1746 //===----------------------------------------------------------------------===//
1747
1748 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1749 /// type implied.  For example, if we parse "4" we don't know what integer type
1750 /// it has.  The value will later be combined with its type and checked for
1751 /// sanity.
1752 bool LLParser::ParseValID(ValID &ID) {
1753   ID.Loc = Lex.getLoc();
1754   switch (Lex.getKind()) {
1755   default: return TokError("expected value token");
1756   case lltok::GlobalID:  // @42
1757     ID.UIntVal = Lex.getUIntVal();
1758     ID.Kind = ValID::t_GlobalID;
1759     break;
1760   case lltok::GlobalVar:  // @foo
1761     ID.StrVal = Lex.getStrVal();
1762     ID.Kind = ValID::t_GlobalName;
1763     break;
1764   case lltok::LocalVarID:  // %42
1765     ID.UIntVal = Lex.getUIntVal();
1766     ID.Kind = ValID::t_LocalID;
1767     break;
1768   case lltok::LocalVar:  // %foo
1769   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1770     ID.StrVal = Lex.getStrVal();
1771     ID.Kind = ValID::t_LocalName;
1772     break;
1773   case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1774     ID.Kind = ValID::t_Metadata;
1775     Lex.Lex();
1776     if (Lex.getKind() == lltok::lbrace) {
1777       SmallVector<Value*, 16> Elts;
1778       if (ParseMDNodeVector(Elts) ||
1779           ParseToken(lltok::rbrace, "expected end of metadata node"))
1780         return true;
1781
1782       ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1783       return false;
1784     }
1785
1786     // Standalone metadata reference
1787     // !{ ..., !42, ... }
1788     if (!ParseMDNode(ID.MetadataVal))
1789       return false;
1790
1791     // MDString:
1792     //   ::= '!' STRINGCONSTANT
1793     if (ParseMDString(ID.MetadataVal)) return true;
1794     ID.Kind = ValID::t_Metadata;
1795     return false;
1796   }
1797   case lltok::APSInt:
1798     ID.APSIntVal = Lex.getAPSIntVal(); 
1799     ID.Kind = ValID::t_APSInt;
1800     break;
1801   case lltok::APFloat:
1802     ID.APFloatVal = Lex.getAPFloatVal();
1803     ID.Kind = ValID::t_APFloat;
1804     break;
1805   case lltok::kw_true:
1806     ID.ConstantVal = ConstantInt::getTrue(Context);
1807     ID.Kind = ValID::t_Constant;
1808     break;
1809   case lltok::kw_false:
1810     ID.ConstantVal = ConstantInt::getFalse(Context);
1811     ID.Kind = ValID::t_Constant;
1812     break;
1813   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1814   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1815   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1816       
1817   case lltok::lbrace: {
1818     // ValID ::= '{' ConstVector '}'
1819     Lex.Lex();
1820     SmallVector<Constant*, 16> Elts;
1821     if (ParseGlobalValueVector(Elts) ||
1822         ParseToken(lltok::rbrace, "expected end of struct constant"))
1823       return true;
1824     
1825     ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1826                                          Elts.size(), false);
1827     ID.Kind = ValID::t_Constant;
1828     return false;
1829   }
1830   case lltok::less: {
1831     // ValID ::= '<' ConstVector '>'         --> Vector.
1832     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1833     Lex.Lex();
1834     bool isPackedStruct = EatIfPresent(lltok::lbrace);
1835     
1836     SmallVector<Constant*, 16> Elts;
1837     LocTy FirstEltLoc = Lex.getLoc();
1838     if (ParseGlobalValueVector(Elts) ||
1839         (isPackedStruct &&
1840          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1841         ParseToken(lltok::greater, "expected end of constant"))
1842       return true;
1843     
1844     if (isPackedStruct) {
1845       ID.ConstantVal =
1846         ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1847       ID.Kind = ValID::t_Constant;
1848       return false;
1849     }
1850     
1851     if (Elts.empty())
1852       return Error(ID.Loc, "constant vector must not be empty");
1853
1854     if (!Elts[0]->getType()->isInteger() &&
1855         !Elts[0]->getType()->isFloatingPoint())
1856       return Error(FirstEltLoc,
1857                    "vector elements must have integer or floating point type");
1858     
1859     // Verify that all the vector elements have the same type.
1860     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1861       if (Elts[i]->getType() != Elts[0]->getType())
1862         return Error(FirstEltLoc,
1863                      "vector element #" + utostr(i) +
1864                     " is not of type '" + Elts[0]->getType()->getDescription());
1865     
1866     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1867     ID.Kind = ValID::t_Constant;
1868     return false;
1869   }
1870   case lltok::lsquare: {   // Array Constant
1871     Lex.Lex();
1872     SmallVector<Constant*, 16> Elts;
1873     LocTy FirstEltLoc = Lex.getLoc();
1874     if (ParseGlobalValueVector(Elts) ||
1875         ParseToken(lltok::rsquare, "expected end of array constant"))
1876       return true;
1877
1878     // Handle empty element.
1879     if (Elts.empty()) {
1880       // Use undef instead of an array because it's inconvenient to determine
1881       // the element type at this point, there being no elements to examine.
1882       ID.Kind = ValID::t_EmptyArray;
1883       return false;
1884     }
1885     
1886     if (!Elts[0]->getType()->isFirstClassType())
1887       return Error(FirstEltLoc, "invalid array element type: " + 
1888                    Elts[0]->getType()->getDescription());
1889           
1890     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1891     
1892     // Verify all elements are correct type!
1893     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1894       if (Elts[i]->getType() != Elts[0]->getType())
1895         return Error(FirstEltLoc,
1896                      "array element #" + utostr(i) +
1897                      " is not of type '" +Elts[0]->getType()->getDescription());
1898     }
1899     
1900     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1901     ID.Kind = ValID::t_Constant;
1902     return false;
1903   }
1904   case lltok::kw_c:  // c "foo"
1905     Lex.Lex();
1906     ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
1907     if (ParseToken(lltok::StringConstant, "expected string")) return true;
1908     ID.Kind = ValID::t_Constant;
1909     return false;
1910
1911   case lltok::kw_asm: {
1912     // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1913     bool HasSideEffect;
1914     Lex.Lex();
1915     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1916         ParseStringConstant(ID.StrVal) ||
1917         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1918         ParseToken(lltok::StringConstant, "expected constraint string"))
1919       return true;
1920     ID.StrVal2 = Lex.getStrVal();
1921     ID.UIntVal = HasSideEffect;
1922     ID.Kind = ValID::t_InlineAsm;
1923     return false;
1924   }
1925       
1926   case lltok::kw_trunc:
1927   case lltok::kw_zext:
1928   case lltok::kw_sext:
1929   case lltok::kw_fptrunc:
1930   case lltok::kw_fpext:
1931   case lltok::kw_bitcast:
1932   case lltok::kw_uitofp:
1933   case lltok::kw_sitofp:
1934   case lltok::kw_fptoui:
1935   case lltok::kw_fptosi: 
1936   case lltok::kw_inttoptr:
1937   case lltok::kw_ptrtoint: { 
1938     unsigned Opc = Lex.getUIntVal();
1939     PATypeHolder DestTy(Type::getVoidTy(Context));
1940     Constant *SrcVal;
1941     Lex.Lex();
1942     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1943         ParseGlobalTypeAndValue(SrcVal) ||
1944         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1945         ParseType(DestTy) ||
1946         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1947       return true;
1948     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1949       return Error(ID.Loc, "invalid cast opcode for cast from '" +
1950                    SrcVal->getType()->getDescription() + "' to '" +
1951                    DestTy->getDescription() + "'");
1952     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 
1953                                                  SrcVal, DestTy);
1954     ID.Kind = ValID::t_Constant;
1955     return false;
1956   }
1957   case lltok::kw_extractvalue: {
1958     Lex.Lex();
1959     Constant *Val;
1960     SmallVector<unsigned, 4> Indices;
1961     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1962         ParseGlobalTypeAndValue(Val) ||
1963         ParseIndexList(Indices) ||
1964         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1965       return true;
1966     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1967       return Error(ID.Loc, "extractvalue operand must be array or struct");
1968     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1969                                           Indices.end()))
1970       return Error(ID.Loc, "invalid indices for extractvalue");
1971     ID.ConstantVal =
1972       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
1973     ID.Kind = ValID::t_Constant;
1974     return false;
1975   }
1976   case lltok::kw_insertvalue: {
1977     Lex.Lex();
1978     Constant *Val0, *Val1;
1979     SmallVector<unsigned, 4> Indices;
1980     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1981         ParseGlobalTypeAndValue(Val0) ||
1982         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1983         ParseGlobalTypeAndValue(Val1) ||
1984         ParseIndexList(Indices) ||
1985         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1986       return true;
1987     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1988       return Error(ID.Loc, "extractvalue operand must be array or struct");
1989     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1990                                           Indices.end()))
1991       return Error(ID.Loc, "invalid indices for insertvalue");
1992     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1993                        Indices.data(), Indices.size());
1994     ID.Kind = ValID::t_Constant;
1995     return false;
1996   }
1997   case lltok::kw_icmp:
1998   case lltok::kw_fcmp: {
1999     unsigned PredVal, Opc = Lex.getUIntVal();
2000     Constant *Val0, *Val1;
2001     Lex.Lex();
2002     if (ParseCmpPredicate(PredVal, Opc) ||
2003         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2004         ParseGlobalTypeAndValue(Val0) ||
2005         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2006         ParseGlobalTypeAndValue(Val1) ||
2007         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2008       return true;
2009     
2010     if (Val0->getType() != Val1->getType())
2011       return Error(ID.Loc, "compare operands must have the same type");
2012     
2013     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2014     
2015     if (Opc == Instruction::FCmp) {
2016       if (!Val0->getType()->isFPOrFPVector())
2017         return Error(ID.Loc, "fcmp requires floating point operands");
2018       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2019     } else {
2020       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2021       if (!Val0->getType()->isIntOrIntVector() &&
2022           !isa<PointerType>(Val0->getType()))
2023         return Error(ID.Loc, "icmp requires pointer or integer operands");
2024       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2025     }
2026     ID.Kind = ValID::t_Constant;
2027     return false;
2028   }
2029       
2030   // Binary Operators.
2031   case lltok::kw_add:
2032   case lltok::kw_fadd:
2033   case lltok::kw_sub:
2034   case lltok::kw_fsub:
2035   case lltok::kw_mul:
2036   case lltok::kw_fmul:
2037   case lltok::kw_udiv:
2038   case lltok::kw_sdiv:
2039   case lltok::kw_fdiv:
2040   case lltok::kw_urem:
2041   case lltok::kw_srem:
2042   case lltok::kw_frem: {
2043     bool NUW = false;
2044     bool NSW = false;
2045     bool Exact = false;
2046     unsigned Opc = Lex.getUIntVal();
2047     Constant *Val0, *Val1;
2048     Lex.Lex();
2049     LocTy ModifierLoc = Lex.getLoc();
2050     if (Opc == Instruction::Add ||
2051         Opc == Instruction::Sub ||
2052         Opc == Instruction::Mul) {
2053       if (EatIfPresent(lltok::kw_nuw))
2054         NUW = true;
2055       if (EatIfPresent(lltok::kw_nsw)) {
2056         NSW = true;
2057         if (EatIfPresent(lltok::kw_nuw))
2058           NUW = true;
2059       }
2060     } else if (Opc == Instruction::SDiv) {
2061       if (EatIfPresent(lltok::kw_exact))
2062         Exact = true;
2063     }
2064     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2065         ParseGlobalTypeAndValue(Val0) ||
2066         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2067         ParseGlobalTypeAndValue(Val1) ||
2068         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2069       return true;
2070     if (Val0->getType() != Val1->getType())
2071       return Error(ID.Loc, "operands of constexpr must have same type");
2072     if (!Val0->getType()->isIntOrIntVector()) {
2073       if (NUW)
2074         return Error(ModifierLoc, "nuw only applies to integer operations");
2075       if (NSW)
2076         return Error(ModifierLoc, "nsw only applies to integer operations");
2077     }
2078     // API compatibility: Accept either integer or floating-point types with
2079     // add, sub, and mul.
2080     if (!Val0->getType()->isIntOrIntVector() &&
2081         !Val0->getType()->isFPOrFPVector())
2082       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2083     Constant *C = ConstantExpr::get(Opc, Val0, Val1);
2084     if (NUW)
2085       cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedWrap(true);
2086     if (NSW)
2087       cast<OverflowingBinaryOperator>(C)->setHasNoSignedWrap(true);
2088     if (Exact)
2089       cast<SDivOperator>(C)->setIsExact(true);
2090     ID.ConstantVal = C;
2091     ID.Kind = ValID::t_Constant;
2092     return false;
2093   }
2094       
2095   // Logical Operations
2096   case lltok::kw_shl:
2097   case lltok::kw_lshr:
2098   case lltok::kw_ashr:
2099   case lltok::kw_and:
2100   case lltok::kw_or:
2101   case lltok::kw_xor: {
2102     unsigned Opc = Lex.getUIntVal();
2103     Constant *Val0, *Val1;
2104     Lex.Lex();
2105     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2106         ParseGlobalTypeAndValue(Val0) ||
2107         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2108         ParseGlobalTypeAndValue(Val1) ||
2109         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2110       return true;
2111     if (Val0->getType() != Val1->getType())
2112       return Error(ID.Loc, "operands of constexpr must have same type");
2113     if (!Val0->getType()->isIntOrIntVector())
2114       return Error(ID.Loc,
2115                    "constexpr requires integer or integer vector operands");
2116     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2117     ID.Kind = ValID::t_Constant;
2118     return false;
2119   }  
2120       
2121   case lltok::kw_getelementptr:
2122   case lltok::kw_shufflevector:
2123   case lltok::kw_insertelement:
2124   case lltok::kw_extractelement:
2125   case lltok::kw_select: {
2126     unsigned Opc = Lex.getUIntVal();
2127     SmallVector<Constant*, 16> Elts;
2128     bool InBounds = false;
2129     Lex.Lex();
2130     if (Opc == Instruction::GetElementPtr)
2131       InBounds = EatIfPresent(lltok::kw_inbounds);
2132     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2133         ParseGlobalValueVector(Elts) ||
2134         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2135       return true;
2136     
2137     if (Opc == Instruction::GetElementPtr) {
2138       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2139         return Error(ID.Loc, "getelementptr requires pointer operand");
2140       
2141       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2142                                              (Value**)(Elts.data() + 1),
2143                                              Elts.size() - 1))
2144         return Error(ID.Loc, "invalid indices for getelementptr");
2145       ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
2146                                               Elts.data() + 1, Elts.size() - 1);
2147       if (InBounds)
2148         cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
2149     } else if (Opc == Instruction::Select) {
2150       if (Elts.size() != 3)
2151         return Error(ID.Loc, "expected three operands to select");
2152       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2153                                                               Elts[2]))
2154         return Error(ID.Loc, Reason);
2155       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2156     } else if (Opc == Instruction::ShuffleVector) {
2157       if (Elts.size() != 3)
2158         return Error(ID.Loc, "expected three operands to shufflevector");
2159       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2160         return Error(ID.Loc, "invalid operands to shufflevector");
2161       ID.ConstantVal =
2162                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2163     } else if (Opc == Instruction::ExtractElement) {
2164       if (Elts.size() != 2)
2165         return Error(ID.Loc, "expected two operands to extractelement");
2166       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2167         return Error(ID.Loc, "invalid extractelement operands");
2168       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2169     } else {
2170       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2171       if (Elts.size() != 3)
2172       return Error(ID.Loc, "expected three operands to insertelement");
2173       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2174         return Error(ID.Loc, "invalid insertelement operands");
2175       ID.ConstantVal =
2176                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2177     }
2178     
2179     ID.Kind = ValID::t_Constant;
2180     return false;
2181   }
2182   }
2183   
2184   Lex.Lex();
2185   return false;
2186 }
2187
2188 /// ParseGlobalValue - Parse a global value with the specified type.
2189 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2190   V = 0;
2191   ValID ID;
2192   return ParseValID(ID) ||
2193          ConvertGlobalValIDToValue(Ty, ID, V);
2194 }
2195
2196 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2197 /// constant.
2198 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2199                                          Constant *&V) {
2200   if (isa<FunctionType>(Ty))
2201     return Error(ID.Loc, "functions are not values, refer to them as pointers");
2202   
2203   switch (ID.Kind) {
2204   default: llvm_unreachable("Unknown ValID!");    
2205   case ValID::t_Metadata:
2206     return Error(ID.Loc, "invalid use of metadata");
2207   case ValID::t_LocalID:
2208   case ValID::t_LocalName:
2209     return Error(ID.Loc, "invalid use of function-local name");
2210   case ValID::t_InlineAsm:
2211     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2212   case ValID::t_GlobalName:
2213     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2214     return V == 0;
2215   case ValID::t_GlobalID:
2216     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2217     return V == 0;
2218   case ValID::t_APSInt:
2219     if (!isa<IntegerType>(Ty))
2220       return Error(ID.Loc, "integer constant must have integer type");
2221     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2222     V = ConstantInt::get(Context, ID.APSIntVal);
2223     return false;
2224   case ValID::t_APFloat:
2225     if (!Ty->isFloatingPoint() ||
2226         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2227       return Error(ID.Loc, "floating point constant invalid for type");
2228       
2229     // The lexer has no type info, so builds all float and double FP constants
2230     // as double.  Fix this here.  Long double does not need this.
2231     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2232         Ty == Type::getFloatTy(Context)) {
2233       bool Ignored;
2234       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2235                             &Ignored);
2236     }
2237     V = ConstantFP::get(Context, ID.APFloatVal);
2238       
2239     if (V->getType() != Ty)
2240       return Error(ID.Loc, "floating point constant does not have type '" +
2241                    Ty->getDescription() + "'");
2242       
2243     return false;
2244   case ValID::t_Null:
2245     if (!isa<PointerType>(Ty))
2246       return Error(ID.Loc, "null must be a pointer type");
2247     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2248     return false;
2249   case ValID::t_Undef:
2250     // FIXME: LabelTy should not be a first-class type.
2251     if ((!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context)) &&
2252         !isa<OpaqueType>(Ty))
2253       return Error(ID.Loc, "invalid type for undef constant");
2254     V = UndefValue::get(Ty);
2255     return false;
2256   case ValID::t_EmptyArray:
2257     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2258       return Error(ID.Loc, "invalid empty array initializer");
2259     V = UndefValue::get(Ty);
2260     return false;
2261   case ValID::t_Zero:
2262     // FIXME: LabelTy should not be a first-class type.
2263     if (!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context))
2264       return Error(ID.Loc, "invalid type for null constant");
2265     V = Constant::getNullValue(Ty);
2266     return false;
2267   case ValID::t_Constant:
2268     if (ID.ConstantVal->getType() != Ty)
2269       return Error(ID.Loc, "constant expression type mismatch");
2270     V = ID.ConstantVal;
2271     return false;
2272   }
2273 }
2274   
2275 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2276   PATypeHolder Type(Type::getVoidTy(Context));
2277   return ParseType(Type) ||
2278          ParseGlobalValue(Type, V);
2279 }    
2280
2281 /// ParseGlobalValueVector
2282 ///   ::= /*empty*/
2283 ///   ::= TypeAndValue (',' TypeAndValue)*
2284 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2285   // Empty list.
2286   if (Lex.getKind() == lltok::rbrace ||
2287       Lex.getKind() == lltok::rsquare ||
2288       Lex.getKind() == lltok::greater ||
2289       Lex.getKind() == lltok::rparen)
2290     return false;
2291   
2292   Constant *C;
2293   if (ParseGlobalTypeAndValue(C)) return true;
2294   Elts.push_back(C);
2295   
2296   while (EatIfPresent(lltok::comma)) {
2297     if (ParseGlobalTypeAndValue(C)) return true;
2298     Elts.push_back(C);
2299   }
2300   
2301   return false;
2302 }
2303
2304
2305 //===----------------------------------------------------------------------===//
2306 // Function Parsing.
2307 //===----------------------------------------------------------------------===//
2308
2309 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2310                                    PerFunctionState &PFS) {
2311   if (ID.Kind == ValID::t_LocalID)
2312     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2313   else if (ID.Kind == ValID::t_LocalName)
2314     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2315   else if (ID.Kind == ValID::t_InlineAsm) {
2316     const PointerType *PTy = dyn_cast<PointerType>(Ty);
2317     const FunctionType *FTy =
2318       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2319     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2320       return Error(ID.Loc, "invalid type for inline asm constraint string");
2321     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2322     return false;
2323   } else if (ID.Kind == ValID::t_Metadata) {
2324     V = ID.MetadataVal;
2325   } else {
2326     Constant *C;
2327     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2328     V = C;
2329     return false;
2330   }
2331
2332   return V == 0;
2333 }
2334
2335 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2336   V = 0;
2337   ValID ID;
2338   return ParseValID(ID) ||
2339          ConvertValIDToValue(Ty, ID, V, PFS);
2340 }
2341
2342 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2343   PATypeHolder T(Type::getVoidTy(Context));
2344   return ParseType(T) ||
2345          ParseValue(T, V, PFS);
2346 }
2347
2348 /// FunctionHeader
2349 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2350 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2351 ///       OptionalAlign OptGC
2352 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2353   // Parse the linkage.
2354   LocTy LinkageLoc = Lex.getLoc();
2355   unsigned Linkage;
2356   
2357   unsigned Visibility, CC, RetAttrs;
2358   PATypeHolder RetType(Type::getVoidTy(Context));
2359   LocTy RetTypeLoc = Lex.getLoc();
2360   if (ParseOptionalLinkage(Linkage) ||
2361       ParseOptionalVisibility(Visibility) ||
2362       ParseOptionalCallingConv(CC) ||
2363       ParseOptionalAttrs(RetAttrs, 1) ||
2364       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2365     return true;
2366
2367   // Verify that the linkage is ok.
2368   switch ((GlobalValue::LinkageTypes)Linkage) {
2369   case GlobalValue::ExternalLinkage:
2370     break; // always ok.
2371   case GlobalValue::DLLImportLinkage:
2372   case GlobalValue::ExternalWeakLinkage:
2373     if (isDefine)
2374       return Error(LinkageLoc, "invalid linkage for function definition");
2375     break;
2376   case GlobalValue::PrivateLinkage:
2377   case GlobalValue::LinkerPrivateLinkage:
2378   case GlobalValue::InternalLinkage:
2379   case GlobalValue::AvailableExternallyLinkage:
2380   case GlobalValue::LinkOnceAnyLinkage:
2381   case GlobalValue::LinkOnceODRLinkage:
2382   case GlobalValue::WeakAnyLinkage:
2383   case GlobalValue::WeakODRLinkage:
2384   case GlobalValue::DLLExportLinkage:
2385     if (!isDefine)
2386       return Error(LinkageLoc, "invalid linkage for function declaration");
2387     break;
2388   case GlobalValue::AppendingLinkage:
2389   case GlobalValue::GhostLinkage:
2390   case GlobalValue::CommonLinkage:
2391     return Error(LinkageLoc, "invalid function linkage type");
2392   }
2393   
2394   if (!FunctionType::isValidReturnType(RetType) ||
2395       isa<OpaqueType>(RetType))
2396     return Error(RetTypeLoc, "invalid function return type");
2397   
2398   LocTy NameLoc = Lex.getLoc();
2399
2400   std::string FunctionName;
2401   if (Lex.getKind() == lltok::GlobalVar) {
2402     FunctionName = Lex.getStrVal();
2403   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2404     unsigned NameID = Lex.getUIntVal();
2405
2406     if (NameID != NumberedVals.size())
2407       return TokError("function expected to be numbered '%" +
2408                       utostr(NumberedVals.size()) + "'");
2409   } else {
2410     return TokError("expected function name");
2411   }
2412   
2413   Lex.Lex();
2414   
2415   if (Lex.getKind() != lltok::lparen)
2416     return TokError("expected '(' in function argument list");
2417   
2418   std::vector<ArgInfo> ArgList;
2419   bool isVarArg;
2420   unsigned FuncAttrs;
2421   std::string Section;
2422   unsigned Alignment;
2423   std::string GC;
2424
2425   if (ParseArgumentList(ArgList, isVarArg, false) ||
2426       ParseOptionalAttrs(FuncAttrs, 2) ||
2427       (EatIfPresent(lltok::kw_section) &&
2428        ParseStringConstant(Section)) ||
2429       ParseOptionalAlignment(Alignment) ||
2430       (EatIfPresent(lltok::kw_gc) &&
2431        ParseStringConstant(GC)))
2432     return true;
2433
2434   // If the alignment was parsed as an attribute, move to the alignment field.
2435   if (FuncAttrs & Attribute::Alignment) {
2436     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2437     FuncAttrs &= ~Attribute::Alignment;
2438   }
2439   
2440   // Okay, if we got here, the function is syntactically valid.  Convert types
2441   // and do semantic checks.
2442   std::vector<const Type*> ParamTypeList;
2443   SmallVector<AttributeWithIndex, 8> Attrs;
2444   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
2445   // attributes.
2446   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2447   if (FuncAttrs & ObsoleteFuncAttrs) {
2448     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2449     FuncAttrs &= ~ObsoleteFuncAttrs;
2450   }
2451   
2452   if (RetAttrs != Attribute::None)
2453     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2454   
2455   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2456     ParamTypeList.push_back(ArgList[i].Type);
2457     if (ArgList[i].Attrs != Attribute::None)
2458       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2459   }
2460
2461   if (FuncAttrs != Attribute::None)
2462     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2463
2464   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2465   
2466   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2467       RetType != Type::getVoidTy(Context))
2468     return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 
2469   
2470   const FunctionType *FT =
2471     FunctionType::get(RetType, ParamTypeList, isVarArg);
2472   const PointerType *PFT = PointerType::getUnqual(FT);
2473
2474   Fn = 0;
2475   if (!FunctionName.empty()) {
2476     // If this was a definition of a forward reference, remove the definition
2477     // from the forward reference table and fill in the forward ref.
2478     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2479       ForwardRefVals.find(FunctionName);
2480     if (FRVI != ForwardRefVals.end()) {
2481       Fn = M->getFunction(FunctionName);
2482       ForwardRefVals.erase(FRVI);
2483     } else if ((Fn = M->getFunction(FunctionName))) {
2484       // If this function already exists in the symbol table, then it is
2485       // multiply defined.  We accept a few cases for old backwards compat.
2486       // FIXME: Remove this stuff for LLVM 3.0.
2487       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2488           (!Fn->isDeclaration() && isDefine)) {
2489         // If the redefinition has different type or different attributes,
2490         // reject it.  If both have bodies, reject it.
2491         return Error(NameLoc, "invalid redefinition of function '" +
2492                      FunctionName + "'");
2493       } else if (Fn->isDeclaration()) {
2494         // Make sure to strip off any argument names so we can't get conflicts.
2495         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2496              AI != AE; ++AI)
2497           AI->setName("");
2498       }
2499     }
2500     
2501   } else if (FunctionName.empty()) {
2502     // If this is a definition of a forward referenced function, make sure the
2503     // types agree.
2504     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2505       = ForwardRefValIDs.find(NumberedVals.size());
2506     if (I != ForwardRefValIDs.end()) {
2507       Fn = cast<Function>(I->second.first);
2508       if (Fn->getType() != PFT)
2509         return Error(NameLoc, "type of definition and forward reference of '@" +
2510                      utostr(NumberedVals.size()) +"' disagree");
2511       ForwardRefValIDs.erase(I);
2512     }
2513   }
2514
2515   if (Fn == 0)
2516     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2517   else // Move the forward-reference to the correct spot in the module.
2518     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2519
2520   if (FunctionName.empty())
2521     NumberedVals.push_back(Fn);
2522   
2523   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2524   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2525   Fn->setCallingConv(CC);
2526   Fn->setAttributes(PAL);
2527   Fn->setAlignment(Alignment);
2528   Fn->setSection(Section);
2529   if (!GC.empty()) Fn->setGC(GC.c_str());
2530     
2531   // Add all of the arguments we parsed to the function.
2532   Function::arg_iterator ArgIt = Fn->arg_begin();
2533   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2534     // If the argument has a name, insert it into the argument symbol table.
2535     if (ArgList[i].Name.empty()) continue;
2536     
2537     // Set the name, if it conflicted, it will be auto-renamed.
2538     ArgIt->setName(ArgList[i].Name);
2539     
2540     if (ArgIt->getNameStr() != ArgList[i].Name)
2541       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2542                    ArgList[i].Name + "'");
2543   }
2544   
2545   return false;
2546 }
2547
2548
2549 /// ParseFunctionBody
2550 ///   ::= '{' BasicBlock+ '}'
2551 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2552 ///
2553 bool LLParser::ParseFunctionBody(Function &Fn) {
2554   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2555     return TokError("expected '{' in function body");
2556   Lex.Lex();  // eat the {.
2557   
2558   PerFunctionState PFS(*this, Fn);
2559   
2560   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2561     if (ParseBasicBlock(PFS)) return true;
2562   
2563   // Eat the }.
2564   Lex.Lex();
2565   
2566   // Verify function is ok.
2567   return PFS.VerifyFunctionComplete();
2568 }
2569
2570 /// ParseBasicBlock
2571 ///   ::= LabelStr? Instruction*
2572 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2573   // If this basic block starts out with a name, remember it.
2574   std::string Name;
2575   LocTy NameLoc = Lex.getLoc();
2576   if (Lex.getKind() == lltok::LabelStr) {
2577     Name = Lex.getStrVal();
2578     Lex.Lex();
2579   }
2580   
2581   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2582   if (BB == 0) return true;
2583   
2584   std::string NameStr;
2585   
2586   // Parse the instructions in this block until we get a terminator.
2587   Instruction *Inst;
2588   do {
2589     // This instruction may have three possibilities for a name: a) none
2590     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2591     LocTy NameLoc = Lex.getLoc();
2592     int NameID = -1;
2593     NameStr = "";
2594     
2595     if (Lex.getKind() == lltok::LocalVarID) {
2596       NameID = Lex.getUIntVal();
2597       Lex.Lex();
2598       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2599         return true;
2600     } else if (Lex.getKind() == lltok::LocalVar ||
2601                // FIXME: REMOVE IN LLVM 3.0
2602                Lex.getKind() == lltok::StringConstant) {
2603       NameStr = Lex.getStrVal();
2604       Lex.Lex();
2605       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2606         return true;
2607     }
2608     
2609     if (ParseInstruction(Inst, BB, PFS)) return true;
2610     
2611     BB->getInstList().push_back(Inst);
2612
2613     // Set the name on the instruction.
2614     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2615   } while (!isa<TerminatorInst>(Inst));
2616   
2617   return false;
2618 }
2619
2620 //===----------------------------------------------------------------------===//
2621 // Instruction Parsing.
2622 //===----------------------------------------------------------------------===//
2623
2624 /// ParseInstruction - Parse one of the many different instructions.
2625 ///
2626 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2627                                 PerFunctionState &PFS) {
2628   lltok::Kind Token = Lex.getKind();
2629   if (Token == lltok::Eof)
2630     return TokError("found end of file when expecting more instructions");
2631   LocTy Loc = Lex.getLoc();
2632   unsigned KeywordVal = Lex.getUIntVal();
2633   Lex.Lex();  // Eat the keyword.
2634   
2635   switch (Token) {
2636   default:                    return Error(Loc, "expected instruction opcode");
2637   // Terminator Instructions.
2638   case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
2639   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2640   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2641   case lltok::kw_br:          return ParseBr(Inst, PFS);
2642   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2643   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2644   // Binary Operators.
2645   case lltok::kw_add:
2646   case lltok::kw_sub:
2647   case lltok::kw_mul: {
2648     bool NUW = false;
2649     bool NSW = false;
2650     LocTy ModifierLoc = Lex.getLoc();
2651     if (EatIfPresent(lltok::kw_nuw))
2652       NUW = true;
2653     if (EatIfPresent(lltok::kw_nsw)) {
2654       NSW = true;
2655       if (EatIfPresent(lltok::kw_nuw))
2656         NUW = true;
2657     }
2658     // API compatibility: Accept either integer or floating-point types.
2659     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2660     if (!Result) {
2661       if (!Inst->getType()->isIntOrIntVector()) {
2662         if (NUW)
2663           return Error(ModifierLoc, "nuw only applies to integer operations");
2664         if (NSW)
2665           return Error(ModifierLoc, "nsw only applies to integer operations");
2666       }
2667       if (NUW)
2668         cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2669       if (NSW)
2670         cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedWrap(true);
2671     }
2672     return Result;
2673   }
2674   case lltok::kw_fadd:
2675   case lltok::kw_fsub:
2676   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2677
2678   case lltok::kw_sdiv: {
2679     bool Exact = false;
2680     if (EatIfPresent(lltok::kw_exact))
2681       Exact = true;
2682     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2683     if (!Result)
2684       if (Exact)
2685         cast<SDivOperator>(Inst)->setIsExact(true);
2686     return Result;
2687   }
2688
2689   case lltok::kw_udiv:
2690   case lltok::kw_urem:
2691   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2692   case lltok::kw_fdiv:
2693   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2694   case lltok::kw_shl:
2695   case lltok::kw_lshr:
2696   case lltok::kw_ashr:
2697   case lltok::kw_and:
2698   case lltok::kw_or:
2699   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2700   case lltok::kw_icmp:
2701   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2702   // Casts.
2703   case lltok::kw_trunc:
2704   case lltok::kw_zext:
2705   case lltok::kw_sext:
2706   case lltok::kw_fptrunc:
2707   case lltok::kw_fpext:
2708   case lltok::kw_bitcast:
2709   case lltok::kw_uitofp:
2710   case lltok::kw_sitofp:
2711   case lltok::kw_fptoui:
2712   case lltok::kw_fptosi: 
2713   case lltok::kw_inttoptr:
2714   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2715   // Other.
2716   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2717   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2718   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2719   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2720   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2721   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2722   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2723   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2724   // Memory.
2725   case lltok::kw_alloca:
2726   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
2727   case lltok::kw_free:           return ParseFree(Inst, PFS);
2728   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2729   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2730   case lltok::kw_volatile:
2731     if (EatIfPresent(lltok::kw_load))
2732       return ParseLoad(Inst, PFS, true);
2733     else if (EatIfPresent(lltok::kw_store))
2734       return ParseStore(Inst, PFS, true);
2735     else
2736       return TokError("expected 'load' or 'store'");
2737   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2738   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2739   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2740   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2741   }
2742 }
2743
2744 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2745 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2746   if (Opc == Instruction::FCmp) {
2747     switch (Lex.getKind()) {
2748     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2749     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2750     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2751     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2752     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2753     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2754     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2755     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2756     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2757     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2758     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2759     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2760     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2761     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2762     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2763     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2764     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2765     }
2766   } else {
2767     switch (Lex.getKind()) {
2768     default: TokError("expected icmp predicate (e.g. 'eq')");
2769     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2770     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2771     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2772     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2773     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2774     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2775     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2776     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2777     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2778     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2779     }
2780   }
2781   Lex.Lex();
2782   return false;
2783 }
2784
2785 //===----------------------------------------------------------------------===//
2786 // Terminator Instructions.
2787 //===----------------------------------------------------------------------===//
2788
2789 /// ParseRet - Parse a return instruction.
2790 ///   ::= 'ret' void
2791 ///   ::= 'ret' TypeAndValue
2792 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  [[obsolete: LLVM 3.0]]
2793 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2794                         PerFunctionState &PFS) {
2795   PATypeHolder Ty(Type::getVoidTy(Context));
2796   if (ParseType(Ty, true /*void allowed*/)) return true;
2797   
2798   if (Ty == Type::getVoidTy(Context)) {
2799     Inst = ReturnInst::Create(Context);
2800     return false;
2801   }
2802   
2803   Value *RV;
2804   if (ParseValue(Ty, RV, PFS)) return true;
2805   
2806   // The normal case is one return value.
2807   if (Lex.getKind() == lltok::comma) {
2808     // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2809     // of 'ret {i32,i32} {i32 1, i32 2}'
2810     SmallVector<Value*, 8> RVs;
2811     RVs.push_back(RV);
2812     
2813     while (EatIfPresent(lltok::comma)) {
2814       if (ParseTypeAndValue(RV, PFS)) return true;
2815       RVs.push_back(RV);
2816     }
2817
2818     RV = UndefValue::get(PFS.getFunction().getReturnType());
2819     for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2820       Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2821       BB->getInstList().push_back(I);
2822       RV = I;
2823     }
2824   }
2825   Inst = ReturnInst::Create(Context, RV);
2826   return false;
2827 }
2828
2829
2830 /// ParseBr
2831 ///   ::= 'br' TypeAndValue
2832 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2833 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2834   LocTy Loc, Loc2;
2835   Value *Op0, *Op1, *Op2;
2836   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2837   
2838   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2839     Inst = BranchInst::Create(BB);
2840     return false;
2841   }
2842   
2843   if (Op0->getType() != Type::getInt1Ty(Context))
2844     return Error(Loc, "branch condition must have 'i1' type");
2845     
2846   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2847       ParseTypeAndValue(Op1, Loc, PFS) ||
2848       ParseToken(lltok::comma, "expected ',' after true destination") ||
2849       ParseTypeAndValue(Op2, Loc2, PFS))
2850     return true;
2851   
2852   if (!isa<BasicBlock>(Op1))
2853     return Error(Loc, "true destination of branch must be a basic block");
2854   if (!isa<BasicBlock>(Op2))
2855     return Error(Loc2, "true destination of branch must be a basic block");
2856     
2857   Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2858   return false;
2859 }
2860
2861 /// ParseSwitch
2862 ///  Instruction
2863 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2864 ///  JumpTable
2865 ///    ::= (TypeAndValue ',' TypeAndValue)*
2866 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2867   LocTy CondLoc, BBLoc;
2868   Value *Cond, *DefaultBB;
2869   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2870       ParseToken(lltok::comma, "expected ',' after switch condition") ||
2871       ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2872       ParseToken(lltok::lsquare, "expected '[' with switch table"))
2873     return true;
2874
2875   if (!isa<IntegerType>(Cond->getType()))
2876     return Error(CondLoc, "switch condition must have integer type");
2877   if (!isa<BasicBlock>(DefaultBB))
2878     return Error(BBLoc, "default destination must be a basic block");
2879   
2880   // Parse the jump table pairs.
2881   SmallPtrSet<Value*, 32> SeenCases;
2882   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2883   while (Lex.getKind() != lltok::rsquare) {
2884     Value *Constant, *DestBB;
2885     
2886     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2887         ParseToken(lltok::comma, "expected ',' after case value") ||
2888         ParseTypeAndValue(DestBB, BBLoc, PFS))
2889       return true;
2890
2891     if (!SeenCases.insert(Constant))
2892       return Error(CondLoc, "duplicate case value in switch");
2893     if (!isa<ConstantInt>(Constant))
2894       return Error(CondLoc, "case value is not a constant integer");
2895     if (!isa<BasicBlock>(DestBB))
2896       return Error(BBLoc, "case destination is not a basic block");
2897     
2898     Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2899                                    cast<BasicBlock>(DestBB)));
2900   }
2901   
2902   Lex.Lex();  // Eat the ']'.
2903   
2904   SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2905                                       Table.size());
2906   for (unsigned i = 0, e = Table.size(); i != e; ++i)
2907     SI->addCase(Table[i].first, Table[i].second);
2908   Inst = SI;
2909   return false;
2910 }
2911
2912 /// ParseInvoke
2913 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2914 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2915 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2916   LocTy CallLoc = Lex.getLoc();
2917   unsigned CC, RetAttrs, FnAttrs;
2918   PATypeHolder RetType(Type::getVoidTy(Context));
2919   LocTy RetTypeLoc;
2920   ValID CalleeID;
2921   SmallVector<ParamInfo, 16> ArgList;
2922
2923   Value *NormalBB, *UnwindBB;
2924   if (ParseOptionalCallingConv(CC) ||
2925       ParseOptionalAttrs(RetAttrs, 1) ||
2926       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2927       ParseValID(CalleeID) ||
2928       ParseParameterList(ArgList, PFS) ||
2929       ParseOptionalAttrs(FnAttrs, 2) ||
2930       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2931       ParseTypeAndValue(NormalBB, PFS) ||
2932       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2933       ParseTypeAndValue(UnwindBB, PFS))
2934     return true;
2935   
2936   if (!isa<BasicBlock>(NormalBB))
2937     return Error(CallLoc, "normal destination is not a basic block");
2938   if (!isa<BasicBlock>(UnwindBB))
2939     return Error(CallLoc, "unwind destination is not a basic block");
2940   
2941   // If RetType is a non-function pointer type, then this is the short syntax
2942   // for the call, which means that RetType is just the return type.  Infer the
2943   // rest of the function argument types from the arguments that are present.
2944   const PointerType *PFTy = 0;
2945   const FunctionType *Ty = 0;
2946   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2947       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2948     // Pull out the types of all of the arguments...
2949     std::vector<const Type*> ParamTypes;
2950     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2951       ParamTypes.push_back(ArgList[i].V->getType());
2952     
2953     if (!FunctionType::isValidReturnType(RetType))
2954       return Error(RetTypeLoc, "Invalid result type for LLVM function");
2955     
2956     Ty = FunctionType::get(RetType, ParamTypes, false);
2957     PFTy = PointerType::getUnqual(Ty);
2958   }
2959   
2960   // Look up the callee.
2961   Value *Callee;
2962   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2963   
2964   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2965   // function attributes.
2966   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2967   if (FnAttrs & ObsoleteFuncAttrs) {
2968     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2969     FnAttrs &= ~ObsoleteFuncAttrs;
2970   }
2971   
2972   // Set up the Attributes for the function.
2973   SmallVector<AttributeWithIndex, 8> Attrs;
2974   if (RetAttrs != Attribute::None)
2975     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2976   
2977   SmallVector<Value*, 8> Args;
2978   
2979   // Loop through FunctionType's arguments and ensure they are specified
2980   // correctly.  Also, gather any parameter attributes.
2981   FunctionType::param_iterator I = Ty->param_begin();
2982   FunctionType::param_iterator E = Ty->param_end();
2983   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2984     const Type *ExpectedTy = 0;
2985     if (I != E) {
2986       ExpectedTy = *I++;
2987     } else if (!Ty->isVarArg()) {
2988       return Error(ArgList[i].Loc, "too many arguments specified");
2989     }
2990     
2991     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2992       return Error(ArgList[i].Loc, "argument is not of expected type '" +
2993                    ExpectedTy->getDescription() + "'");
2994     Args.push_back(ArgList[i].V);
2995     if (ArgList[i].Attrs != Attribute::None)
2996       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2997   }
2998   
2999   if (I != E)
3000     return Error(CallLoc, "not enough parameters specified for call");
3001   
3002   if (FnAttrs != Attribute::None)
3003     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3004   
3005   // Finish off the Attributes and check them
3006   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3007   
3008   InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3009                                       cast<BasicBlock>(UnwindBB),
3010                                       Args.begin(), Args.end());
3011   II->setCallingConv(CC);
3012   II->setAttributes(PAL);
3013   Inst = II;
3014   return false;
3015 }
3016
3017
3018
3019 //===----------------------------------------------------------------------===//
3020 // Binary Operators.
3021 //===----------------------------------------------------------------------===//
3022
3023 /// ParseArithmetic
3024 ///  ::= ArithmeticOps TypeAndValue ',' Value
3025 ///
3026 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3027 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3028 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3029                                unsigned Opc, unsigned OperandType) {
3030   LocTy Loc; Value *LHS, *RHS;
3031   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3032       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3033       ParseValue(LHS->getType(), RHS, PFS))
3034     return true;
3035
3036   bool Valid;
3037   switch (OperandType) {
3038   default: llvm_unreachable("Unknown operand type!");
3039   case 0: // int or FP.
3040     Valid = LHS->getType()->isIntOrIntVector() ||
3041             LHS->getType()->isFPOrFPVector();
3042     break;
3043   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3044   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3045   }
3046   
3047   if (!Valid)
3048     return Error(Loc, "invalid operand type for instruction");
3049   
3050   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3051   return false;
3052 }
3053
3054 /// ParseLogical
3055 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3056 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3057                             unsigned Opc) {
3058   LocTy Loc; Value *LHS, *RHS;
3059   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3060       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3061       ParseValue(LHS->getType(), RHS, PFS))
3062     return true;
3063
3064   if (!LHS->getType()->isIntOrIntVector())
3065     return Error(Loc,"instruction requires integer or integer vector operands");
3066
3067   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3068   return false;
3069 }
3070
3071
3072 /// ParseCompare
3073 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3074 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3075 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3076                             unsigned Opc) {
3077   // Parse the integer/fp comparison predicate.
3078   LocTy Loc;
3079   unsigned Pred;
3080   Value *LHS, *RHS;
3081   if (ParseCmpPredicate(Pred, Opc) ||
3082       ParseTypeAndValue(LHS, Loc, PFS) ||
3083       ParseToken(lltok::comma, "expected ',' after compare value") ||
3084       ParseValue(LHS->getType(), RHS, PFS))
3085     return true;
3086   
3087   if (Opc == Instruction::FCmp) {
3088     if (!LHS->getType()->isFPOrFPVector())
3089       return Error(Loc, "fcmp requires floating point operands");
3090     Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3091   } else {
3092     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3093     if (!LHS->getType()->isIntOrIntVector() &&
3094         !isa<PointerType>(LHS->getType()))
3095       return Error(Loc, "icmp requires integer operands");
3096     Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3097   }
3098   return false;
3099 }
3100
3101 //===----------------------------------------------------------------------===//
3102 // Other Instructions.
3103 //===----------------------------------------------------------------------===//
3104
3105
3106 /// ParseCast
3107 ///   ::= CastOpc TypeAndValue 'to' Type
3108 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3109                          unsigned Opc) {
3110   LocTy Loc;  Value *Op;
3111   PATypeHolder DestTy(Type::getVoidTy(Context));
3112   if (ParseTypeAndValue(Op, Loc, PFS) ||
3113       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3114       ParseType(DestTy))
3115     return true;
3116   
3117   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3118     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3119     return Error(Loc, "invalid cast opcode for cast from '" +
3120                  Op->getType()->getDescription() + "' to '" +
3121                  DestTy->getDescription() + "'");
3122   }
3123   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3124   return false;
3125 }
3126
3127 /// ParseSelect
3128 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3129 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3130   LocTy Loc;
3131   Value *Op0, *Op1, *Op2;
3132   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3133       ParseToken(lltok::comma, "expected ',' after select condition") ||
3134       ParseTypeAndValue(Op1, PFS) ||
3135       ParseToken(lltok::comma, "expected ',' after select value") ||
3136       ParseTypeAndValue(Op2, PFS))
3137     return true;
3138   
3139   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3140     return Error(Loc, Reason);
3141   
3142   Inst = SelectInst::Create(Op0, Op1, Op2);
3143   return false;
3144 }
3145
3146 /// ParseVA_Arg
3147 ///   ::= 'va_arg' TypeAndValue ',' Type
3148 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3149   Value *Op;
3150   PATypeHolder EltTy(Type::getVoidTy(Context));
3151   LocTy TypeLoc;
3152   if (ParseTypeAndValue(Op, PFS) ||
3153       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3154       ParseType(EltTy, TypeLoc))
3155     return true;
3156   
3157   if (!EltTy->isFirstClassType())
3158     return Error(TypeLoc, "va_arg requires operand with first class type");
3159
3160   Inst = new VAArgInst(Op, EltTy);
3161   return false;
3162 }
3163
3164 /// ParseExtractElement
3165 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3166 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3167   LocTy Loc;
3168   Value *Op0, *Op1;
3169   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3170       ParseToken(lltok::comma, "expected ',' after extract value") ||
3171       ParseTypeAndValue(Op1, PFS))
3172     return true;
3173   
3174   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3175     return Error(Loc, "invalid extractelement operands");
3176   
3177   Inst = ExtractElementInst::Create(Op0, Op1);
3178   return false;
3179 }
3180
3181 /// ParseInsertElement
3182 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3183 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3184   LocTy Loc;
3185   Value *Op0, *Op1, *Op2;
3186   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3187       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3188       ParseTypeAndValue(Op1, PFS) ||
3189       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3190       ParseTypeAndValue(Op2, PFS))
3191     return true;
3192   
3193   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3194     return Error(Loc, "invalid insertelement operands");
3195   
3196   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3197   return false;
3198 }
3199
3200 /// ParseShuffleVector
3201 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3202 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3203   LocTy Loc;
3204   Value *Op0, *Op1, *Op2;
3205   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3206       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3207       ParseTypeAndValue(Op1, PFS) ||
3208       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3209       ParseTypeAndValue(Op2, PFS))
3210     return true;
3211   
3212   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3213     return Error(Loc, "invalid extractelement operands");
3214   
3215   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3216   return false;
3217 }
3218
3219 /// ParsePHI
3220 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3221 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3222   PATypeHolder Ty(Type::getVoidTy(Context));
3223   Value *Op0, *Op1;
3224   LocTy TypeLoc = Lex.getLoc();
3225   
3226   if (ParseType(Ty) ||
3227       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3228       ParseValue(Ty, Op0, PFS) ||
3229       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3230       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3231       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3232     return true;
3233  
3234   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3235   while (1) {
3236     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3237     
3238     if (!EatIfPresent(lltok::comma))
3239       break;
3240
3241     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3242         ParseValue(Ty, Op0, PFS) ||
3243         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3244         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3245         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3246       return true;
3247   }
3248   
3249   if (!Ty->isFirstClassType())
3250     return Error(TypeLoc, "phi node must have first class type");
3251
3252   PHINode *PN = PHINode::Create(Ty);
3253   PN->reserveOperandSpace(PHIVals.size());
3254   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3255     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3256   Inst = PN;
3257   return false;
3258 }
3259
3260 /// ParseCall
3261 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3262 ///       ParameterList OptionalAttrs
3263 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3264                          bool isTail) {
3265   unsigned CC, RetAttrs, FnAttrs;
3266   PATypeHolder RetType(Type::getVoidTy(Context));
3267   LocTy RetTypeLoc;
3268   ValID CalleeID;
3269   SmallVector<ParamInfo, 16> ArgList;
3270   LocTy CallLoc = Lex.getLoc();
3271   
3272   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3273       ParseOptionalCallingConv(CC) ||
3274       ParseOptionalAttrs(RetAttrs, 1) ||
3275       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3276       ParseValID(CalleeID) ||
3277       ParseParameterList(ArgList, PFS) ||
3278       ParseOptionalAttrs(FnAttrs, 2))
3279     return true;
3280   
3281   // If RetType is a non-function pointer type, then this is the short syntax
3282   // for the call, which means that RetType is just the return type.  Infer the
3283   // rest of the function argument types from the arguments that are present.
3284   const PointerType *PFTy = 0;
3285   const FunctionType *Ty = 0;
3286   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3287       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3288     // Pull out the types of all of the arguments...
3289     std::vector<const Type*> ParamTypes;
3290     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3291       ParamTypes.push_back(ArgList[i].V->getType());
3292     
3293     if (!FunctionType::isValidReturnType(RetType))
3294       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3295     
3296     Ty = FunctionType::get(RetType, ParamTypes, false);
3297     PFTy = PointerType::getUnqual(Ty);
3298   }
3299   
3300   // Look up the callee.
3301   Value *Callee;
3302   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3303   
3304   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3305   // function attributes.
3306   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3307   if (FnAttrs & ObsoleteFuncAttrs) {
3308     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3309     FnAttrs &= ~ObsoleteFuncAttrs;
3310   }
3311
3312   // Set up the Attributes for the function.
3313   SmallVector<AttributeWithIndex, 8> Attrs;
3314   if (RetAttrs != Attribute::None)
3315     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3316   
3317   SmallVector<Value*, 8> Args;
3318   
3319   // Loop through FunctionType's arguments and ensure they are specified
3320   // correctly.  Also, gather any parameter attributes.
3321   FunctionType::param_iterator I = Ty->param_begin();
3322   FunctionType::param_iterator E = Ty->param_end();
3323   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3324     const Type *ExpectedTy = 0;
3325     if (I != E) {
3326       ExpectedTy = *I++;
3327     } else if (!Ty->isVarArg()) {
3328       return Error(ArgList[i].Loc, "too many arguments specified");
3329     }
3330     
3331     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3332       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3333                    ExpectedTy->getDescription() + "'");
3334     Args.push_back(ArgList[i].V);
3335     if (ArgList[i].Attrs != Attribute::None)
3336       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3337   }
3338   
3339   if (I != E)
3340     return Error(CallLoc, "not enough parameters specified for call");
3341
3342   if (FnAttrs != Attribute::None)
3343     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3344
3345   // Finish off the Attributes and check them
3346   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3347   
3348   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3349   CI->setTailCall(isTail);
3350   CI->setCallingConv(CC);
3351   CI->setAttributes(PAL);
3352   Inst = CI;
3353   return false;
3354 }
3355
3356 //===----------------------------------------------------------------------===//
3357 // Memory Instructions.
3358 //===----------------------------------------------------------------------===//
3359
3360 /// ParseAlloc
3361 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3362 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3363 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3364                           unsigned Opc) {
3365   PATypeHolder Ty(Type::getVoidTy(Context));
3366   Value *Size = 0;
3367   LocTy SizeLoc;
3368   unsigned Alignment = 0;
3369   if (ParseType(Ty)) return true;
3370
3371   if (EatIfPresent(lltok::comma)) {
3372     if (Lex.getKind() == lltok::kw_align) {
3373       if (ParseOptionalAlignment(Alignment)) return true;
3374     } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3375                ParseOptionalCommaAlignment(Alignment)) {
3376       return true;
3377     }
3378   }
3379
3380   if (Size && Size->getType() != Type::getInt32Ty(Context))
3381     return Error(SizeLoc, "element count must be i32");
3382
3383   if (Opc == Instruction::Malloc)
3384     Inst = new MallocInst(Ty, Size, Alignment);
3385   else
3386     Inst = new AllocaInst(Ty, Size, Alignment);
3387   return false;
3388 }
3389
3390 /// ParseFree
3391 ///   ::= 'free' TypeAndValue
3392 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3393   Value *Val; LocTy Loc;
3394   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3395   if (!isa<PointerType>(Val->getType()))
3396     return Error(Loc, "operand to free must be a pointer");
3397   Inst = new FreeInst(Val);
3398   return false;
3399 }
3400
3401 /// ParseLoad
3402 ///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3403 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3404                          bool isVolatile) {
3405   Value *Val; LocTy Loc;
3406   unsigned Alignment;
3407   if (ParseTypeAndValue(Val, Loc, PFS) ||
3408       ParseOptionalCommaAlignment(Alignment))
3409     return true;
3410
3411   if (!isa<PointerType>(Val->getType()) ||
3412       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3413     return Error(Loc, "load operand must be a pointer to a first class type");
3414   
3415   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3416   return false;
3417 }
3418
3419 /// ParseStore
3420 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3421 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3422                           bool isVolatile) {
3423   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3424   unsigned Alignment;
3425   if (ParseTypeAndValue(Val, Loc, PFS) ||
3426       ParseToken(lltok::comma, "expected ',' after store operand") ||
3427       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3428       ParseOptionalCommaAlignment(Alignment))
3429     return true;
3430   
3431   if (!isa<PointerType>(Ptr->getType()))
3432     return Error(PtrLoc, "store operand must be a pointer");
3433   if (!Val->getType()->isFirstClassType())
3434     return Error(Loc, "store operand must be a first class value");
3435   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3436     return Error(Loc, "stored value and pointer type do not match");
3437   
3438   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3439   return false;
3440 }
3441
3442 /// ParseGetResult
3443 ///   ::= 'getresult' TypeAndValue ',' i32
3444 /// FIXME: Remove support for getresult in LLVM 3.0
3445 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3446   Value *Val; LocTy ValLoc, EltLoc;
3447   unsigned Element;
3448   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3449       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3450       ParseUInt32(Element, EltLoc))
3451     return true;
3452   
3453   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3454     return Error(ValLoc, "getresult inst requires an aggregate operand");
3455   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3456     return Error(EltLoc, "invalid getresult index for value");
3457   Inst = ExtractValueInst::Create(Val, Element);
3458   return false;
3459 }
3460
3461 /// ParseGetElementPtr
3462 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3463 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3464   Value *Ptr, *Val; LocTy Loc, EltLoc;
3465
3466   bool InBounds = EatIfPresent(lltok::kw_inbounds);
3467
3468   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3469   
3470   if (!isa<PointerType>(Ptr->getType()))
3471     return Error(Loc, "base of getelementptr must be a pointer");
3472   
3473   SmallVector<Value*, 16> Indices;
3474   while (EatIfPresent(lltok::comma)) {
3475     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3476     if (!isa<IntegerType>(Val->getType()))
3477       return Error(EltLoc, "getelementptr index must be an integer");
3478     Indices.push_back(Val);
3479   }
3480   
3481   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3482                                          Indices.begin(), Indices.end()))
3483     return Error(Loc, "invalid getelementptr indices");
3484   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3485   if (InBounds)
3486     cast<GEPOperator>(Inst)->setIsInBounds(true);
3487   return false;
3488 }
3489
3490 /// ParseExtractValue
3491 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3492 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3493   Value *Val; LocTy Loc;
3494   SmallVector<unsigned, 4> Indices;
3495   if (ParseTypeAndValue(Val, Loc, PFS) ||
3496       ParseIndexList(Indices))
3497     return true;
3498
3499   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3500     return Error(Loc, "extractvalue operand must be array or struct");
3501
3502   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3503                                         Indices.end()))
3504     return Error(Loc, "invalid indices for extractvalue");
3505   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3506   return false;
3507 }
3508
3509 /// ParseInsertValue
3510 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3511 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3512   Value *Val0, *Val1; LocTy Loc0, Loc1;
3513   SmallVector<unsigned, 4> Indices;
3514   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3515       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3516       ParseTypeAndValue(Val1, Loc1, PFS) ||
3517       ParseIndexList(Indices))
3518     return true;
3519   
3520   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3521     return Error(Loc0, "extractvalue operand must be array or struct");
3522   
3523   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3524                                         Indices.end()))
3525     return Error(Loc0, "invalid indices for insertvalue");
3526   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3527   return false;
3528 }
3529
3530 //===----------------------------------------------------------------------===//
3531 // Embedded metadata.
3532 //===----------------------------------------------------------------------===//
3533
3534 /// ParseMDNodeVector
3535 ///   ::= Element (',' Element)*
3536 /// Element
3537 ///   ::= 'null' | TypeAndValue
3538 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3539   assert(Lex.getKind() == lltok::lbrace);
3540   Lex.Lex();
3541   do {
3542     Value *V = 0;
3543     if (Lex.getKind() == lltok::kw_null) {
3544       Lex.Lex();
3545       V = 0;
3546     } else {
3547       PATypeHolder Ty(Type::getVoidTy(Context));
3548       if (ParseType(Ty)) return true;
3549       if (Lex.getKind() == lltok::Metadata) {
3550         Lex.Lex();
3551         MetadataBase *Node = 0;
3552         if (!ParseMDNode(Node))
3553           V = Node;
3554         else {
3555           MetadataBase *MDS = 0;
3556           if (ParseMDString(MDS)) return true;
3557           V = MDS;
3558         }
3559       } else {
3560         Constant *C;
3561         if (ParseGlobalValue(Ty, C)) return true;
3562         V = C;
3563       }
3564     }
3565     Elts.push_back(V);
3566   } while (EatIfPresent(lltok::comma));
3567
3568   return false;
3569 }