ab686ced9b07952abafdb5acc49e128ddaea3445
[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::VoidTy);
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::VoidTy);
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(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::VoidTy);
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::VoidTy);
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::LabelTy)
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::VoidTy)
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();
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();
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();
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(); //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::LabelTy)
1231         return TokError("basic block pointers are invalid");
1232       if (Result.get() == Type::VoidTy)
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::LabelTy)
1243         return TokError("basic block pointers are invalid");
1244       if (Result.get() == Type::VoidTy)
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::VoidTy);
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::VoidTy);
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::VoidTy)
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::VoidTy)
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::VoidTy)
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::VoidTy)
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::VoidTy);
1485   if (ParseTypeRec(EltTy)) return true;
1486   
1487   if (EltTy == Type::VoidTy)
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::LabelTy)
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) && Ty != Type::LabelTy) {
1588     P.Error(Loc, "invalid use of a non-first-class type");
1589     return 0;
1590   }
1591   
1592   // Otherwise, create a new forward reference for this value and remember it.
1593   Value *FwdVal;
1594   if (Ty == Type::LabelTy) 
1595     FwdVal = BasicBlock::Create(Name, &F);
1596   else
1597     FwdVal = new Argument(Ty, Name);
1598   
1599   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1600   return FwdVal;
1601 }
1602
1603 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1604                                           LocTy Loc) {
1605   // Look this name up in the normal function symbol table.
1606   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1607   
1608   // If this is a forward reference for the value, see if we already created a
1609   // forward ref record.
1610   if (Val == 0) {
1611     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1612       I = ForwardRefValIDs.find(ID);
1613     if (I != ForwardRefValIDs.end())
1614       Val = I->second.first;
1615   }
1616   
1617   // If we have the value in the symbol table or fwd-ref table, return it.
1618   if (Val) {
1619     if (Val->getType() == Ty) return Val;
1620     if (Ty == Type::LabelTy)
1621       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1622     else
1623       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1624               Val->getType()->getDescription() + "'");
1625     return 0;
1626   }
1627   
1628   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1629     P.Error(Loc, "invalid use of a non-first-class type");
1630     return 0;
1631   }
1632   
1633   // Otherwise, create a new forward reference for this value and remember it.
1634   Value *FwdVal;
1635   if (Ty == Type::LabelTy) 
1636     FwdVal = BasicBlock::Create("", &F);
1637   else
1638     FwdVal = new Argument(Ty);
1639   
1640   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1641   return FwdVal;
1642 }
1643
1644 /// SetInstName - After an instruction is parsed and inserted into its
1645 /// basic block, this installs its name.
1646 bool LLParser::PerFunctionState::SetInstName(int NameID,
1647                                              const std::string &NameStr,
1648                                              LocTy NameLoc, Instruction *Inst) {
1649   // If this instruction has void type, it cannot have a name or ID specified.
1650   if (Inst->getType() == Type::VoidTy) {
1651     if (NameID != -1 || !NameStr.empty())
1652       return P.Error(NameLoc, "instructions returning void cannot have a name");
1653     return false;
1654   }
1655   
1656   // If this was a numbered instruction, verify that the instruction is the
1657   // expected value and resolve any forward references.
1658   if (NameStr.empty()) {
1659     // If neither a name nor an ID was specified, just use the next ID.
1660     if (NameID == -1)
1661       NameID = NumberedVals.size();
1662     
1663     if (unsigned(NameID) != NumberedVals.size())
1664       return P.Error(NameLoc, "instruction expected to be numbered '%" +
1665                      utostr(NumberedVals.size()) + "'");
1666     
1667     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1668       ForwardRefValIDs.find(NameID);
1669     if (FI != ForwardRefValIDs.end()) {
1670       if (FI->second.first->getType() != Inst->getType())
1671         return P.Error(NameLoc, "instruction forward referenced with type '" + 
1672                        FI->second.first->getType()->getDescription() + "'");
1673       FI->second.first->replaceAllUsesWith(Inst);
1674       ForwardRefValIDs.erase(FI);
1675     }
1676
1677     NumberedVals.push_back(Inst);
1678     return false;
1679   }
1680
1681   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1682   std::map<std::string, std::pair<Value*, LocTy> >::iterator
1683     FI = ForwardRefVals.find(NameStr);
1684   if (FI != ForwardRefVals.end()) {
1685     if (FI->second.first->getType() != Inst->getType())
1686       return P.Error(NameLoc, "instruction forward referenced with type '" + 
1687                      FI->second.first->getType()->getDescription() + "'");
1688     FI->second.first->replaceAllUsesWith(Inst);
1689     ForwardRefVals.erase(FI);
1690   }
1691   
1692   // Set the name on the instruction.
1693   Inst->setName(NameStr);
1694   
1695   if (Inst->getNameStr() != NameStr)
1696     return P.Error(NameLoc, "multiple definition of local value named '" + 
1697                    NameStr + "'");
1698   return false;
1699 }
1700
1701 /// GetBB - Get a basic block with the specified name or ID, creating a
1702 /// forward reference record if needed.
1703 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1704                                               LocTy Loc) {
1705   return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1706 }
1707
1708 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1709   return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1710 }
1711
1712 /// DefineBB - Define the specified basic block, which is either named or
1713 /// unnamed.  If there is an error, this returns null otherwise it returns
1714 /// the block being defined.
1715 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1716                                                  LocTy Loc) {
1717   BasicBlock *BB;
1718   if (Name.empty())
1719     BB = GetBB(NumberedVals.size(), Loc);
1720   else
1721     BB = GetBB(Name, Loc);
1722   if (BB == 0) return 0; // Already diagnosed error.
1723   
1724   // Move the block to the end of the function.  Forward ref'd blocks are
1725   // inserted wherever they happen to be referenced.
1726   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1727   
1728   // Remove the block from forward ref sets.
1729   if (Name.empty()) {
1730     ForwardRefValIDs.erase(NumberedVals.size());
1731     NumberedVals.push_back(BB);
1732   } else {
1733     // BB forward references are already in the function symbol table.
1734     ForwardRefVals.erase(Name);
1735   }
1736   
1737   return BB;
1738 }
1739
1740 //===----------------------------------------------------------------------===//
1741 // Constants.
1742 //===----------------------------------------------------------------------===//
1743
1744 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1745 /// type implied.  For example, if we parse "4" we don't know what integer type
1746 /// it has.  The value will later be combined with its type and checked for
1747 /// sanity.
1748 bool LLParser::ParseValID(ValID &ID) {
1749   ID.Loc = Lex.getLoc();
1750   switch (Lex.getKind()) {
1751   default: return TokError("expected value token");
1752   case lltok::GlobalID:  // @42
1753     ID.UIntVal = Lex.getUIntVal();
1754     ID.Kind = ValID::t_GlobalID;
1755     break;
1756   case lltok::GlobalVar:  // @foo
1757     ID.StrVal = Lex.getStrVal();
1758     ID.Kind = ValID::t_GlobalName;
1759     break;
1760   case lltok::LocalVarID:  // %42
1761     ID.UIntVal = Lex.getUIntVal();
1762     ID.Kind = ValID::t_LocalID;
1763     break;
1764   case lltok::LocalVar:  // %foo
1765   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1766     ID.StrVal = Lex.getStrVal();
1767     ID.Kind = ValID::t_LocalName;
1768     break;
1769   case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1770     ID.Kind = ValID::t_Metadata;
1771     Lex.Lex();
1772     if (Lex.getKind() == lltok::lbrace) {
1773       SmallVector<Value*, 16> Elts;
1774       if (ParseMDNodeVector(Elts) ||
1775           ParseToken(lltok::rbrace, "expected end of metadata node"))
1776         return true;
1777
1778       ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1779       return false;
1780     }
1781
1782     // Standalone metadata reference
1783     // !{ ..., !42, ... }
1784     if (!ParseMDNode(ID.MetadataVal))
1785       return false;
1786
1787     // MDString:
1788     //   ::= '!' STRINGCONSTANT
1789     if (ParseMDString(ID.MetadataVal)) return true;
1790     ID.Kind = ValID::t_Metadata;
1791     return false;
1792   }
1793   case lltok::APSInt:
1794     ID.APSIntVal = Lex.getAPSIntVal(); 
1795     ID.Kind = ValID::t_APSInt;
1796     break;
1797   case lltok::APFloat:
1798     ID.APFloatVal = Lex.getAPFloatVal();
1799     ID.Kind = ValID::t_APFloat;
1800     break;
1801   case lltok::kw_true:
1802     ID.ConstantVal = ConstantInt::getTrue(Context);
1803     ID.Kind = ValID::t_Constant;
1804     break;
1805   case lltok::kw_false:
1806     ID.ConstantVal = ConstantInt::getFalse(Context);
1807     ID.Kind = ValID::t_Constant;
1808     break;
1809   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1810   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1811   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1812       
1813   case lltok::lbrace: {
1814     // ValID ::= '{' ConstVector '}'
1815     Lex.Lex();
1816     SmallVector<Constant*, 16> Elts;
1817     if (ParseGlobalValueVector(Elts) ||
1818         ParseToken(lltok::rbrace, "expected end of struct constant"))
1819       return true;
1820     
1821     ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1822                                          Elts.size(), false);
1823     ID.Kind = ValID::t_Constant;
1824     return false;
1825   }
1826   case lltok::less: {
1827     // ValID ::= '<' ConstVector '>'         --> Vector.
1828     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1829     Lex.Lex();
1830     bool isPackedStruct = EatIfPresent(lltok::lbrace);
1831     
1832     SmallVector<Constant*, 16> Elts;
1833     LocTy FirstEltLoc = Lex.getLoc();
1834     if (ParseGlobalValueVector(Elts) ||
1835         (isPackedStruct &&
1836          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1837         ParseToken(lltok::greater, "expected end of constant"))
1838       return true;
1839     
1840     if (isPackedStruct) {
1841       ID.ConstantVal =
1842         ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1843       ID.Kind = ValID::t_Constant;
1844       return false;
1845     }
1846     
1847     if (Elts.empty())
1848       return Error(ID.Loc, "constant vector must not be empty");
1849
1850     if (!Elts[0]->getType()->isInteger() &&
1851         !Elts[0]->getType()->isFloatingPoint())
1852       return Error(FirstEltLoc,
1853                    "vector elements must have integer or floating point type");
1854     
1855     // Verify that all the vector elements have the same type.
1856     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1857       if (Elts[i]->getType() != Elts[0]->getType())
1858         return Error(FirstEltLoc,
1859                      "vector element #" + utostr(i) +
1860                     " is not of type '" + Elts[0]->getType()->getDescription());
1861     
1862     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1863     ID.Kind = ValID::t_Constant;
1864     return false;
1865   }
1866   case lltok::lsquare: {   // Array Constant
1867     Lex.Lex();
1868     SmallVector<Constant*, 16> Elts;
1869     LocTy FirstEltLoc = Lex.getLoc();
1870     if (ParseGlobalValueVector(Elts) ||
1871         ParseToken(lltok::rsquare, "expected end of array constant"))
1872       return true;
1873
1874     // Handle empty element.
1875     if (Elts.empty()) {
1876       // Use undef instead of an array because it's inconvenient to determine
1877       // the element type at this point, there being no elements to examine.
1878       ID.Kind = ValID::t_EmptyArray;
1879       return false;
1880     }
1881     
1882     if (!Elts[0]->getType()->isFirstClassType())
1883       return Error(FirstEltLoc, "invalid array element type: " + 
1884                    Elts[0]->getType()->getDescription());
1885           
1886     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1887     
1888     // Verify all elements are correct type!
1889     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1890       if (Elts[i]->getType() != Elts[0]->getType())
1891         return Error(FirstEltLoc,
1892                      "array element #" + utostr(i) +
1893                      " is not of type '" +Elts[0]->getType()->getDescription());
1894     }
1895     
1896     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1897     ID.Kind = ValID::t_Constant;
1898     return false;
1899   }
1900   case lltok::kw_c:  // c "foo"
1901     Lex.Lex();
1902     ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1903     if (ParseToken(lltok::StringConstant, "expected string")) return true;
1904     ID.Kind = ValID::t_Constant;
1905     return false;
1906
1907   case lltok::kw_asm: {
1908     // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1909     bool HasSideEffect;
1910     Lex.Lex();
1911     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1912         ParseStringConstant(ID.StrVal) ||
1913         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1914         ParseToken(lltok::StringConstant, "expected constraint string"))
1915       return true;
1916     ID.StrVal2 = Lex.getStrVal();
1917     ID.UIntVal = HasSideEffect;
1918     ID.Kind = ValID::t_InlineAsm;
1919     return false;
1920   }
1921       
1922   case lltok::kw_trunc:
1923   case lltok::kw_zext:
1924   case lltok::kw_sext:
1925   case lltok::kw_fptrunc:
1926   case lltok::kw_fpext:
1927   case lltok::kw_bitcast:
1928   case lltok::kw_uitofp:
1929   case lltok::kw_sitofp:
1930   case lltok::kw_fptoui:
1931   case lltok::kw_fptosi: 
1932   case lltok::kw_inttoptr:
1933   case lltok::kw_ptrtoint: { 
1934     unsigned Opc = Lex.getUIntVal();
1935     PATypeHolder DestTy(Type::VoidTy);
1936     Constant *SrcVal;
1937     Lex.Lex();
1938     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1939         ParseGlobalTypeAndValue(SrcVal) ||
1940         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1941         ParseType(DestTy) ||
1942         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1943       return true;
1944     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1945       return Error(ID.Loc, "invalid cast opcode for cast from '" +
1946                    SrcVal->getType()->getDescription() + "' to '" +
1947                    DestTy->getDescription() + "'");
1948     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 
1949                                                  SrcVal, DestTy);
1950     ID.Kind = ValID::t_Constant;
1951     return false;
1952   }
1953   case lltok::kw_extractvalue: {
1954     Lex.Lex();
1955     Constant *Val;
1956     SmallVector<unsigned, 4> Indices;
1957     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1958         ParseGlobalTypeAndValue(Val) ||
1959         ParseIndexList(Indices) ||
1960         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1961       return true;
1962     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1963       return Error(ID.Loc, "extractvalue operand must be array or struct");
1964     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1965                                           Indices.end()))
1966       return Error(ID.Loc, "invalid indices for extractvalue");
1967     ID.ConstantVal =
1968       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
1969     ID.Kind = ValID::t_Constant;
1970     return false;
1971   }
1972   case lltok::kw_insertvalue: {
1973     Lex.Lex();
1974     Constant *Val0, *Val1;
1975     SmallVector<unsigned, 4> Indices;
1976     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1977         ParseGlobalTypeAndValue(Val0) ||
1978         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1979         ParseGlobalTypeAndValue(Val1) ||
1980         ParseIndexList(Indices) ||
1981         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1982       return true;
1983     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1984       return Error(ID.Loc, "extractvalue operand must be array or struct");
1985     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1986                                           Indices.end()))
1987       return Error(ID.Loc, "invalid indices for insertvalue");
1988     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1989                        Indices.data(), Indices.size());
1990     ID.Kind = ValID::t_Constant;
1991     return false;
1992   }
1993   case lltok::kw_icmp:
1994   case lltok::kw_fcmp: {
1995     unsigned PredVal, Opc = Lex.getUIntVal();
1996     Constant *Val0, *Val1;
1997     Lex.Lex();
1998     if (ParseCmpPredicate(PredVal, Opc) ||
1999         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2000         ParseGlobalTypeAndValue(Val0) ||
2001         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2002         ParseGlobalTypeAndValue(Val1) ||
2003         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2004       return true;
2005     
2006     if (Val0->getType() != Val1->getType())
2007       return Error(ID.Loc, "compare operands must have the same type");
2008     
2009     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2010     
2011     if (Opc == Instruction::FCmp) {
2012       if (!Val0->getType()->isFPOrFPVector())
2013         return Error(ID.Loc, "fcmp requires floating point operands");
2014       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2015     } else {
2016       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2017       if (!Val0->getType()->isIntOrIntVector() &&
2018           !isa<PointerType>(Val0->getType()))
2019         return Error(ID.Loc, "icmp requires pointer or integer operands");
2020       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2021     }
2022     ID.Kind = ValID::t_Constant;
2023     return false;
2024   }
2025       
2026   // Binary Operators.
2027   case lltok::kw_add:
2028   case lltok::kw_fadd:
2029   case lltok::kw_sub:
2030   case lltok::kw_fsub:
2031   case lltok::kw_mul:
2032   case lltok::kw_fmul:
2033   case lltok::kw_udiv:
2034   case lltok::kw_sdiv:
2035   case lltok::kw_fdiv:
2036   case lltok::kw_urem:
2037   case lltok::kw_srem:
2038   case lltok::kw_frem: {
2039     bool NUW = false;
2040     bool NSW = false;
2041     bool Exact = false;
2042     unsigned Opc = Lex.getUIntVal();
2043     Constant *Val0, *Val1;
2044     Lex.Lex();
2045     LocTy ModifierLoc = Lex.getLoc();
2046     if (Opc == Instruction::Add ||
2047         Opc == Instruction::Sub ||
2048         Opc == Instruction::Mul) {
2049       if (EatIfPresent(lltok::kw_nuw))
2050         NUW = true;
2051       if (EatIfPresent(lltok::kw_nsw)) {
2052         NSW = true;
2053         if (EatIfPresent(lltok::kw_nuw))
2054           NUW = true;
2055       }
2056     } else if (Opc == Instruction::SDiv) {
2057       if (EatIfPresent(lltok::kw_exact))
2058         Exact = true;
2059     }
2060     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2061         ParseGlobalTypeAndValue(Val0) ||
2062         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2063         ParseGlobalTypeAndValue(Val1) ||
2064         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2065       return true;
2066     if (Val0->getType() != Val1->getType())
2067       return Error(ID.Loc, "operands of constexpr must have same type");
2068     if (!Val0->getType()->isIntOrIntVector()) {
2069       if (NUW)
2070         return Error(ModifierLoc, "nuw only applies to integer operations");
2071       if (NSW)
2072         return Error(ModifierLoc, "nsw only applies to integer operations");
2073     }
2074     // API compatibility: Accept either integer or floating-point types with
2075     // add, sub, and mul.
2076     if (!Val0->getType()->isIntOrIntVector() &&
2077         !Val0->getType()->isFPOrFPVector())
2078       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2079     Constant *C = ConstantExpr::get(Opc, Val0, Val1);
2080     if (NUW)
2081       cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedOverflow(true);
2082     if (NSW)
2083       cast<OverflowingBinaryOperator>(C)->setHasNoSignedOverflow(true);
2084     if (Exact)
2085       cast<SDivOperator>(C)->setIsExact(true);
2086     ID.ConstantVal = C;
2087     ID.Kind = ValID::t_Constant;
2088     return false;
2089   }
2090       
2091   // Logical Operations
2092   case lltok::kw_shl:
2093   case lltok::kw_lshr:
2094   case lltok::kw_ashr:
2095   case lltok::kw_and:
2096   case lltok::kw_or:
2097   case lltok::kw_xor: {
2098     unsigned Opc = Lex.getUIntVal();
2099     Constant *Val0, *Val1;
2100     Lex.Lex();
2101     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2102         ParseGlobalTypeAndValue(Val0) ||
2103         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2104         ParseGlobalTypeAndValue(Val1) ||
2105         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2106       return true;
2107     if (Val0->getType() != Val1->getType())
2108       return Error(ID.Loc, "operands of constexpr must have same type");
2109     if (!Val0->getType()->isIntOrIntVector())
2110       return Error(ID.Loc,
2111                    "constexpr requires integer or integer vector operands");
2112     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2113     ID.Kind = ValID::t_Constant;
2114     return false;
2115   }  
2116       
2117   case lltok::kw_getelementptr:
2118   case lltok::kw_shufflevector:
2119   case lltok::kw_insertelement:
2120   case lltok::kw_extractelement:
2121   case lltok::kw_select: {
2122     unsigned Opc = Lex.getUIntVal();
2123     SmallVector<Constant*, 16> Elts;
2124     bool InBounds = false;
2125     Lex.Lex();
2126     if (Opc == Instruction::GetElementPtr)
2127       InBounds = EatIfPresent(lltok::kw_inbounds);
2128     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2129         ParseGlobalValueVector(Elts) ||
2130         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2131       return true;
2132     
2133     if (Opc == Instruction::GetElementPtr) {
2134       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2135         return Error(ID.Loc, "getelementptr requires pointer operand");
2136       
2137       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2138                                              (Value**)(Elts.data() + 1),
2139                                              Elts.size() - 1))
2140         return Error(ID.Loc, "invalid indices for getelementptr");
2141       ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
2142                                               Elts.data() + 1, Elts.size() - 1);
2143       if (InBounds)
2144         cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
2145     } else if (Opc == Instruction::Select) {
2146       if (Elts.size() != 3)
2147         return Error(ID.Loc, "expected three operands to select");
2148       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2149                                                               Elts[2]))
2150         return Error(ID.Loc, Reason);
2151       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2152     } else if (Opc == Instruction::ShuffleVector) {
2153       if (Elts.size() != 3)
2154         return Error(ID.Loc, "expected three operands to shufflevector");
2155       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2156         return Error(ID.Loc, "invalid operands to shufflevector");
2157       ID.ConstantVal =
2158                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2159     } else if (Opc == Instruction::ExtractElement) {
2160       if (Elts.size() != 2)
2161         return Error(ID.Loc, "expected two operands to extractelement");
2162       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2163         return Error(ID.Loc, "invalid extractelement operands");
2164       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2165     } else {
2166       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2167       if (Elts.size() != 3)
2168       return Error(ID.Loc, "expected three operands to insertelement");
2169       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2170         return Error(ID.Loc, "invalid insertelement operands");
2171       ID.ConstantVal =
2172                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2173     }
2174     
2175     ID.Kind = ValID::t_Constant;
2176     return false;
2177   }
2178   }
2179   
2180   Lex.Lex();
2181   return false;
2182 }
2183
2184 /// ParseGlobalValue - Parse a global value with the specified type.
2185 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2186   V = 0;
2187   ValID ID;
2188   return ParseValID(ID) ||
2189          ConvertGlobalValIDToValue(Ty, ID, V);
2190 }
2191
2192 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2193 /// constant.
2194 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2195                                          Constant *&V) {
2196   if (isa<FunctionType>(Ty))
2197     return Error(ID.Loc, "functions are not values, refer to them as pointers");
2198   
2199   switch (ID.Kind) {
2200   default: llvm_unreachable("Unknown ValID!");    
2201   case ValID::t_Metadata:
2202     return Error(ID.Loc, "invalid use of metadata");
2203   case ValID::t_LocalID:
2204   case ValID::t_LocalName:
2205     return Error(ID.Loc, "invalid use of function-local name");
2206   case ValID::t_InlineAsm:
2207     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2208   case ValID::t_GlobalName:
2209     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2210     return V == 0;
2211   case ValID::t_GlobalID:
2212     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2213     return V == 0;
2214   case ValID::t_APSInt:
2215     if (!isa<IntegerType>(Ty))
2216       return Error(ID.Loc, "integer constant must have integer type");
2217     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2218     V = ConstantInt::get(Context, ID.APSIntVal);
2219     return false;
2220   case ValID::t_APFloat:
2221     if (!Ty->isFloatingPoint() ||
2222         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2223       return Error(ID.Loc, "floating point constant invalid for type");
2224       
2225     // The lexer has no type info, so builds all float and double FP constants
2226     // as double.  Fix this here.  Long double does not need this.
2227     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2228         Ty == Type::FloatTy) {
2229       bool Ignored;
2230       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2231                             &Ignored);
2232     }
2233     V = ConstantFP::get(Context, ID.APFloatVal);
2234       
2235     if (V->getType() != Ty)
2236       return Error(ID.Loc, "floating point constant does not have type '" +
2237                    Ty->getDescription() + "'");
2238       
2239     return false;
2240   case ValID::t_Null:
2241     if (!isa<PointerType>(Ty))
2242       return Error(ID.Loc, "null must be a pointer type");
2243     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2244     return false;
2245   case ValID::t_Undef:
2246     // FIXME: LabelTy should not be a first-class type.
2247     if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2248         !isa<OpaqueType>(Ty))
2249       return Error(ID.Loc, "invalid type for undef constant");
2250     V = UndefValue::get(Ty);
2251     return false;
2252   case ValID::t_EmptyArray:
2253     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2254       return Error(ID.Loc, "invalid empty array initializer");
2255     V = UndefValue::get(Ty);
2256     return false;
2257   case ValID::t_Zero:
2258     // FIXME: LabelTy should not be a first-class type.
2259     if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2260       return Error(ID.Loc, "invalid type for null constant");
2261     V = Constant::getNullValue(Ty);
2262     return false;
2263   case ValID::t_Constant:
2264     if (ID.ConstantVal->getType() != Ty)
2265       return Error(ID.Loc, "constant expression type mismatch");
2266     V = ID.ConstantVal;
2267     return false;
2268   }
2269 }
2270   
2271 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2272   PATypeHolder Type(Type::VoidTy);
2273   return ParseType(Type) ||
2274          ParseGlobalValue(Type, V);
2275 }    
2276
2277 /// ParseGlobalValueVector
2278 ///   ::= /*empty*/
2279 ///   ::= TypeAndValue (',' TypeAndValue)*
2280 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2281   // Empty list.
2282   if (Lex.getKind() == lltok::rbrace ||
2283       Lex.getKind() == lltok::rsquare ||
2284       Lex.getKind() == lltok::greater ||
2285       Lex.getKind() == lltok::rparen)
2286     return false;
2287   
2288   Constant *C;
2289   if (ParseGlobalTypeAndValue(C)) return true;
2290   Elts.push_back(C);
2291   
2292   while (EatIfPresent(lltok::comma)) {
2293     if (ParseGlobalTypeAndValue(C)) return true;
2294     Elts.push_back(C);
2295   }
2296   
2297   return false;
2298 }
2299
2300
2301 //===----------------------------------------------------------------------===//
2302 // Function Parsing.
2303 //===----------------------------------------------------------------------===//
2304
2305 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2306                                    PerFunctionState &PFS) {
2307   if (ID.Kind == ValID::t_LocalID)
2308     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2309   else if (ID.Kind == ValID::t_LocalName)
2310     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2311   else if (ID.Kind == ValID::t_InlineAsm) {
2312     const PointerType *PTy = dyn_cast<PointerType>(Ty);
2313     const FunctionType *FTy =
2314       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2315     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2316       return Error(ID.Loc, "invalid type for inline asm constraint string");
2317     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2318     return false;
2319   } else if (ID.Kind == ValID::t_Metadata) {
2320     V = ID.MetadataVal;
2321   } else {
2322     Constant *C;
2323     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2324     V = C;
2325     return false;
2326   }
2327
2328   return V == 0;
2329 }
2330
2331 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2332   V = 0;
2333   ValID ID;
2334   return ParseValID(ID) ||
2335          ConvertValIDToValue(Ty, ID, V, PFS);
2336 }
2337
2338 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2339   PATypeHolder T(Type::VoidTy);
2340   return ParseType(T) ||
2341          ParseValue(T, V, PFS);
2342 }
2343
2344 /// FunctionHeader
2345 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2346 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2347 ///       OptionalAlign OptGC
2348 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2349   // Parse the linkage.
2350   LocTy LinkageLoc = Lex.getLoc();
2351   unsigned Linkage;
2352   
2353   unsigned Visibility, CC, RetAttrs;
2354   PATypeHolder RetType(Type::VoidTy);
2355   LocTy RetTypeLoc = Lex.getLoc();
2356   if (ParseOptionalLinkage(Linkage) ||
2357       ParseOptionalVisibility(Visibility) ||
2358       ParseOptionalCallingConv(CC) ||
2359       ParseOptionalAttrs(RetAttrs, 1) ||
2360       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2361     return true;
2362
2363   // Verify that the linkage is ok.
2364   switch ((GlobalValue::LinkageTypes)Linkage) {
2365   case GlobalValue::ExternalLinkage:
2366     break; // always ok.
2367   case GlobalValue::DLLImportLinkage:
2368   case GlobalValue::ExternalWeakLinkage:
2369     if (isDefine)
2370       return Error(LinkageLoc, "invalid linkage for function definition");
2371     break;
2372   case GlobalValue::PrivateLinkage:
2373   case GlobalValue::LinkerPrivateLinkage:
2374   case GlobalValue::InternalLinkage:
2375   case GlobalValue::AvailableExternallyLinkage:
2376   case GlobalValue::LinkOnceAnyLinkage:
2377   case GlobalValue::LinkOnceODRLinkage:
2378   case GlobalValue::WeakAnyLinkage:
2379   case GlobalValue::WeakODRLinkage:
2380   case GlobalValue::DLLExportLinkage:
2381     if (!isDefine)
2382       return Error(LinkageLoc, "invalid linkage for function declaration");
2383     break;
2384   case GlobalValue::AppendingLinkage:
2385   case GlobalValue::GhostLinkage:
2386   case GlobalValue::CommonLinkage:
2387     return Error(LinkageLoc, "invalid function linkage type");
2388   }
2389   
2390   if (!FunctionType::isValidReturnType(RetType) ||
2391       isa<OpaqueType>(RetType))
2392     return Error(RetTypeLoc, "invalid function return type");
2393   
2394   LocTy NameLoc = Lex.getLoc();
2395
2396   std::string FunctionName;
2397   if (Lex.getKind() == lltok::GlobalVar) {
2398     FunctionName = Lex.getStrVal();
2399   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2400     unsigned NameID = Lex.getUIntVal();
2401
2402     if (NameID != NumberedVals.size())
2403       return TokError("function expected to be numbered '%" +
2404                       utostr(NumberedVals.size()) + "'");
2405   } else {
2406     return TokError("expected function name");
2407   }
2408   
2409   Lex.Lex();
2410   
2411   if (Lex.getKind() != lltok::lparen)
2412     return TokError("expected '(' in function argument list");
2413   
2414   std::vector<ArgInfo> ArgList;
2415   bool isVarArg;
2416   unsigned FuncAttrs;
2417   std::string Section;
2418   unsigned Alignment;
2419   std::string GC;
2420
2421   if (ParseArgumentList(ArgList, isVarArg, false) ||
2422       ParseOptionalAttrs(FuncAttrs, 2) ||
2423       (EatIfPresent(lltok::kw_section) &&
2424        ParseStringConstant(Section)) ||
2425       ParseOptionalAlignment(Alignment) ||
2426       (EatIfPresent(lltok::kw_gc) &&
2427        ParseStringConstant(GC)))
2428     return true;
2429
2430   // If the alignment was parsed as an attribute, move to the alignment field.
2431   if (FuncAttrs & Attribute::Alignment) {
2432     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2433     FuncAttrs &= ~Attribute::Alignment;
2434   }
2435   
2436   // Okay, if we got here, the function is syntactically valid.  Convert types
2437   // and do semantic checks.
2438   std::vector<const Type*> ParamTypeList;
2439   SmallVector<AttributeWithIndex, 8> Attrs;
2440   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
2441   // attributes.
2442   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2443   if (FuncAttrs & ObsoleteFuncAttrs) {
2444     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2445     FuncAttrs &= ~ObsoleteFuncAttrs;
2446   }
2447   
2448   if (RetAttrs != Attribute::None)
2449     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2450   
2451   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2452     ParamTypeList.push_back(ArgList[i].Type);
2453     if (ArgList[i].Attrs != Attribute::None)
2454       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2455   }
2456
2457   if (FuncAttrs != Attribute::None)
2458     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2459
2460   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2461   
2462   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2463       RetType != Type::VoidTy)
2464     return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 
2465   
2466   const FunctionType *FT =
2467     FunctionType::get(RetType, ParamTypeList, isVarArg);
2468   const PointerType *PFT = PointerType::getUnqual(FT);
2469
2470   Fn = 0;
2471   if (!FunctionName.empty()) {
2472     // If this was a definition of a forward reference, remove the definition
2473     // from the forward reference table and fill in the forward ref.
2474     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2475       ForwardRefVals.find(FunctionName);
2476     if (FRVI != ForwardRefVals.end()) {
2477       Fn = M->getFunction(FunctionName);
2478       ForwardRefVals.erase(FRVI);
2479     } else if ((Fn = M->getFunction(FunctionName))) {
2480       // If this function already exists in the symbol table, then it is
2481       // multiply defined.  We accept a few cases for old backwards compat.
2482       // FIXME: Remove this stuff for LLVM 3.0.
2483       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2484           (!Fn->isDeclaration() && isDefine)) {
2485         // If the redefinition has different type or different attributes,
2486         // reject it.  If both have bodies, reject it.
2487         return Error(NameLoc, "invalid redefinition of function '" +
2488                      FunctionName + "'");
2489       } else if (Fn->isDeclaration()) {
2490         // Make sure to strip off any argument names so we can't get conflicts.
2491         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2492              AI != AE; ++AI)
2493           AI->setName("");
2494       }
2495     }
2496     
2497   } else if (FunctionName.empty()) {
2498     // If this is a definition of a forward referenced function, make sure the
2499     // types agree.
2500     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2501       = ForwardRefValIDs.find(NumberedVals.size());
2502     if (I != ForwardRefValIDs.end()) {
2503       Fn = cast<Function>(I->second.first);
2504       if (Fn->getType() != PFT)
2505         return Error(NameLoc, "type of definition and forward reference of '@" +
2506                      utostr(NumberedVals.size()) +"' disagree");
2507       ForwardRefValIDs.erase(I);
2508     }
2509   }
2510
2511   if (Fn == 0)
2512     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2513   else // Move the forward-reference to the correct spot in the module.
2514     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2515
2516   if (FunctionName.empty())
2517     NumberedVals.push_back(Fn);
2518   
2519   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2520   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2521   Fn->setCallingConv(CC);
2522   Fn->setAttributes(PAL);
2523   Fn->setAlignment(Alignment);
2524   Fn->setSection(Section);
2525   if (!GC.empty()) Fn->setGC(GC.c_str());
2526     
2527   // Add all of the arguments we parsed to the function.
2528   Function::arg_iterator ArgIt = Fn->arg_begin();
2529   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2530     // If the argument has a name, insert it into the argument symbol table.
2531     if (ArgList[i].Name.empty()) continue;
2532     
2533     // Set the name, if it conflicted, it will be auto-renamed.
2534     ArgIt->setName(ArgList[i].Name);
2535     
2536     if (ArgIt->getNameStr() != ArgList[i].Name)
2537       return Error(ArgList[i].Loc, "redefinition of argument '%" +
2538                    ArgList[i].Name + "'");
2539   }
2540   
2541   return false;
2542 }
2543
2544
2545 /// ParseFunctionBody
2546 ///   ::= '{' BasicBlock+ '}'
2547 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2548 ///
2549 bool LLParser::ParseFunctionBody(Function &Fn) {
2550   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2551     return TokError("expected '{' in function body");
2552   Lex.Lex();  // eat the {.
2553   
2554   PerFunctionState PFS(*this, Fn);
2555   
2556   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2557     if (ParseBasicBlock(PFS)) return true;
2558   
2559   // Eat the }.
2560   Lex.Lex();
2561   
2562   // Verify function is ok.
2563   return PFS.VerifyFunctionComplete();
2564 }
2565
2566 /// ParseBasicBlock
2567 ///   ::= LabelStr? Instruction*
2568 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2569   // If this basic block starts out with a name, remember it.
2570   std::string Name;
2571   LocTy NameLoc = Lex.getLoc();
2572   if (Lex.getKind() == lltok::LabelStr) {
2573     Name = Lex.getStrVal();
2574     Lex.Lex();
2575   }
2576   
2577   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2578   if (BB == 0) return true;
2579   
2580   std::string NameStr;
2581   
2582   // Parse the instructions in this block until we get a terminator.
2583   Instruction *Inst;
2584   do {
2585     // This instruction may have three possibilities for a name: a) none
2586     // specified, b) name specified "%foo =", c) number specified: "%4 =".
2587     LocTy NameLoc = Lex.getLoc();
2588     int NameID = -1;
2589     NameStr = "";
2590     
2591     if (Lex.getKind() == lltok::LocalVarID) {
2592       NameID = Lex.getUIntVal();
2593       Lex.Lex();
2594       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2595         return true;
2596     } else if (Lex.getKind() == lltok::LocalVar ||
2597                // FIXME: REMOVE IN LLVM 3.0
2598                Lex.getKind() == lltok::StringConstant) {
2599       NameStr = Lex.getStrVal();
2600       Lex.Lex();
2601       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2602         return true;
2603     }
2604     
2605     if (ParseInstruction(Inst, BB, PFS)) return true;
2606     
2607     BB->getInstList().push_back(Inst);
2608
2609     // Set the name on the instruction.
2610     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2611   } while (!isa<TerminatorInst>(Inst));
2612   
2613   return false;
2614 }
2615
2616 //===----------------------------------------------------------------------===//
2617 // Instruction Parsing.
2618 //===----------------------------------------------------------------------===//
2619
2620 /// ParseInstruction - Parse one of the many different instructions.
2621 ///
2622 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2623                                 PerFunctionState &PFS) {
2624   lltok::Kind Token = Lex.getKind();
2625   if (Token == lltok::Eof)
2626     return TokError("found end of file when expecting more instructions");
2627   LocTy Loc = Lex.getLoc();
2628   unsigned KeywordVal = Lex.getUIntVal();
2629   Lex.Lex();  // Eat the keyword.
2630   
2631   switch (Token) {
2632   default:                    return Error(Loc, "expected instruction opcode");
2633   // Terminator Instructions.
2634   case lltok::kw_unwind:      Inst = new UnwindInst(); return false;
2635   case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2636   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2637   case lltok::kw_br:          return ParseBr(Inst, PFS);
2638   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2639   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2640   // Binary Operators.
2641   case lltok::kw_add:
2642   case lltok::kw_sub:
2643   case lltok::kw_mul: {
2644     bool NUW = false;
2645     bool NSW = false;
2646     LocTy ModifierLoc = Lex.getLoc();
2647     if (EatIfPresent(lltok::kw_nuw))
2648       NUW = true;
2649     if (EatIfPresent(lltok::kw_nsw)) {
2650       NSW = true;
2651       if (EatIfPresent(lltok::kw_nuw))
2652         NUW = true;
2653     }
2654     // API compatibility: Accept either integer or floating-point types.
2655     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2656     if (!Result) {
2657       if (!Inst->getType()->isIntOrIntVector()) {
2658         if (NUW)
2659           return Error(ModifierLoc, "nuw only applies to integer operations");
2660         if (NSW)
2661           return Error(ModifierLoc, "nsw only applies to integer operations");
2662       }
2663       if (NUW)
2664         cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2665       if (NSW)
2666         cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2667     }
2668     return Result;
2669   }
2670   case lltok::kw_fadd:
2671   case lltok::kw_fsub:
2672   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2673
2674   case lltok::kw_sdiv: {
2675     bool Exact = false;
2676     if (EatIfPresent(lltok::kw_exact))
2677       Exact = true;
2678     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2679     if (!Result)
2680       if (Exact)
2681         cast<SDivOperator>(Inst)->setIsExact(true);
2682     return Result;
2683   }
2684
2685   case lltok::kw_udiv:
2686   case lltok::kw_urem:
2687   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2688   case lltok::kw_fdiv:
2689   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2690   case lltok::kw_shl:
2691   case lltok::kw_lshr:
2692   case lltok::kw_ashr:
2693   case lltok::kw_and:
2694   case lltok::kw_or:
2695   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2696   case lltok::kw_icmp:
2697   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2698   // Casts.
2699   case lltok::kw_trunc:
2700   case lltok::kw_zext:
2701   case lltok::kw_sext:
2702   case lltok::kw_fptrunc:
2703   case lltok::kw_fpext:
2704   case lltok::kw_bitcast:
2705   case lltok::kw_uitofp:
2706   case lltok::kw_sitofp:
2707   case lltok::kw_fptoui:
2708   case lltok::kw_fptosi: 
2709   case lltok::kw_inttoptr:
2710   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2711   // Other.
2712   case lltok::kw_select:         return ParseSelect(Inst, PFS);
2713   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2714   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2715   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2716   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2717   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2718   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2719   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2720   // Memory.
2721   case lltok::kw_alloca:
2722   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
2723   case lltok::kw_free:           return ParseFree(Inst, PFS);
2724   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2725   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2726   case lltok::kw_volatile:
2727     if (EatIfPresent(lltok::kw_load))
2728       return ParseLoad(Inst, PFS, true);
2729     else if (EatIfPresent(lltok::kw_store))
2730       return ParseStore(Inst, PFS, true);
2731     else
2732       return TokError("expected 'load' or 'store'");
2733   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2734   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2735   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2736   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2737   }
2738 }
2739
2740 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2741 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2742   if (Opc == Instruction::FCmp) {
2743     switch (Lex.getKind()) {
2744     default: TokError("expected fcmp predicate (e.g. 'oeq')");
2745     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2746     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2747     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2748     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2749     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2750     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2751     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2752     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2753     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2754     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2755     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2756     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2757     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2758     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2759     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2760     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2761     }
2762   } else {
2763     switch (Lex.getKind()) {
2764     default: TokError("expected icmp predicate (e.g. 'eq')");
2765     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2766     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2767     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2768     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2769     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2770     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2771     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2772     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2773     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2774     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2775     }
2776   }
2777   Lex.Lex();
2778   return false;
2779 }
2780
2781 //===----------------------------------------------------------------------===//
2782 // Terminator Instructions.
2783 //===----------------------------------------------------------------------===//
2784
2785 /// ParseRet - Parse a return instruction.
2786 ///   ::= 'ret' void
2787 ///   ::= 'ret' TypeAndValue
2788 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  [[obsolete: LLVM 3.0]]
2789 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2790                         PerFunctionState &PFS) {
2791   PATypeHolder Ty(Type::VoidTy);
2792   if (ParseType(Ty, true /*void allowed*/)) return true;
2793   
2794   if (Ty == Type::VoidTy) {
2795     Inst = ReturnInst::Create();
2796     return false;
2797   }
2798   
2799   Value *RV;
2800   if (ParseValue(Ty, RV, PFS)) return true;
2801   
2802   // The normal case is one return value.
2803   if (Lex.getKind() == lltok::comma) {
2804     // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2805     // of 'ret {i32,i32} {i32 1, i32 2}'
2806     SmallVector<Value*, 8> RVs;
2807     RVs.push_back(RV);
2808     
2809     while (EatIfPresent(lltok::comma)) {
2810       if (ParseTypeAndValue(RV, PFS)) return true;
2811       RVs.push_back(RV);
2812     }
2813
2814     RV = UndefValue::get(PFS.getFunction().getReturnType());
2815     for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2816       Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2817       BB->getInstList().push_back(I);
2818       RV = I;
2819     }
2820   }
2821   Inst = ReturnInst::Create(RV);
2822   return false;
2823 }
2824
2825
2826 /// ParseBr
2827 ///   ::= 'br' TypeAndValue
2828 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2829 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2830   LocTy Loc, Loc2;
2831   Value *Op0, *Op1, *Op2;
2832   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2833   
2834   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2835     Inst = BranchInst::Create(BB);
2836     return false;
2837   }
2838   
2839   if (Op0->getType() != Type::Int1Ty)
2840     return Error(Loc, "branch condition must have 'i1' type");
2841     
2842   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2843       ParseTypeAndValue(Op1, Loc, PFS) ||
2844       ParseToken(lltok::comma, "expected ',' after true destination") ||
2845       ParseTypeAndValue(Op2, Loc2, PFS))
2846     return true;
2847   
2848   if (!isa<BasicBlock>(Op1))
2849     return Error(Loc, "true destination of branch must be a basic block");
2850   if (!isa<BasicBlock>(Op2))
2851     return Error(Loc2, "true destination of branch must be a basic block");
2852     
2853   Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2854   return false;
2855 }
2856
2857 /// ParseSwitch
2858 ///  Instruction
2859 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2860 ///  JumpTable
2861 ///    ::= (TypeAndValue ',' TypeAndValue)*
2862 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2863   LocTy CondLoc, BBLoc;
2864   Value *Cond, *DefaultBB;
2865   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2866       ParseToken(lltok::comma, "expected ',' after switch condition") ||
2867       ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2868       ParseToken(lltok::lsquare, "expected '[' with switch table"))
2869     return true;
2870
2871   if (!isa<IntegerType>(Cond->getType()))
2872     return Error(CondLoc, "switch condition must have integer type");
2873   if (!isa<BasicBlock>(DefaultBB))
2874     return Error(BBLoc, "default destination must be a basic block");
2875   
2876   // Parse the jump table pairs.
2877   SmallPtrSet<Value*, 32> SeenCases;
2878   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2879   while (Lex.getKind() != lltok::rsquare) {
2880     Value *Constant, *DestBB;
2881     
2882     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2883         ParseToken(lltok::comma, "expected ',' after case value") ||
2884         ParseTypeAndValue(DestBB, BBLoc, PFS))
2885       return true;
2886
2887     if (!SeenCases.insert(Constant))
2888       return Error(CondLoc, "duplicate case value in switch");
2889     if (!isa<ConstantInt>(Constant))
2890       return Error(CondLoc, "case value is not a constant integer");
2891     if (!isa<BasicBlock>(DestBB))
2892       return Error(BBLoc, "case destination is not a basic block");
2893     
2894     Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2895                                    cast<BasicBlock>(DestBB)));
2896   }
2897   
2898   Lex.Lex();  // Eat the ']'.
2899   
2900   SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2901                                       Table.size());
2902   for (unsigned i = 0, e = Table.size(); i != e; ++i)
2903     SI->addCase(Table[i].first, Table[i].second);
2904   Inst = SI;
2905   return false;
2906 }
2907
2908 /// ParseInvoke
2909 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2910 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2911 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2912   LocTy CallLoc = Lex.getLoc();
2913   unsigned CC, RetAttrs, FnAttrs;
2914   PATypeHolder RetType(Type::VoidTy);
2915   LocTy RetTypeLoc;
2916   ValID CalleeID;
2917   SmallVector<ParamInfo, 16> ArgList;
2918
2919   Value *NormalBB, *UnwindBB;
2920   if (ParseOptionalCallingConv(CC) ||
2921       ParseOptionalAttrs(RetAttrs, 1) ||
2922       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2923       ParseValID(CalleeID) ||
2924       ParseParameterList(ArgList, PFS) ||
2925       ParseOptionalAttrs(FnAttrs, 2) ||
2926       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2927       ParseTypeAndValue(NormalBB, PFS) ||
2928       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2929       ParseTypeAndValue(UnwindBB, PFS))
2930     return true;
2931   
2932   if (!isa<BasicBlock>(NormalBB))
2933     return Error(CallLoc, "normal destination is not a basic block");
2934   if (!isa<BasicBlock>(UnwindBB))
2935     return Error(CallLoc, "unwind destination is not a basic block");
2936   
2937   // If RetType is a non-function pointer type, then this is the short syntax
2938   // for the call, which means that RetType is just the return type.  Infer the
2939   // rest of the function argument types from the arguments that are present.
2940   const PointerType *PFTy = 0;
2941   const FunctionType *Ty = 0;
2942   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2943       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2944     // Pull out the types of all of the arguments...
2945     std::vector<const Type*> ParamTypes;
2946     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2947       ParamTypes.push_back(ArgList[i].V->getType());
2948     
2949     if (!FunctionType::isValidReturnType(RetType))
2950       return Error(RetTypeLoc, "Invalid result type for LLVM function");
2951     
2952     Ty = FunctionType::get(RetType, ParamTypes, false);
2953     PFTy = PointerType::getUnqual(Ty);
2954   }
2955   
2956   // Look up the callee.
2957   Value *Callee;
2958   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2959   
2960   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2961   // function attributes.
2962   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2963   if (FnAttrs & ObsoleteFuncAttrs) {
2964     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2965     FnAttrs &= ~ObsoleteFuncAttrs;
2966   }
2967   
2968   // Set up the Attributes for the function.
2969   SmallVector<AttributeWithIndex, 8> Attrs;
2970   if (RetAttrs != Attribute::None)
2971     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2972   
2973   SmallVector<Value*, 8> Args;
2974   
2975   // Loop through FunctionType's arguments and ensure they are specified
2976   // correctly.  Also, gather any parameter attributes.
2977   FunctionType::param_iterator I = Ty->param_begin();
2978   FunctionType::param_iterator E = Ty->param_end();
2979   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2980     const Type *ExpectedTy = 0;
2981     if (I != E) {
2982       ExpectedTy = *I++;
2983     } else if (!Ty->isVarArg()) {
2984       return Error(ArgList[i].Loc, "too many arguments specified");
2985     }
2986     
2987     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2988       return Error(ArgList[i].Loc, "argument is not of expected type '" +
2989                    ExpectedTy->getDescription() + "'");
2990     Args.push_back(ArgList[i].V);
2991     if (ArgList[i].Attrs != Attribute::None)
2992       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2993   }
2994   
2995   if (I != E)
2996     return Error(CallLoc, "not enough parameters specified for call");
2997   
2998   if (FnAttrs != Attribute::None)
2999     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3000   
3001   // Finish off the Attributes and check them
3002   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3003   
3004   InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3005                                       cast<BasicBlock>(UnwindBB),
3006                                       Args.begin(), Args.end());
3007   II->setCallingConv(CC);
3008   II->setAttributes(PAL);
3009   Inst = II;
3010   return false;
3011 }
3012
3013
3014
3015 //===----------------------------------------------------------------------===//
3016 // Binary Operators.
3017 //===----------------------------------------------------------------------===//
3018
3019 /// ParseArithmetic
3020 ///  ::= ArithmeticOps TypeAndValue ',' Value
3021 ///
3022 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3023 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3024 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3025                                unsigned Opc, unsigned OperandType) {
3026   LocTy Loc; Value *LHS, *RHS;
3027   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3028       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3029       ParseValue(LHS->getType(), RHS, PFS))
3030     return true;
3031
3032   bool Valid;
3033   switch (OperandType) {
3034   default: llvm_unreachable("Unknown operand type!");
3035   case 0: // int or FP.
3036     Valid = LHS->getType()->isIntOrIntVector() ||
3037             LHS->getType()->isFPOrFPVector();
3038     break;
3039   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3040   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3041   }
3042   
3043   if (!Valid)
3044     return Error(Loc, "invalid operand type for instruction");
3045   
3046   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3047   return false;
3048 }
3049
3050 /// ParseLogical
3051 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3052 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3053                             unsigned Opc) {
3054   LocTy Loc; Value *LHS, *RHS;
3055   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3056       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3057       ParseValue(LHS->getType(), RHS, PFS))
3058     return true;
3059
3060   if (!LHS->getType()->isIntOrIntVector())
3061     return Error(Loc,"instruction requires integer or integer vector operands");
3062
3063   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3064   return false;
3065 }
3066
3067
3068 /// ParseCompare
3069 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3070 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3071 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3072                             unsigned Opc) {
3073   // Parse the integer/fp comparison predicate.
3074   LocTy Loc;
3075   unsigned Pred;
3076   Value *LHS, *RHS;
3077   if (ParseCmpPredicate(Pred, Opc) ||
3078       ParseTypeAndValue(LHS, Loc, PFS) ||
3079       ParseToken(lltok::comma, "expected ',' after compare value") ||
3080       ParseValue(LHS->getType(), RHS, PFS))
3081     return true;
3082   
3083   if (Opc == Instruction::FCmp) {
3084     if (!LHS->getType()->isFPOrFPVector())
3085       return Error(Loc, "fcmp requires floating point operands");
3086     Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3087   } else {
3088     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3089     if (!LHS->getType()->isIntOrIntVector() &&
3090         !isa<PointerType>(LHS->getType()))
3091       return Error(Loc, "icmp requires integer operands");
3092     Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3093   }
3094   return false;
3095 }
3096
3097 //===----------------------------------------------------------------------===//
3098 // Other Instructions.
3099 //===----------------------------------------------------------------------===//
3100
3101
3102 /// ParseCast
3103 ///   ::= CastOpc TypeAndValue 'to' Type
3104 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3105                          unsigned Opc) {
3106   LocTy Loc;  Value *Op;
3107   PATypeHolder DestTy(Type::VoidTy);
3108   if (ParseTypeAndValue(Op, Loc, PFS) ||
3109       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3110       ParseType(DestTy))
3111     return true;
3112   
3113   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3114     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3115     return Error(Loc, "invalid cast opcode for cast from '" +
3116                  Op->getType()->getDescription() + "' to '" +
3117                  DestTy->getDescription() + "'");
3118   }
3119   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3120   return false;
3121 }
3122
3123 /// ParseSelect
3124 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3125 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3126   LocTy Loc;
3127   Value *Op0, *Op1, *Op2;
3128   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3129       ParseToken(lltok::comma, "expected ',' after select condition") ||
3130       ParseTypeAndValue(Op1, PFS) ||
3131       ParseToken(lltok::comma, "expected ',' after select value") ||
3132       ParseTypeAndValue(Op2, PFS))
3133     return true;
3134   
3135   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3136     return Error(Loc, Reason);
3137   
3138   Inst = SelectInst::Create(Op0, Op1, Op2);
3139   return false;
3140 }
3141
3142 /// ParseVA_Arg
3143 ///   ::= 'va_arg' TypeAndValue ',' Type
3144 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3145   Value *Op;
3146   PATypeHolder EltTy(Type::VoidTy);
3147   LocTy TypeLoc;
3148   if (ParseTypeAndValue(Op, PFS) ||
3149       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3150       ParseType(EltTy, TypeLoc))
3151     return true;
3152   
3153   if (!EltTy->isFirstClassType())
3154     return Error(TypeLoc, "va_arg requires operand with first class type");
3155
3156   Inst = new VAArgInst(Op, EltTy);
3157   return false;
3158 }
3159
3160 /// ParseExtractElement
3161 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3162 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3163   LocTy Loc;
3164   Value *Op0, *Op1;
3165   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3166       ParseToken(lltok::comma, "expected ',' after extract value") ||
3167       ParseTypeAndValue(Op1, PFS))
3168     return true;
3169   
3170   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3171     return Error(Loc, "invalid extractelement operands");
3172   
3173   Inst = ExtractElementInst::Create(Op0, Op1);
3174   return false;
3175 }
3176
3177 /// ParseInsertElement
3178 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3179 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3180   LocTy Loc;
3181   Value *Op0, *Op1, *Op2;
3182   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3183       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3184       ParseTypeAndValue(Op1, PFS) ||
3185       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3186       ParseTypeAndValue(Op2, PFS))
3187     return true;
3188   
3189   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3190     return Error(Loc, "invalid insertelement operands");
3191   
3192   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3193   return false;
3194 }
3195
3196 /// ParseShuffleVector
3197 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3198 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3199   LocTy Loc;
3200   Value *Op0, *Op1, *Op2;
3201   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3202       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3203       ParseTypeAndValue(Op1, PFS) ||
3204       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3205       ParseTypeAndValue(Op2, PFS))
3206     return true;
3207   
3208   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3209     return Error(Loc, "invalid extractelement operands");
3210   
3211   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3212   return false;
3213 }
3214
3215 /// ParsePHI
3216 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3217 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3218   PATypeHolder Ty(Type::VoidTy);
3219   Value *Op0, *Op1;
3220   LocTy TypeLoc = Lex.getLoc();
3221   
3222   if (ParseType(Ty) ||
3223       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3224       ParseValue(Ty, Op0, PFS) ||
3225       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3226       ParseValue(Type::LabelTy, Op1, PFS) ||
3227       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3228     return true;
3229  
3230   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3231   while (1) {
3232     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3233     
3234     if (!EatIfPresent(lltok::comma))
3235       break;
3236
3237     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3238         ParseValue(Ty, Op0, PFS) ||
3239         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3240         ParseValue(Type::LabelTy, Op1, PFS) ||
3241         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3242       return true;
3243   }
3244   
3245   if (!Ty->isFirstClassType())
3246     return Error(TypeLoc, "phi node must have first class type");
3247
3248   PHINode *PN = PHINode::Create(Ty);
3249   PN->reserveOperandSpace(PHIVals.size());
3250   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3251     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3252   Inst = PN;
3253   return false;
3254 }
3255
3256 /// ParseCall
3257 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3258 ///       ParameterList OptionalAttrs
3259 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3260                          bool isTail) {
3261   unsigned CC, RetAttrs, FnAttrs;
3262   PATypeHolder RetType(Type::VoidTy);
3263   LocTy RetTypeLoc;
3264   ValID CalleeID;
3265   SmallVector<ParamInfo, 16> ArgList;
3266   LocTy CallLoc = Lex.getLoc();
3267   
3268   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3269       ParseOptionalCallingConv(CC) ||
3270       ParseOptionalAttrs(RetAttrs, 1) ||
3271       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3272       ParseValID(CalleeID) ||
3273       ParseParameterList(ArgList, PFS) ||
3274       ParseOptionalAttrs(FnAttrs, 2))
3275     return true;
3276   
3277   // If RetType is a non-function pointer type, then this is the short syntax
3278   // for the call, which means that RetType is just the return type.  Infer the
3279   // rest of the function argument types from the arguments that are present.
3280   const PointerType *PFTy = 0;
3281   const FunctionType *Ty = 0;
3282   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3283       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3284     // Pull out the types of all of the arguments...
3285     std::vector<const Type*> ParamTypes;
3286     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3287       ParamTypes.push_back(ArgList[i].V->getType());
3288     
3289     if (!FunctionType::isValidReturnType(RetType))
3290       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3291     
3292     Ty = FunctionType::get(RetType, ParamTypes, false);
3293     PFTy = PointerType::getUnqual(Ty);
3294   }
3295   
3296   // Look up the callee.
3297   Value *Callee;
3298   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3299   
3300   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3301   // function attributes.
3302   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3303   if (FnAttrs & ObsoleteFuncAttrs) {
3304     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3305     FnAttrs &= ~ObsoleteFuncAttrs;
3306   }
3307
3308   // Set up the Attributes for the function.
3309   SmallVector<AttributeWithIndex, 8> Attrs;
3310   if (RetAttrs != Attribute::None)
3311     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3312   
3313   SmallVector<Value*, 8> Args;
3314   
3315   // Loop through FunctionType's arguments and ensure they are specified
3316   // correctly.  Also, gather any parameter attributes.
3317   FunctionType::param_iterator I = Ty->param_begin();
3318   FunctionType::param_iterator E = Ty->param_end();
3319   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3320     const Type *ExpectedTy = 0;
3321     if (I != E) {
3322       ExpectedTy = *I++;
3323     } else if (!Ty->isVarArg()) {
3324       return Error(ArgList[i].Loc, "too many arguments specified");
3325     }
3326     
3327     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3328       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3329                    ExpectedTy->getDescription() + "'");
3330     Args.push_back(ArgList[i].V);
3331     if (ArgList[i].Attrs != Attribute::None)
3332       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3333   }
3334   
3335   if (I != E)
3336     return Error(CallLoc, "not enough parameters specified for call");
3337
3338   if (FnAttrs != Attribute::None)
3339     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3340
3341   // Finish off the Attributes and check them
3342   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3343   
3344   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3345   CI->setTailCall(isTail);
3346   CI->setCallingConv(CC);
3347   CI->setAttributes(PAL);
3348   Inst = CI;
3349   return false;
3350 }
3351
3352 //===----------------------------------------------------------------------===//
3353 // Memory Instructions.
3354 //===----------------------------------------------------------------------===//
3355
3356 /// ParseAlloc
3357 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3358 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3359 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3360                           unsigned Opc) {
3361   PATypeHolder Ty(Type::VoidTy);
3362   Value *Size = 0;
3363   LocTy SizeLoc;
3364   unsigned Alignment = 0;
3365   if (ParseType(Ty)) return true;
3366
3367   if (EatIfPresent(lltok::comma)) {
3368     if (Lex.getKind() == lltok::kw_align) {
3369       if (ParseOptionalAlignment(Alignment)) return true;
3370     } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3371                ParseOptionalCommaAlignment(Alignment)) {
3372       return true;
3373     }
3374   }
3375
3376   if (Size && Size->getType() != Type::Int32Ty)
3377     return Error(SizeLoc, "element count must be i32");
3378
3379   if (Opc == Instruction::Malloc)
3380     Inst = new MallocInst(Ty, Size, Alignment);
3381   else
3382     Inst = new AllocaInst(Ty, Size, Alignment);
3383   return false;
3384 }
3385
3386 /// ParseFree
3387 ///   ::= 'free' TypeAndValue
3388 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3389   Value *Val; LocTy Loc;
3390   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3391   if (!isa<PointerType>(Val->getType()))
3392     return Error(Loc, "operand to free must be a pointer");
3393   Inst = new FreeInst(Val);
3394   return false;
3395 }
3396
3397 /// ParseLoad
3398 ///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3399 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3400                          bool isVolatile) {
3401   Value *Val; LocTy Loc;
3402   unsigned Alignment;
3403   if (ParseTypeAndValue(Val, Loc, PFS) ||
3404       ParseOptionalCommaAlignment(Alignment))
3405     return true;
3406
3407   if (!isa<PointerType>(Val->getType()) ||
3408       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3409     return Error(Loc, "load operand must be a pointer to a first class type");
3410   
3411   Inst = new LoadInst(Val, "", isVolatile, Alignment);
3412   return false;
3413 }
3414
3415 /// ParseStore
3416 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3417 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3418                           bool isVolatile) {
3419   Value *Val, *Ptr; LocTy Loc, PtrLoc;
3420   unsigned Alignment;
3421   if (ParseTypeAndValue(Val, Loc, PFS) ||
3422       ParseToken(lltok::comma, "expected ',' after store operand") ||
3423       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3424       ParseOptionalCommaAlignment(Alignment))
3425     return true;
3426   
3427   if (!isa<PointerType>(Ptr->getType()))
3428     return Error(PtrLoc, "store operand must be a pointer");
3429   if (!Val->getType()->isFirstClassType())
3430     return Error(Loc, "store operand must be a first class value");
3431   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3432     return Error(Loc, "stored value and pointer type do not match");
3433   
3434   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3435   return false;
3436 }
3437
3438 /// ParseGetResult
3439 ///   ::= 'getresult' TypeAndValue ',' i32
3440 /// FIXME: Remove support for getresult in LLVM 3.0
3441 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3442   Value *Val; LocTy ValLoc, EltLoc;
3443   unsigned Element;
3444   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3445       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3446       ParseUInt32(Element, EltLoc))
3447     return true;
3448   
3449   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3450     return Error(ValLoc, "getresult inst requires an aggregate operand");
3451   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3452     return Error(EltLoc, "invalid getresult index for value");
3453   Inst = ExtractValueInst::Create(Val, Element);
3454   return false;
3455 }
3456
3457 /// ParseGetElementPtr
3458 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3459 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3460   Value *Ptr, *Val; LocTy Loc, EltLoc;
3461
3462   bool InBounds = EatIfPresent(lltok::kw_inbounds);
3463
3464   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3465   
3466   if (!isa<PointerType>(Ptr->getType()))
3467     return Error(Loc, "base of getelementptr must be a pointer");
3468   
3469   SmallVector<Value*, 16> Indices;
3470   while (EatIfPresent(lltok::comma)) {
3471     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3472     if (!isa<IntegerType>(Val->getType()))
3473       return Error(EltLoc, "getelementptr index must be an integer");
3474     Indices.push_back(Val);
3475   }
3476   
3477   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3478                                          Indices.begin(), Indices.end()))
3479     return Error(Loc, "invalid getelementptr indices");
3480   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3481   if (InBounds)
3482     cast<GEPOperator>(Inst)->setIsInBounds(true);
3483   return false;
3484 }
3485
3486 /// ParseExtractValue
3487 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3488 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3489   Value *Val; LocTy Loc;
3490   SmallVector<unsigned, 4> Indices;
3491   if (ParseTypeAndValue(Val, Loc, PFS) ||
3492       ParseIndexList(Indices))
3493     return true;
3494
3495   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3496     return Error(Loc, "extractvalue operand must be array or struct");
3497
3498   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3499                                         Indices.end()))
3500     return Error(Loc, "invalid indices for extractvalue");
3501   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3502   return false;
3503 }
3504
3505 /// ParseInsertValue
3506 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3507 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3508   Value *Val0, *Val1; LocTy Loc0, Loc1;
3509   SmallVector<unsigned, 4> Indices;
3510   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3511       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3512       ParseTypeAndValue(Val1, Loc1, PFS) ||
3513       ParseIndexList(Indices))
3514     return true;
3515   
3516   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3517     return Error(Loc0, "extractvalue operand must be array or struct");
3518   
3519   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3520                                         Indices.end()))
3521     return Error(Loc0, "invalid indices for insertvalue");
3522   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3523   return false;
3524 }
3525
3526 //===----------------------------------------------------------------------===//
3527 // Embedded metadata.
3528 //===----------------------------------------------------------------------===//
3529
3530 /// ParseMDNodeVector
3531 ///   ::= Element (',' Element)*
3532 /// Element
3533 ///   ::= 'null' | TypeAndValue
3534 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3535   assert(Lex.getKind() == lltok::lbrace);
3536   Lex.Lex();
3537   do {
3538     Value *V = 0;
3539     if (Lex.getKind() == lltok::kw_null) {
3540       Lex.Lex();
3541       V = 0;
3542     } else {
3543       PATypeHolder Ty(Type::VoidTy);
3544       if (ParseType(Ty)) return true;
3545       if (Lex.getKind() == lltok::Metadata) {
3546         Lex.Lex();
3547         MetadataBase *Node = 0;
3548         if (!ParseMDNode(Node))
3549           V = Node;
3550         else {
3551           MetadataBase *MDS = 0;
3552           if (ParseMDString(MDS)) return true;
3553           V = MDS;
3554         }
3555       } else {
3556         Constant *C;
3557         if (ParseGlobalValue(Ty, C)) return true;
3558         V = C;
3559       }
3560     }
3561     Elts.push_back(V);
3562   } while (EatIfPresent(lltok::comma));
3563
3564   return false;
3565 }