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