For PR1187:
[oota-llvm.git] / tools / llvm-upgrade / UpgradeParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM assembly languages files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
24 #include <algorithm>
25 #include <iostream>
26 #include <list>
27 #include <utility>
28
29 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30 // relating to upreferences in the input stream.
31 //
32 //#define DEBUG_UPREFS 1
33 #ifdef DEBUG_UPREFS
34 #define UR_OUT(X) std::cerr << X
35 #else
36 #define UR_OUT(X)
37 #endif
38
39 #define YYERROR_VERBOSE 1
40 #define YYINCLUDED_STDLIB_H
41 #define YYDEBUG 1
42
43 int yylex();
44 int yyparse();
45
46 int yyerror(const char*);
47 static void warning(const std::string& WarningMsg);
48
49 namespace llvm {
50
51 std::istream* LexInput;
52 static std::string CurFilename;
53
54 // This bool controls whether attributes are ever added to function declarations
55 // definitions and calls.
56 static bool AddAttributes = false;
57
58 static Module *ParserResult;
59 static bool ObsoleteVarArgs;
60 static bool NewVarArgs;
61 static BasicBlock *CurBB;
62 static GlobalVariable *CurGV;
63
64 // This contains info used when building the body of a function.  It is
65 // destroyed when the function is completed.
66 //
67 typedef std::vector<Value *> ValueList;           // Numbered defs
68
69 typedef std::pair<std::string,const Type*> RenameMapKey;
70 typedef std::map<RenameMapKey,std::string> RenameMapType;
71
72 static void 
73 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
75
76 static struct PerModuleInfo {
77   Module *CurrentModule;
78   std::map<const Type *, ValueList> Values; // Module level numbered definitions
79   std::map<const Type *,ValueList> LateResolveValues;
80   std::vector<PATypeHolder>    Types;
81   std::map<ValID, PATypeHolder> LateResolveTypes;
82   static Module::Endianness Endian;
83   static Module::PointerSize PointerSize;
84   RenameMapType RenameMap;
85
86   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87   /// how they were referenced and on which line of the input they came from so
88   /// that we can resolve them later and print error messages as appropriate.
89   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90
91   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92   // references to global values.  Global values may be referenced before they
93   // are defined, and if so, the temporary object that they represent is held
94   // here.  This is used for forward references of GlobalValues.
95   //
96   typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*> 
97     GlobalRefsType;
98   GlobalRefsType GlobalRefs;
99
100   void ModuleDone() {
101     // If we could not resolve some functions at function compilation time
102     // (calls to functions before they are defined), resolve them now...  Types
103     // are resolved when the constant pool has been completely parsed.
104     //
105     ResolveDefinitions(LateResolveValues);
106
107     // Check to make sure that all global value forward references have been
108     // resolved!
109     //
110     if (!GlobalRefs.empty()) {
111       std::string UndefinedReferences = "Unresolved global references exist:\n";
112
113       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
114            I != E; ++I) {
115         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
116                                I->first.second.getName() + "\n";
117       }
118       error(UndefinedReferences);
119       return;
120     }
121
122     if (CurrentModule->getDataLayout().empty()) {
123       std::string dataLayout;
124       if (Endian != Module::AnyEndianness)
125         dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126       if (PointerSize != Module::AnyPointerSize) {
127         if (!dataLayout.empty())
128           dataLayout += "-";
129         dataLayout.append(PointerSize == Module::Pointer64 ? 
130                           "p:64:64" : "p:32:32");
131       }
132       CurrentModule->setDataLayout(dataLayout);
133     }
134
135     Values.clear();         // Clear out function local definitions
136     Types.clear();
137     CurrentModule = 0;
138   }
139
140   // GetForwardRefForGlobal - Check to see if there is a forward reference
141   // for this global.  If so, remove it from the GlobalRefs map and return it.
142   // If not, just return null.
143   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144     // Check to see if there is a forward reference to this global variable...
145     // if there is, eliminate it and patch the reference to use the new def'n.
146     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147     GlobalValue *Ret = 0;
148     if (I != GlobalRefs.end()) {
149       Ret = I->second;
150       GlobalRefs.erase(I);
151     }
152     return Ret;
153   }
154   void setEndianness(Module::Endianness E) { Endian = E; }
155   void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
156 } CurModule;
157
158 Module::Endianness  PerModuleInfo::Endian = Module::AnyEndianness;
159 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
160
161 static struct PerFunctionInfo {
162   Function *CurrentFunction;     // Pointer to current function being created
163
164   std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165   std::map<const Type*, ValueList> LateResolveValues;
166   bool isDeclare;                   // Is this function a forward declararation?
167   GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
168
169   /// BBForwardRefs - When we see forward references to basic blocks, keep
170   /// track of them here.
171   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172   std::vector<BasicBlock*> NumberedBlocks;
173   RenameMapType RenameMap;
174   unsigned NextBBNum;
175
176   inline PerFunctionInfo() {
177     CurrentFunction = 0;
178     isDeclare = false;
179     Linkage = GlobalValue::ExternalLinkage;    
180   }
181
182   inline void FunctionStart(Function *M) {
183     CurrentFunction = M;
184     NextBBNum = 0;
185   }
186
187   void FunctionDone() {
188     NumberedBlocks.clear();
189
190     // Any forward referenced blocks left?
191     if (!BBForwardRefs.empty()) {
192       error("Undefined reference to label " + 
193             BBForwardRefs.begin()->first->getName());
194       return;
195     }
196
197     // Resolve all forward references now.
198     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
199
200     Values.clear();         // Clear out function local definitions
201     RenameMap.clear();
202     CurrentFunction = 0;
203     isDeclare = false;
204     Linkage = GlobalValue::ExternalLinkage;
205   }
206 } CurFun;  // Info for the current function...
207
208 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
209
210
211 //===----------------------------------------------------------------------===//
212 //               Code to handle definitions of all the types
213 //===----------------------------------------------------------------------===//
214
215 static int InsertValue(Value *V,
216                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
217   if (V->hasName()) return -1;           // Is this a numbered definition?
218
219   // Yes, insert the value into the value table...
220   ValueList &List = ValueTab[V->getType()];
221   List.push_back(V);
222   return List.size()-1;
223 }
224
225 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
226   switch (D.Type) {
227   case ValID::NumberVal:               // Is it a numbered definition?
228     // Module constants occupy the lowest numbered slots...
229     if ((unsigned)D.Num < CurModule.Types.size()) {
230       return CurModule.Types[(unsigned)D.Num];
231     }
232     break;
233   case ValID::NameVal:                 // Is it a named definition?
234     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
235       D.destroy();  // Free old strdup'd memory...
236       return N;
237     }
238     break;
239   default:
240     error("Internal parser error: Invalid symbol type reference");
241     return 0;
242   }
243
244   // If we reached here, we referenced either a symbol that we don't know about
245   // or an id number that hasn't been read yet.  We may be referencing something
246   // forward, so just create an entry to be resolved later and get to it...
247   //
248   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
249
250
251   if (inFunctionScope()) {
252     if (D.Type == ValID::NameVal) {
253       error("Reference to an undefined type: '" + D.getName() + "'");
254       return 0;
255     } else {
256       error("Reference to an undefined type: #" + itostr(D.Num));
257       return 0;
258     }
259   }
260
261   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
262   if (I != CurModule.LateResolveTypes.end())
263     return I->second;
264
265   Type *Typ = OpaqueType::get();
266   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
267   return Typ;
268  }
269
270 /// This function determines if two function types differ only in their use of
271 /// the sret parameter attribute in the first argument. If they are identical 
272 /// in all other respects, it returns true. Otherwise, it returns false.
273 bool FuncTysDifferOnlyBySRet(const FunctionType *F1, 
274                                    const FunctionType *F2) {
275   if (F1->getReturnType() != F2->getReturnType() ||
276       F1->getNumParams() != F2->getNumParams() ||
277       F1->getParamAttrs(0) != F2->getParamAttrs(0))
278     return false;
279   unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
280   for (unsigned i = 0; i < F1->getNumParams(); ++i) {
281     if (F1->getParamType(i) != F2->getParamType(i) ||
282         unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
283         unsigned(F2->getParamAttrs(i+1)) & SRetMask)
284       return false;
285   }
286   return true;
287 }
288
289 // The upgrade of csretcc to sret param attribute may have caused a function 
290 // to not be found because the param attribute changed the type of the called 
291 // function. This helper function, used in getExistingValue, detects that
292 // situation and returns V if it occurs and 0 otherwise. 
293 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
294   // Handle degenerate cases
295   if (!V)
296     return 0;
297   if (V->getType() == Ty)
298     return V;
299
300   Value* Result = 0;
301   const PointerType *PF1 = dyn_cast<PointerType>(Ty);
302   const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
303   if (PF1 && PF2) {
304     const FunctionType *FT1 =
305       dyn_cast<FunctionType>(PF1->getElementType());
306     const FunctionType *FT2 =
307       dyn_cast<FunctionType>(PF2->getElementType());
308     if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
309       if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
310         Result = V;
311       else if (Constant *C = dyn_cast<Constant>(V))
312         Result = ConstantExpr::getBitCast(C, PF1);
313       else
314         Result = new BitCastInst(V, PF1, "upgrd.cast", CurBB);
315   }
316   return Result;
317 }
318
319 // getExistingValue - Look up the value specified by the provided type and
320 // the provided ValID.  If the value exists and has already been defined, return
321 // it.  Otherwise return null.
322 //
323 static Value *getExistingValue(const Type *Ty, const ValID &D) {
324   if (isa<FunctionType>(Ty)) {
325     error("Functions are not values and must be referenced as pointers");
326   }
327
328   switch (D.Type) {
329   case ValID::NumberVal: {                 // Is it a numbered definition?
330     unsigned Num = (unsigned)D.Num;
331
332     // Module constants occupy the lowest numbered slots...
333     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
334     if (VI != CurModule.Values.end()) {
335       if (Num < VI->second.size())
336         return VI->second[Num];
337       Num -= VI->second.size();
338     }
339
340     // Make sure that our type is within bounds
341     VI = CurFun.Values.find(Ty);
342     if (VI == CurFun.Values.end()) return 0;
343
344     // Check that the number is within bounds...
345     if (VI->second.size() <= Num) return 0;
346
347     return VI->second[Num];
348   }
349
350   case ValID::NameVal: {                // Is it a named definition?
351     // Get the name out of the ID
352     std::string Name(D.Name);
353     Value* V = 0;
354     RenameMapKey Key = std::make_pair(Name, Ty);
355     if (inFunctionScope()) {
356       // See if the name was renamed
357       RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
358       std::string LookupName;
359       if (I != CurFun.RenameMap.end())
360         LookupName = I->second;
361       else
362         LookupName = Name;
363       ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
364       V = SymTab.lookup(LookupName);
365       V = handleSRetFuncTypeMerge(V, Ty);
366     }
367     if (!V) {
368       RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
369       std::string LookupName;
370       if (I != CurModule.RenameMap.end())
371         LookupName = I->second;
372       else
373         LookupName = Name;
374       V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
375       V = handleSRetFuncTypeMerge(V, Ty);
376     }
377     if (!V) 
378       return 0;
379
380     D.destroy();  // Free old strdup'd memory...
381     return V;
382   }
383
384   // Check to make sure that "Ty" is an integral type, and that our
385   // value will fit into the specified type...
386   case ValID::ConstSIntVal:    // Is it a constant pool reference??
387     if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
388       error("Signed integral constant '" + itostr(D.ConstPool64) + 
389             "' is invalid for type '" + Ty->getDescription() + "'");
390     }
391     return ConstantInt::get(Ty, D.ConstPool64);
392
393   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
394     if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
395       if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
396         error("Integral constant '" + utostr(D.UConstPool64) + 
397               "' is invalid or out of range");
398       else     // This is really a signed reference.  Transmogrify.
399         return ConstantInt::get(Ty, D.ConstPool64);
400     } else
401       return ConstantInt::get(Ty, D.UConstPool64);
402
403   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
404     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
405       error("FP constant invalid for type");
406     return ConstantFP::get(Ty, D.ConstPoolFP);
407
408   case ValID::ConstNullVal:      // Is it a null value?
409     if (!isa<PointerType>(Ty))
410       error("Cannot create a a non pointer null");
411     return ConstantPointerNull::get(cast<PointerType>(Ty));
412
413   case ValID::ConstUndefVal:      // Is it an undef value?
414     return UndefValue::get(Ty);
415
416   case ValID::ConstZeroVal:      // Is it a zero value?
417     return Constant::getNullValue(Ty);
418     
419   case ValID::ConstantVal:       // Fully resolved constant?
420     if (D.ConstantValue->getType() != Ty) 
421       error("Constant expression type different from required type");
422     return D.ConstantValue;
423
424   case ValID::InlineAsmVal: {    // Inline asm expression
425     const PointerType *PTy = dyn_cast<PointerType>(Ty);
426     const FunctionType *FTy =
427       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
428     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
429       error("Invalid type for asm constraint string");
430     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
431                                    D.IAD->HasSideEffects);
432     D.destroy();   // Free InlineAsmDescriptor.
433     return IA;
434   }
435   default:
436     assert(0 && "Unhandled case");
437     return 0;
438   }   // End of switch
439
440   assert(0 && "Unhandled case");
441   return 0;
442 }
443
444 // getVal - This function is identical to getExistingValue, except that if a
445 // value is not already defined, it "improvises" by creating a placeholder var
446 // that looks and acts just like the requested variable.  When the value is
447 // defined later, all uses of the placeholder variable are replaced with the
448 // real thing.
449 //
450 static Value *getVal(const Type *Ty, const ValID &ID) {
451   if (Ty == Type::LabelTy)
452     error("Cannot use a basic block here");
453
454   // See if the value has already been defined.
455   Value *V = getExistingValue(Ty, ID);
456   if (V) return V;
457
458   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
459     error("Invalid use of a composite type");
460
461   // If we reached here, we referenced either a symbol that we don't know about
462   // or an id number that hasn't been read yet.  We may be referencing something
463   // forward, so just create an entry to be resolved later and get to it...
464   V = new Argument(Ty);
465
466   // Remember where this forward reference came from.  FIXME, shouldn't we try
467   // to recycle these things??
468   CurModule.PlaceHolderInfo.insert(
469     std::make_pair(V, std::make_pair(ID, Upgradelineno)));
470
471   if (inFunctionScope())
472     InsertValue(V, CurFun.LateResolveValues);
473   else
474     InsertValue(V, CurModule.LateResolveValues);
475   return V;
476 }
477
478 /// getBBVal - This is used for two purposes:
479 ///  * If isDefinition is true, a new basic block with the specified ID is being
480 ///    defined.
481 ///  * If isDefinition is true, this is a reference to a basic block, which may
482 ///    or may not be a forward reference.
483 ///
484 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
485   assert(inFunctionScope() && "Can't get basic block at global scope");
486
487   std::string Name;
488   BasicBlock *BB = 0;
489   switch (ID.Type) {
490   default: 
491     error("Illegal label reference " + ID.getName());
492     break;
493   case ValID::NumberVal:                // Is it a numbered definition?
494     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
495       CurFun.NumberedBlocks.resize(ID.Num+1);
496     BB = CurFun.NumberedBlocks[ID.Num];
497     break;
498   case ValID::NameVal:                  // Is it a named definition?
499     Name = ID.Name;
500     if (Value *N = CurFun.CurrentFunction->
501                    getValueSymbolTable().lookup(Name)) {
502       if (N->getType() != Type::LabelTy)
503         error("Name '" + Name + "' does not refer to a BasicBlock");
504       BB = cast<BasicBlock>(N);
505     }
506     break;
507   }
508
509   // See if the block has already been defined.
510   if (BB) {
511     // If this is the definition of the block, make sure the existing value was
512     // just a forward reference.  If it was a forward reference, there will be
513     // an entry for it in the PlaceHolderInfo map.
514     if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
515       // The existing value was a definition, not a forward reference.
516       error("Redefinition of label " + ID.getName());
517
518     ID.destroy();                       // Free strdup'd memory.
519     return BB;
520   }
521
522   // Otherwise this block has not been seen before.
523   BB = new BasicBlock("", CurFun.CurrentFunction);
524   if (ID.Type == ValID::NameVal) {
525     BB->setName(ID.Name);
526   } else {
527     CurFun.NumberedBlocks[ID.Num] = BB;
528   }
529
530   // If this is not a definition, keep track of it so we can use it as a forward
531   // reference.
532   if (!isDefinition) {
533     // Remember where this forward reference came from.
534     CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
535   } else {
536     // The forward declaration could have been inserted anywhere in the
537     // function: insert it into the correct place now.
538     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
539     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
540   }
541   ID.destroy();
542   return BB;
543 }
544
545
546 //===----------------------------------------------------------------------===//
547 //              Code to handle forward references in instructions
548 //===----------------------------------------------------------------------===//
549 //
550 // This code handles the late binding needed with statements that reference
551 // values not defined yet... for example, a forward branch, or the PHI node for
552 // a loop body.
553 //
554 // This keeps a table (CurFun.LateResolveValues) of all such forward references
555 // and back patchs after we are done.
556 //
557
558 // ResolveDefinitions - If we could not resolve some defs at parsing
559 // time (forward branches, phi functions for loops, etc...) resolve the
560 // defs now...
561 //
562 static void 
563 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
564                    std::map<const Type*,ValueList> *FutureLateResolvers) {
565
566   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
567   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
568          E = LateResolvers.end(); LRI != E; ++LRI) {
569     const Type* Ty = LRI->first;
570     ValueList &List = LRI->second;
571     while (!List.empty()) {
572       Value *V = List.back();
573       List.pop_back();
574
575       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
576         CurModule.PlaceHolderInfo.find(V);
577       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
578
579       ValID &DID = PHI->second.first;
580
581       Value *TheRealValue = getExistingValue(Ty, DID);
582       if (TheRealValue) {
583         V->replaceAllUsesWith(TheRealValue);
584         delete V;
585         CurModule.PlaceHolderInfo.erase(PHI);
586       } else if (FutureLateResolvers) {
587         // Functions have their unresolved items forwarded to the module late
588         // resolver table
589         InsertValue(V, *FutureLateResolvers);
590       } else {
591         if (DID.Type == ValID::NameVal) {
592           error("Reference to an invalid definition: '" + DID.getName() +
593                 "' of type '" + V->getType()->getDescription() + "'",
594                 PHI->second.second);
595             return;
596         } else {
597           error("Reference to an invalid definition: #" +
598                 itostr(DID.Num) + " of type '" + 
599                 V->getType()->getDescription() + "'", PHI->second.second);
600           return;
601         }
602       }
603     }
604   }
605
606   LateResolvers.clear();
607 }
608
609 // ResolveTypeTo - A brand new type was just declared.  This means that (if
610 // name is not null) things referencing Name can be resolved.  Otherwise, things
611 // refering to the number can be resolved.  Do this now.
612 //
613 static void ResolveTypeTo(char *Name, const Type *ToTy) {
614   ValID D;
615   if (Name) D = ValID::create(Name);
616   else      D = ValID::create((int)CurModule.Types.size());
617
618   std::map<ValID, PATypeHolder>::iterator I =
619     CurModule.LateResolveTypes.find(D);
620   if (I != CurModule.LateResolveTypes.end()) {
621     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
622     CurModule.LateResolveTypes.erase(I);
623   }
624 }
625
626 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
627 static std::string makeNameUnique(const std::string& Name) {
628   static unsigned UniqueNameCounter = 1;
629   std::string Result(Name);
630   Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
631   return Result;
632 }
633
634 /// This is the implementation portion of TypeHasInteger. It traverses the
635 /// type given, avoiding recursive types, and returns true as soon as it finds
636 /// an integer type. If no integer type is found, it returns false.
637 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
638   // Handle some easy cases
639   if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
640     return false;
641   if (Ty->isInteger())
642     return true;
643   if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
644     return STy->getElementType()->isInteger();
645
646   // Avoid type structure recursion
647   for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
648        I != E; ++I)
649     if (Ty == *I)
650       return false;
651
652   // Push us on the type stack
653   Stack.push_back(Ty);
654
655   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
656     if (TypeHasIntegerI(FTy->getReturnType(), Stack)) 
657       return true;
658     FunctionType::param_iterator I = FTy->param_begin();
659     FunctionType::param_iterator E = FTy->param_end();
660     for (; I != E; ++I)
661       if (TypeHasIntegerI(*I, Stack))
662         return true;
663     return false;
664   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
665     StructType::element_iterator I = STy->element_begin();
666     StructType::element_iterator E = STy->element_end();
667     for (; I != E; ++I) {
668       if (TypeHasIntegerI(*I, Stack))
669         return true;
670     }
671     return false;
672   }
673   // There shouldn't be anything else, but its definitely not integer
674   assert(0 && "What type is this?");
675   return false;
676 }
677
678 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
679 /// to avoid recursion, and then calls TypeHasIntegerI.
680 static inline bool TypeHasInteger(const Type *Ty) {
681   std::vector<const Type*> TyStack;
682   return TypeHasIntegerI(Ty, TyStack);
683 }
684
685 // setValueName - Set the specified value to the name given.  The name may be
686 // null potentially, in which case this is a noop.  The string passed in is
687 // assumed to be a malloc'd string buffer, and is free'd by this function.
688 //
689 static void setValueName(Value *V, char *NameStr) {
690   if (NameStr) {
691     std::string Name(NameStr);      // Copy string
692     free(NameStr);                  // Free old string
693
694     if (V->getType() == Type::VoidTy) {
695       error("Can't assign name '" + Name + "' to value with void type");
696       return;
697     }
698
699     assert(inFunctionScope() && "Must be in function scope");
700
701     // Search the function's symbol table for an existing value of this name
702     ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
703     Value* Existing = ST.lookup(Name);
704     if (Existing) {
705       // An existing value of the same name was found. This might have happened
706       // because of the integer type planes collapsing in LLVM 2.0. 
707       if (Existing->getType() == V->getType() &&
708           !TypeHasInteger(Existing->getType())) {
709         // If the type does not contain any integers in them then this can't be
710         // a type plane collapsing issue. It truly is a redefinition and we 
711         // should error out as the assembly is invalid.
712         error("Redefinition of value named '" + Name + "' of type '" +
713               V->getType()->getDescription() + "'");
714         return;
715       } 
716       // In LLVM 2.0 we don't allow names to be re-used for any values in a 
717       // function, regardless of Type. Previously re-use of names was okay as 
718       // long as they were distinct types. With type planes collapsing because
719       // of the signedness change and because of PR411, this can no longer be
720       // supported. We must search the entire symbol table for a conflicting
721       // name and make the name unique. No warning is needed as this can't 
722       // cause a problem.
723       std::string NewName = makeNameUnique(Name);
724       // We're changing the name but it will probably be used by other 
725       // instructions as operands later on. Consequently we have to retain
726       // a mapping of the renaming that we're doing.
727       RenameMapKey Key = std::make_pair(Name,V->getType());
728       CurFun.RenameMap[Key] = NewName;
729       Name = NewName;
730     }
731
732     // Set the name.
733     V->setName(Name);
734   }
735 }
736
737 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
738 /// this is a declaration, otherwise it is a definition.
739 static GlobalVariable *
740 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
741                     bool isConstantGlobal, const Type *Ty,
742                     Constant *Initializer) {
743   if (isa<FunctionType>(Ty))
744     error("Cannot declare global vars of function type");
745
746   const PointerType *PTy = PointerType::get(Ty);
747
748   std::string Name;
749   if (NameStr) {
750     Name = NameStr;      // Copy string
751     free(NameStr);       // Free old string
752   }
753
754   // See if this global value was forward referenced.  If so, recycle the
755   // object.
756   ValID ID;
757   if (!Name.empty()) {
758     ID = ValID::create((char*)Name.c_str());
759   } else {
760     ID = ValID::create((int)CurModule.Values[PTy].size());
761   }
762
763   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
764     // Move the global to the end of the list, from whereever it was
765     // previously inserted.
766     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
767     CurModule.CurrentModule->getGlobalList().remove(GV);
768     CurModule.CurrentModule->getGlobalList().push_back(GV);
769     GV->setInitializer(Initializer);
770     GV->setLinkage(Linkage);
771     GV->setConstant(isConstantGlobal);
772     InsertValue(GV, CurModule.Values);
773     return GV;
774   }
775
776   // If this global has a name, check to see if there is already a definition
777   // of this global in the module and emit warnings if there are conflicts.
778   if (!Name.empty()) {
779     // The global has a name. See if there's an existing one of the same name.
780     if (CurModule.CurrentModule->getNamedGlobal(Name)) {
781       // We found an existing global ov the same name. This isn't allowed 
782       // in LLVM 2.0. Consequently, we must alter the name of the global so it
783       // can at least compile. This can happen because of type planes 
784       // There is alread a global of the same name which means there is a
785       // conflict. Let's see what we can do about it.
786       std::string NewName(makeNameUnique(Name));
787       if (Linkage == GlobalValue::InternalLinkage) {
788         // The linkage type is internal so just warn about the rename without
789         // invoking "scarey language" about linkage failures. GVars with
790         // InternalLinkage can be renamed at will.
791         warning("Global variable '" + Name + "' was renamed to '"+ 
792                 NewName + "'");
793       } else {
794         // The linkage of this gval is external so we can't reliably rename 
795         // it because it could potentially create a linking problem.  
796         // However, we can't leave the name conflict in the output either or 
797         // it won't assemble with LLVM 2.0.  So, all we can do is rename 
798         // this one to something unique and emit a warning about the problem.
799         warning("Renaming global variable '" + Name + "' to '" + NewName + 
800                   "' may cause linkage errors");
801       }
802
803       // Put the renaming in the global rename map
804       RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
805       CurModule.RenameMap[Key] = NewName;
806
807       // Rename it
808       Name = NewName;
809     }
810   }
811
812   // Otherwise there is no existing GV to use, create one now.
813   GlobalVariable *GV =
814     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
815                        CurModule.CurrentModule);
816   InsertValue(GV, CurModule.Values);
817   return GV;
818 }
819
820 // setTypeName - Set the specified type to the name given.  The name may be
821 // null potentially, in which case this is a noop.  The string passed in is
822 // assumed to be a malloc'd string buffer, and is freed by this function.
823 //
824 // This function returns true if the type has already been defined, but is
825 // allowed to be redefined in the specified context.  If the name is a new name
826 // for the type plane, it is inserted and false is returned.
827 static bool setTypeName(const Type *T, char *NameStr) {
828   assert(!inFunctionScope() && "Can't give types function-local names");
829   if (NameStr == 0) return false;
830  
831   std::string Name(NameStr);      // Copy string
832   free(NameStr);                  // Free old string
833
834   // We don't allow assigning names to void type
835   if (T == Type::VoidTy) {
836     error("Can't assign name '" + Name + "' to the void type");
837     return false;
838   }
839
840   // Set the type name, checking for conflicts as we do so.
841   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
842
843   if (AlreadyExists) {   // Inserting a name that is already defined???
844     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
845     assert(Existing && "Conflict but no matching type?");
846
847     // There is only one case where this is allowed: when we are refining an
848     // opaque type.  In this case, Existing will be an opaque type.
849     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
850       // We ARE replacing an opaque type!
851       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
852       return true;
853     }
854
855     // Otherwise, this is an attempt to redefine a type. That's okay if
856     // the redefinition is identical to the original. This will be so if
857     // Existing and T point to the same Type object. In this one case we
858     // allow the equivalent redefinition.
859     if (Existing == T) return true;  // Yes, it's equal.
860
861     // Any other kind of (non-equivalent) redefinition is an error.
862     error("Redefinition of type named '" + Name + "' in the '" +
863           T->getDescription() + "' type plane");
864   }
865
866   return false;
867 }
868
869 //===----------------------------------------------------------------------===//
870 // Code for handling upreferences in type names...
871 //
872
873 // TypeContains - Returns true if Ty directly contains E in it.
874 //
875 static bool TypeContains(const Type *Ty, const Type *E) {
876   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
877                    E) != Ty->subtype_end();
878 }
879
880 namespace {
881   struct UpRefRecord {
882     // NestingLevel - The number of nesting levels that need to be popped before
883     // this type is resolved.
884     unsigned NestingLevel;
885
886     // LastContainedTy - This is the type at the current binding level for the
887     // type.  Every time we reduce the nesting level, this gets updated.
888     const Type *LastContainedTy;
889
890     // UpRefTy - This is the actual opaque type that the upreference is
891     // represented with.
892     OpaqueType *UpRefTy;
893
894     UpRefRecord(unsigned NL, OpaqueType *URTy)
895       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
896   };
897 }
898
899 // UpRefs - A list of the outstanding upreferences that need to be resolved.
900 static std::vector<UpRefRecord> UpRefs;
901
902 /// HandleUpRefs - Every time we finish a new layer of types, this function is
903 /// called.  It loops through the UpRefs vector, which is a list of the
904 /// currently active types.  For each type, if the up reference is contained in
905 /// the newly completed type, we decrement the level count.  When the level
906 /// count reaches zero, the upreferenced type is the type that is passed in:
907 /// thus we can complete the cycle.
908 ///
909 static PATypeHolder HandleUpRefs(const Type *ty) {
910   // If Ty isn't abstract, or if there are no up-references in it, then there is
911   // nothing to resolve here.
912   if (!ty->isAbstract() || UpRefs.empty()) return ty;
913   
914   PATypeHolder Ty(ty);
915   UR_OUT("Type '" << Ty->getDescription() <<
916          "' newly formed.  Resolving upreferences.\n" <<
917          UpRefs.size() << " upreferences active!\n");
918
919   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
920   // to zero), we resolve them all together before we resolve them to Ty.  At
921   // the end of the loop, if there is anything to resolve to Ty, it will be in
922   // this variable.
923   OpaqueType *TypeToResolve = 0;
924
925   for (unsigned i = 0; i != UpRefs.size(); ++i) {
926     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
927            << UpRefs[i].second->getDescription() << ") = "
928            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
929     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
930       // Decrement level of upreference
931       unsigned Level = --UpRefs[i].NestingLevel;
932       UpRefs[i].LastContainedTy = Ty;
933       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
934       if (Level == 0) {                     // Upreference should be resolved!
935         if (!TypeToResolve) {
936           TypeToResolve = UpRefs[i].UpRefTy;
937         } else {
938           UR_OUT("  * Resolving upreference for "
939                  << UpRefs[i].second->getDescription() << "\n";
940                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
941           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
942           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
943                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
944         }
945         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
946         --i;                                // Do not skip the next element...
947       }
948     }
949   }
950
951   if (TypeToResolve) {
952     UR_OUT("  * Resolving upreference for "
953            << UpRefs[i].second->getDescription() << "\n";
954            std::string OldName = TypeToResolve->getDescription());
955     TypeToResolve->refineAbstractTypeTo(Ty);
956   }
957
958   return Ty;
959 }
960
961 static inline Instruction::TermOps 
962 getTermOp(TermOps op) {
963   switch (op) {
964     default           : assert(0 && "Invalid OldTermOp");
965     case RetOp        : return Instruction::Ret;
966     case BrOp         : return Instruction::Br;
967     case SwitchOp     : return Instruction::Switch;
968     case InvokeOp     : return Instruction::Invoke;
969     case UnwindOp     : return Instruction::Unwind;
970     case UnreachableOp: return Instruction::Unreachable;
971   }
972 }
973
974 static inline Instruction::BinaryOps 
975 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
976   switch (op) {
977     default     : assert(0 && "Invalid OldBinaryOps");
978     case SetEQ  : 
979     case SetNE  : 
980     case SetLE  :
981     case SetGE  :
982     case SetLT  :
983     case SetGT  : assert(0 && "Should use getCompareOp");
984     case AddOp  : return Instruction::Add;
985     case SubOp  : return Instruction::Sub;
986     case MulOp  : return Instruction::Mul;
987     case DivOp  : {
988       // This is an obsolete instruction so we must upgrade it based on the
989       // types of its operands.
990       bool isFP = Ty->isFloatingPoint();
991       if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
992         // If its a packed type we want to use the element type
993         isFP = PTy->getElementType()->isFloatingPoint();
994       if (isFP)
995         return Instruction::FDiv;
996       else if (Sign == Signed)
997         return Instruction::SDiv;
998       return Instruction::UDiv;
999     }
1000     case UDivOp : return Instruction::UDiv;
1001     case SDivOp : return Instruction::SDiv;
1002     case FDivOp : return Instruction::FDiv;
1003     case RemOp  : {
1004       // This is an obsolete instruction so we must upgrade it based on the
1005       // types of its operands.
1006       bool isFP = Ty->isFloatingPoint();
1007       if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1008         // If its a packed type we want to use the element type
1009         isFP = PTy->getElementType()->isFloatingPoint();
1010       // Select correct opcode
1011       if (isFP)
1012         return Instruction::FRem;
1013       else if (Sign == Signed)
1014         return Instruction::SRem;
1015       return Instruction::URem;
1016     }
1017     case URemOp : return Instruction::URem;
1018     case SRemOp : return Instruction::SRem;
1019     case FRemOp : return Instruction::FRem;
1020     case LShrOp : return Instruction::LShr;
1021     case AShrOp : return Instruction::AShr;
1022     case ShlOp  : return Instruction::Shl;
1023     case ShrOp  : 
1024       if (Sign == Signed)
1025         return Instruction::AShr;
1026       return Instruction::LShr;
1027     case AndOp  : return Instruction::And;
1028     case OrOp   : return Instruction::Or;
1029     case XorOp  : return Instruction::Xor;
1030   }
1031 }
1032
1033 static inline Instruction::OtherOps 
1034 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1035              Signedness Sign) {
1036   bool isSigned = Sign == Signed;
1037   bool isFP = Ty->isFloatingPoint();
1038   switch (op) {
1039     default     : assert(0 && "Invalid OldSetCC");
1040     case SetEQ  : 
1041       if (isFP) {
1042         predicate = FCmpInst::FCMP_OEQ;
1043         return Instruction::FCmp;
1044       } else {
1045         predicate = ICmpInst::ICMP_EQ;
1046         return Instruction::ICmp;
1047       }
1048     case SetNE  : 
1049       if (isFP) {
1050         predicate = FCmpInst::FCMP_UNE;
1051         return Instruction::FCmp;
1052       } else {
1053         predicate = ICmpInst::ICMP_NE;
1054         return Instruction::ICmp;
1055       }
1056     case SetLE  : 
1057       if (isFP) {
1058         predicate = FCmpInst::FCMP_OLE;
1059         return Instruction::FCmp;
1060       } else {
1061         if (isSigned)
1062           predicate = ICmpInst::ICMP_SLE;
1063         else
1064           predicate = ICmpInst::ICMP_ULE;
1065         return Instruction::ICmp;
1066       }
1067     case SetGE  : 
1068       if (isFP) {
1069         predicate = FCmpInst::FCMP_OGE;
1070         return Instruction::FCmp;
1071       } else {
1072         if (isSigned)
1073           predicate = ICmpInst::ICMP_SGE;
1074         else
1075           predicate = ICmpInst::ICMP_UGE;
1076         return Instruction::ICmp;
1077       }
1078     case SetLT  : 
1079       if (isFP) {
1080         predicate = FCmpInst::FCMP_OLT;
1081         return Instruction::FCmp;
1082       } else {
1083         if (isSigned)
1084           predicate = ICmpInst::ICMP_SLT;
1085         else
1086           predicate = ICmpInst::ICMP_ULT;
1087         return Instruction::ICmp;
1088       }
1089     case SetGT  : 
1090       if (isFP) {
1091         predicate = FCmpInst::FCMP_OGT;
1092         return Instruction::FCmp;
1093       } else {
1094         if (isSigned)
1095           predicate = ICmpInst::ICMP_SGT;
1096         else
1097           predicate = ICmpInst::ICMP_UGT;
1098         return Instruction::ICmp;
1099       }
1100   }
1101 }
1102
1103 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1104   switch (op) {
1105     default              : assert(0 && "Invalid OldMemoryOps");
1106     case MallocOp        : return Instruction::Malloc;
1107     case FreeOp          : return Instruction::Free;
1108     case AllocaOp        : return Instruction::Alloca;
1109     case LoadOp          : return Instruction::Load;
1110     case StoreOp         : return Instruction::Store;
1111     case GetElementPtrOp : return Instruction::GetElementPtr;
1112   }
1113 }
1114
1115 static inline Instruction::OtherOps 
1116 getOtherOp(OtherOps op, Signedness Sign) {
1117   switch (op) {
1118     default               : assert(0 && "Invalid OldOtherOps");
1119     case PHIOp            : return Instruction::PHI;
1120     case CallOp           : return Instruction::Call;
1121     case SelectOp         : return Instruction::Select;
1122     case UserOp1          : return Instruction::UserOp1;
1123     case UserOp2          : return Instruction::UserOp2;
1124     case VAArg            : return Instruction::VAArg;
1125     case ExtractElementOp : return Instruction::ExtractElement;
1126     case InsertElementOp  : return Instruction::InsertElement;
1127     case ShuffleVectorOp  : return Instruction::ShuffleVector;
1128     case ICmpOp           : return Instruction::ICmp;
1129     case FCmpOp           : return Instruction::FCmp;
1130   };
1131 }
1132
1133 static inline Value*
1134 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy, 
1135         Signedness DstSign, bool ForceInstruction = false) {
1136   Instruction::CastOps Opcode;
1137   const Type* SrcTy = Src->getType();
1138   if (op == CastOp) {
1139     if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1140       // fp -> ptr cast is no longer supported but we must upgrade this
1141       // by doing a double cast: fp -> int -> ptr
1142       SrcTy = Type::Int64Ty;
1143       Opcode = Instruction::IntToPtr;
1144       if (isa<Constant>(Src)) {
1145         Src = ConstantExpr::getCast(Instruction::FPToUI, 
1146                                      cast<Constant>(Src), SrcTy);
1147       } else {
1148         std::string NewName(makeNameUnique(Src->getName()));
1149         Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1150       }
1151     } else if (isa<IntegerType>(DstTy) &&
1152                cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1153       // cast type %x to bool was previously defined as setne type %x, null
1154       // The cast semantic is now to truncate, not compare so we must retain
1155       // the original intent by replacing the cast with a setne
1156       Constant* Null = Constant::getNullValue(SrcTy);
1157       Instruction::OtherOps Opcode = Instruction::ICmp;
1158       unsigned short predicate = ICmpInst::ICMP_NE;
1159       if (SrcTy->isFloatingPoint()) {
1160         Opcode = Instruction::FCmp;
1161         predicate = FCmpInst::FCMP_ONE;
1162       } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1163         error("Invalid cast to bool");
1164       }
1165       if (isa<Constant>(Src) && !ForceInstruction)
1166         return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1167       else
1168         return CmpInst::create(Opcode, predicate, Src, Null);
1169     }
1170     // Determine the opcode to use by calling CastInst::getCastOpcode
1171     Opcode = 
1172       CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1173
1174   } else switch (op) {
1175     default: assert(0 && "Invalid cast token");
1176     case TruncOp:    Opcode = Instruction::Trunc; break;
1177     case ZExtOp:     Opcode = Instruction::ZExt; break;
1178     case SExtOp:     Opcode = Instruction::SExt; break;
1179     case FPTruncOp:  Opcode = Instruction::FPTrunc; break;
1180     case FPExtOp:    Opcode = Instruction::FPExt; break;
1181     case FPToUIOp:   Opcode = Instruction::FPToUI; break;
1182     case FPToSIOp:   Opcode = Instruction::FPToSI; break;
1183     case UIToFPOp:   Opcode = Instruction::UIToFP; break;
1184     case SIToFPOp:   Opcode = Instruction::SIToFP; break;
1185     case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1186     case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1187     case BitCastOp:  Opcode = Instruction::BitCast; break;
1188   }
1189
1190   if (isa<Constant>(Src) && !ForceInstruction)
1191     return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1192   return CastInst::create(Opcode, Src, DstTy);
1193 }
1194
1195 static Instruction *
1196 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID, 
1197                      std::vector<Value*>& Args) {
1198
1199   std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1200   if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1201     if (Args.size() != 2)
1202       error("Invalid prototype for " + Name + " prototype");
1203     return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1204   } else {
1205     const Type* PtrTy = PointerType::get(Type::Int8Ty);
1206     std::vector<const Type*> Params;
1207     if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1208       if (Args.size() != 1)
1209         error("Invalid prototype for " + Name + " prototype");
1210       Params.push_back(PtrTy);
1211       const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1212       const PointerType *PFTy = PointerType::get(FTy);
1213       Value* Func = getVal(PFTy, ID);
1214       Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1215       return new CallInst(Func, Args);
1216     } else if (Name == "llvm.va_copy") {
1217       if (Args.size() != 2)
1218         error("Invalid prototype for " + Name + " prototype");
1219       Params.push_back(PtrTy);
1220       Params.push_back(PtrTy);
1221       const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1222       const PointerType *PFTy = PointerType::get(FTy);
1223       Value* Func = getVal(PFTy, ID);
1224       std::string InstName0(makeNameUnique("va0"));
1225       std::string InstName1(makeNameUnique("va1"));
1226       Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1227       Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1228       return new CallInst(Func, Args);
1229     }
1230   }
1231   return 0;
1232 }
1233
1234 const Type* upgradeGEPIndices(const Type* PTy, 
1235                        std::vector<ValueInfo> *Indices, 
1236                        std::vector<Value*>    &VIndices, 
1237                        std::vector<Constant*> *CIndices = 0) {
1238   // Traverse the indices with a gep_type_iterator so we can build the list
1239   // of constant and value indices for use later. Also perform upgrades
1240   VIndices.clear();
1241   if (CIndices) CIndices->clear();
1242   for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1243     VIndices.push_back((*Indices)[i].V);
1244   generic_gep_type_iterator<std::vector<Value*>::iterator>
1245     GTI = gep_type_begin(PTy, VIndices.begin(),  VIndices.end()),
1246     GTE = gep_type_end(PTy,  VIndices.begin(),  VIndices.end());
1247   for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1248     Value *Index = VIndices[i];
1249     if (CIndices && !isa<Constant>(Index))
1250       error("Indices to constant getelementptr must be constants");
1251     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte 
1252     // struct indices to i32 struct indices with ZExt for compatibility.
1253     else if (isa<StructType>(*GTI)) {        // Only change struct indices
1254       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1255         if (CUI->getType()->getBitWidth() == 8)
1256           Index = 
1257             ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1258     } else {
1259       // Make sure that unsigned SequentialType indices are zext'd to 
1260       // 64-bits if they were smaller than that because LLVM 2.0 will sext 
1261       // all indices for SequentialType elements. We must retain the same 
1262       // semantic (zext) for unsigned types.
1263       if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1264         if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1265           if (CIndices)
1266             Index = ConstantExpr::getCast(Instruction::ZExt, 
1267               cast<Constant>(Index), Type::Int64Ty);
1268           else
1269             Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1270               makeNameUnique("gep"), CurBB);
1271           VIndices[i] = Index;
1272         }
1273     }
1274     // Add to the CIndices list, if requested.
1275     if (CIndices)
1276       CIndices->push_back(cast<Constant>(Index));
1277   }
1278
1279   const Type *IdxTy =
1280     GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1281     if (!IdxTy)
1282       error("Index list invalid for constant getelementptr");
1283   return IdxTy;
1284 }
1285
1286 unsigned upgradeCallingConv(unsigned CC) {
1287   switch (CC) {
1288     case OldCallingConv::C           : return CallingConv::C;
1289     case OldCallingConv::CSRet       : return CallingConv::C;
1290     case OldCallingConv::Fast        : return CallingConv::Fast;
1291     case OldCallingConv::Cold        : return CallingConv::Cold;
1292     case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1293     case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1294     default:
1295       return CC;
1296   }
1297 }
1298
1299 Module* UpgradeAssembly(const std::string &infile, std::istream& in, 
1300                               bool debug, bool addAttrs)
1301 {
1302   Upgradelineno = 1; 
1303   CurFilename = infile;
1304   LexInput = &in;
1305   yydebug = debug;
1306   AddAttributes = addAttrs;
1307   ObsoleteVarArgs = false;
1308   NewVarArgs = false;
1309
1310   CurModule.CurrentModule = new Module(CurFilename);
1311
1312   // Check to make sure the parser succeeded
1313   if (yyparse()) {
1314     if (ParserResult)
1315       delete ParserResult;
1316     std::cerr << "llvm-upgrade: parse failed.\n";
1317     return 0;
1318   }
1319
1320   // Check to make sure that parsing produced a result
1321   if (!ParserResult) {
1322     std::cerr << "llvm-upgrade: no parse result.\n";
1323     return 0;
1324   }
1325
1326   // Reset ParserResult variable while saving its value for the result.
1327   Module *Result = ParserResult;
1328   ParserResult = 0;
1329
1330   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1331   {
1332     Function* F;
1333     if ((F = Result->getFunction("llvm.va_start"))
1334         && F->getFunctionType()->getNumParams() == 0)
1335       ObsoleteVarArgs = true;
1336     if((F = Result->getFunction("llvm.va_copy"))
1337        && F->getFunctionType()->getNumParams() == 1)
1338       ObsoleteVarArgs = true;
1339   }
1340
1341   if (ObsoleteVarArgs && NewVarArgs) {
1342     error("This file is corrupt: it uses both new and old style varargs");
1343     return 0;
1344   }
1345
1346   if(ObsoleteVarArgs) {
1347     if(Function* F = Result->getFunction("llvm.va_start")) {
1348       if (F->arg_size() != 0) {
1349         error("Obsolete va_start takes 0 argument");
1350         return 0;
1351       }
1352       
1353       //foo = va_start()
1354       // ->
1355       //bar = alloca typeof(foo)
1356       //va_start(bar)
1357       //foo = load bar
1358
1359       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1360       const Type* ArgTy = F->getFunctionType()->getReturnType();
1361       const Type* ArgTyPtr = PointerType::get(ArgTy);
1362       Function* NF = cast<Function>(Result->getOrInsertFunction(
1363         "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1364
1365       while (!F->use_empty()) {
1366         CallInst* CI = cast<CallInst>(F->use_back());
1367         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1368         new CallInst(NF, bar, "", CI);
1369         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1370         CI->replaceAllUsesWith(foo);
1371         CI->getParent()->getInstList().erase(CI);
1372       }
1373       Result->getFunctionList().erase(F);
1374     }
1375     
1376     if(Function* F = Result->getFunction("llvm.va_end")) {
1377       if(F->arg_size() != 1) {
1378         error("Obsolete va_end takes 1 argument");
1379         return 0;
1380       }
1381
1382       //vaend foo
1383       // ->
1384       //bar = alloca 1 of typeof(foo)
1385       //vaend bar
1386       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1387       const Type* ArgTy = F->getFunctionType()->getParamType(0);
1388       const Type* ArgTyPtr = PointerType::get(ArgTy);
1389       Function* NF = cast<Function>(Result->getOrInsertFunction(
1390         "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1391
1392       while (!F->use_empty()) {
1393         CallInst* CI = cast<CallInst>(F->use_back());
1394         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1395         new StoreInst(CI->getOperand(1), bar, CI);
1396         new CallInst(NF, bar, "", CI);
1397         CI->getParent()->getInstList().erase(CI);
1398       }
1399       Result->getFunctionList().erase(F);
1400     }
1401
1402     if(Function* F = Result->getFunction("llvm.va_copy")) {
1403       if(F->arg_size() != 1) {
1404         error("Obsolete va_copy takes 1 argument");
1405         return 0;
1406       }
1407       //foo = vacopy(bar)
1408       // ->
1409       //a = alloca 1 of typeof(foo)
1410       //b = alloca 1 of typeof(foo)
1411       //store bar -> b
1412       //vacopy(a, b)
1413       //foo = load a
1414       
1415       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1416       const Type* ArgTy = F->getFunctionType()->getReturnType();
1417       const Type* ArgTyPtr = PointerType::get(ArgTy);
1418       Function* NF = cast<Function>(Result->getOrInsertFunction(
1419         "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1420
1421       while (!F->use_empty()) {
1422         CallInst* CI = cast<CallInst>(F->use_back());
1423         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1424         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1425         new StoreInst(CI->getOperand(1), b, CI);
1426         new CallInst(NF, a, b, "", CI);
1427         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1428         CI->replaceAllUsesWith(foo);
1429         CI->getParent()->getInstList().erase(CI);
1430       }
1431       Result->getFunctionList().erase(F);
1432     }
1433   }
1434
1435   return Result;
1436 }
1437
1438 } // end llvm namespace
1439
1440 using namespace llvm;
1441
1442 %}
1443
1444 %union {
1445   llvm::Module                           *ModuleVal;
1446   llvm::Function                         *FunctionVal;
1447   std::pair<llvm::PATypeInfo, char*>     *ArgVal;
1448   llvm::BasicBlock                       *BasicBlockVal;
1449   llvm::TerminatorInst                   *TermInstVal;
1450   llvm::InstrInfo                        InstVal;
1451   llvm::ConstInfo                        ConstVal;
1452   llvm::ValueInfo                        ValueVal;
1453   llvm::PATypeInfo                       TypeVal;
1454   llvm::TypeInfo                         PrimType;
1455   llvm::PHIListInfo                      PHIList;
1456   std::list<llvm::PATypeInfo>            *TypeList;
1457   std::vector<llvm::ValueInfo>           *ValueList;
1458   std::vector<llvm::ConstInfo>           *ConstVector;
1459
1460
1461   std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1462   // Represent the RHS of PHI node
1463   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1464
1465   llvm::GlobalValue::LinkageTypes         Linkage;
1466   int64_t                           SInt64Val;
1467   uint64_t                          UInt64Val;
1468   int                               SIntVal;
1469   unsigned                          UIntVal;
1470   double                            FPVal;
1471   bool                              BoolVal;
1472
1473   char                             *StrVal;   // This memory is strdup'd!
1474   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
1475
1476   llvm::BinaryOps                   BinaryOpVal;
1477   llvm::TermOps                     TermOpVal;
1478   llvm::MemoryOps                   MemOpVal;
1479   llvm::OtherOps                    OtherOpVal;
1480   llvm::CastOps                     CastOpVal;
1481   llvm::ICmpInst::Predicate         IPred;
1482   llvm::FCmpInst::Predicate         FPred;
1483   llvm::Module::Endianness          Endianness;
1484 }
1485
1486 %type <ModuleVal>     Module FunctionList
1487 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
1488 %type <BasicBlockVal> BasicBlock InstructionList
1489 %type <TermInstVal>   BBTerminatorInst
1490 %type <InstVal>       Inst InstVal MemoryInst
1491 %type <ConstVal>      ConstVal ConstExpr
1492 %type <ConstVector>   ConstVector
1493 %type <ArgList>       ArgList ArgListH
1494 %type <ArgVal>        ArgVal
1495 %type <PHIList>       PHIList
1496 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
1497 %type <ValueList>     IndexList                   // For GEP derived indices
1498 %type <TypeList>      TypeListI ArgTypeListI
1499 %type <JumpTable>     JumpTable
1500 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
1501 %type <BoolVal>       OptVolatile                 // 'volatile' or not
1502 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
1503 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
1504 %type <Linkage>       OptLinkage FnDeclareLinkage
1505 %type <Endianness>    BigOrLittle
1506
1507 // ValueRef - Unresolved reference to a definition or BB
1508 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
1509 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
1510
1511 // Tokens and types for handling constant integer values
1512 //
1513 // ESINT64VAL - A negative number within long long range
1514 %token <SInt64Val> ESINT64VAL
1515
1516 // EUINT64VAL - A positive number within uns. long long range
1517 %token <UInt64Val> EUINT64VAL
1518 %type  <SInt64Val> EINT64VAL
1519
1520 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
1521 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
1522 %type   <SIntVal>   INTVAL
1523 %token  <FPVal>     FPVAL     // Float or Double constant
1524
1525 // Built in types...
1526 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
1527 %type  <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1528 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1529 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1530
1531 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1532 %type  <StrVal> Name OptName OptAssign
1533 %type  <UIntVal> OptAlign OptCAlign
1534 %type <StrVal> OptSection SectionString
1535
1536 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1537 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1538 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1539 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1540 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1541 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1542 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1543 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1544 %token DATALAYOUT
1545 %type <UIntVal> OptCallingConv
1546
1547 // Basic Block Terminating Operators
1548 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1549 %token UNWIND EXCEPT
1550
1551 // Binary Operators
1552 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1553 %type  <BinaryOpVal> ShiftOps
1554 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM 
1555 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR 
1556 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
1557 %token <OtherOpVal> ICMP FCMP
1558
1559 // Memory Instructions
1560 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1561
1562 // Other Operators
1563 %token <OtherOpVal> PHI_TOK SELECT VAARG
1564 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1565 %token VAARG_old VANEXT_old //OBSOLETE
1566
1567 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1568 %type  <IPred> IPredicates
1569 %type  <FPred> FPredicates
1570 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
1571 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1572
1573 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI 
1574 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST 
1575 %type  <CastOpVal> CastOps
1576
1577 %start Module
1578
1579 %%
1580
1581 // Handle constant integer size restriction and conversion...
1582 //
1583 INTVAL 
1584   : SINTVAL
1585   | UINTVAL {
1586     if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1587       error("Value too large for type");
1588     $$ = (int32_t)$1;
1589   }
1590   ;
1591
1592 EINT64VAL 
1593   : ESINT64VAL       // These have same type and can't cause problems...
1594   | EUINT64VAL {
1595     if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1596       error("Value too large for type");
1597     $$ = (int64_t)$1;
1598   };
1599
1600 // Operations that are notably excluded from this list include:
1601 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1602 //
1603 ArithmeticOps
1604   : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1605   ;
1606
1607 LogicalOps   
1608   : AND | OR | XOR
1609   ;
1610
1611 SetCondOps   
1612   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1613   ;
1614
1615 IPredicates  
1616   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1617   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1618   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1619   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1620   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1621   ;
1622
1623 FPredicates  
1624   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1625   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1626   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1627   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1628   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1629   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1630   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1631   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1632   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1633   ;
1634 ShiftOps  
1635   : SHL | SHR | ASHR | LSHR
1636   ;
1637
1638 CastOps      
1639   : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI 
1640   | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1641   ;
1642
1643 // These are some types that allow classification if we only want a particular 
1644 // thing... for example, only a signed, unsigned, or integral type.
1645 SIntType 
1646   :  LONG |  INT |  SHORT | SBYTE
1647   ;
1648
1649 UIntType 
1650   : ULONG | UINT | USHORT | UBYTE
1651   ;
1652
1653 IntType  
1654   : SIntType | UIntType
1655   ;
1656
1657 FPType   
1658   : FLOAT | DOUBLE
1659   ;
1660
1661 // OptAssign - Value producing statements have an optional assignment component
1662 OptAssign 
1663   : Name '=' {
1664     $$ = $1;
1665   }
1666   | /*empty*/ {
1667     $$ = 0;
1668   };
1669
1670 OptLinkage 
1671   : INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1672   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; } 
1673   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1674   | APPENDING   { $$ = GlobalValue::AppendingLinkage; } 
1675   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1676   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1677   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1678   | /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1679   ;
1680
1681 OptCallingConv 
1682   : /*empty*/          { $$ = OldCallingConv::C; } 
1683   | CCC_TOK            { $$ = OldCallingConv::C; } 
1684   | CSRETCC_TOK        { $$ = OldCallingConv::CSRet; } 
1685   | FASTCC_TOK         { $$ = OldCallingConv::Fast; } 
1686   | COLDCC_TOK         { $$ = OldCallingConv::Cold; } 
1687   | X86_STDCALLCC_TOK  { $$ = OldCallingConv::X86_StdCall; } 
1688   | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; } 
1689   | CC_TOK EUINT64VAL  {
1690     if ((unsigned)$2 != $2)
1691       error("Calling conv too large");
1692     $$ = $2;
1693   }
1694   ;
1695
1696 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1697 // a comma before it.
1698 OptAlign 
1699   : /*empty*/        { $$ = 0; } 
1700   | ALIGN EUINT64VAL {
1701     $$ = $2;
1702     if ($$ != 0 && !isPowerOf2_32($$))
1703       error("Alignment must be a power of two");
1704   }
1705   ;
1706
1707 OptCAlign 
1708   : /*empty*/ { $$ = 0; } 
1709   | ',' ALIGN EUINT64VAL {
1710     $$ = $3;
1711     if ($$ != 0 && !isPowerOf2_32($$))
1712       error("Alignment must be a power of two");
1713   }
1714   ;
1715
1716 SectionString 
1717   : SECTION STRINGCONSTANT {
1718     for (unsigned i = 0, e = strlen($2); i != e; ++i)
1719       if ($2[i] == '"' || $2[i] == '\\')
1720         error("Invalid character in section name");
1721     $$ = $2;
1722   }
1723   ;
1724
1725 OptSection 
1726   : /*empty*/ { $$ = 0; } 
1727   | SectionString { $$ = $1; }
1728   ;
1729
1730 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1731 // is set to be the global we are processing.
1732 //
1733 GlobalVarAttributes 
1734   : /* empty */ {} 
1735   | ',' GlobalVarAttribute GlobalVarAttributes {}
1736   ;
1737
1738 GlobalVarAttribute
1739   : SectionString {
1740     CurGV->setSection($1);
1741     free($1);
1742   } 
1743   | ALIGN EUINT64VAL {
1744     if ($2 != 0 && !isPowerOf2_32($2))
1745       error("Alignment must be a power of two");
1746     CurGV->setAlignment($2);
1747     
1748   }
1749   ;
1750
1751 //===----------------------------------------------------------------------===//
1752 // Types includes all predefined types... except void, because it can only be
1753 // used in specific contexts (function returning void for example).  To have
1754 // access to it, a user must explicitly use TypesV.
1755 //
1756
1757 // TypesV includes all of 'Types', but it also includes the void type.
1758 TypesV    
1759   : Types
1760   | VOID { 
1761     $$.PAT = new PATypeHolder($1.T); 
1762     $$.S = Signless;
1763   }
1764   ;
1765
1766 UpRTypesV 
1767   : UpRTypes 
1768   | VOID { 
1769     $$.PAT = new PATypeHolder($1.T); 
1770     $$.S = Signless;
1771   }
1772   ;
1773
1774 Types
1775   : UpRTypes {
1776     if (!UpRefs.empty())
1777       error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
1778     $$ = $1;
1779   }
1780   ;
1781
1782 PrimType
1783   : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT 
1784   | LONG | ULONG | FLOAT | DOUBLE | LABEL
1785   ;
1786
1787 // Derived types are added later...
1788 UpRTypes 
1789   : PrimType { 
1790     $$.PAT = new PATypeHolder($1.T);
1791     $$.S = $1.S;
1792   }
1793   | OPAQUE {
1794     $$.PAT = new PATypeHolder(OpaqueType::get());
1795     $$.S = Signless;
1796   }
1797   | SymbolicValueRef {            // Named types are also simple types...
1798     const Type* tmp = getType($1);
1799     $$.PAT = new PATypeHolder(tmp);
1800     $$.S = Signless; // FIXME: what if its signed?
1801   }
1802   | '\\' EUINT64VAL {                   // Type UpReference
1803     if ($2 > (uint64_t)~0U) 
1804       error("Value out of range");
1805     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1806     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1807     $$.PAT = new PATypeHolder(OT);
1808     $$.S = Signless;
1809     UR_OUT("New Upreference!\n");
1810   }
1811   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1812     std::vector<const Type*> Params;
1813     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1814            E = $3->end(); I != E; ++I) {
1815       Params.push_back(I->PAT->get());
1816     }
1817     FunctionType::ParamAttrsList ParamAttrs;
1818     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1819     if (isVarArg) Params.pop_back();
1820
1821     $$.PAT = new PATypeHolder(
1822       HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg, 
1823                    ParamAttrs)));
1824     $$.S = $1.S;
1825     delete $1.PAT;    // Delete the return type handle
1826     delete $3;      // Delete the argument list
1827   }
1828   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1829     $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(), 
1830                                                         (unsigned)$2)));
1831     $$.S = $4.S;
1832     delete $4.PAT;
1833   }
1834   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1835      const llvm::Type* ElemTy = $4.PAT->get();
1836      if ((unsigned)$2 != $2)
1837         error("Unsigned result not equal to signed result");
1838      if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1839         error("Elements of a PackedType must be integer or floating point");
1840      if (!isPowerOf2_32($2))
1841        error("PackedType length should be a power of 2");
1842      $$.PAT = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy, 
1843                                           (unsigned)$2)));
1844      $$.S = $4.S;
1845      delete $4.PAT;
1846   }
1847   | '{' TypeListI '}' {                        // Structure type?
1848     std::vector<const Type*> Elements;
1849     for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1850            E = $2->end(); I != E; ++I)
1851       Elements.push_back(I->PAT->get());
1852     $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1853     $$.S = Signless;
1854     delete $2;
1855   }
1856   | '{' '}' {                                  // Empty structure type?
1857     $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1858     $$.S = Signless;
1859   }
1860   | '<' '{' TypeListI '}' '>' {                // Packed Structure type?
1861     std::vector<const Type*> Elements;
1862     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1863            E = $3->end(); I != E; ++I) {
1864       Elements.push_back(I->PAT->get());
1865       delete I->PAT;
1866     }
1867     $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1868     $$.S = Signless;
1869     delete $3;
1870   }
1871   | '<' '{' '}' '>' {                          // Empty packed structure type?
1872     $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1873     $$.S = Signless;
1874   }
1875   | UpRTypes '*' {                             // Pointer type?
1876     if ($1.PAT->get() == Type::LabelTy)
1877       error("Cannot form a pointer to a basic block");
1878     $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get())));
1879     $$.S = $1.S;
1880     delete $1.PAT;
1881   }
1882   ;
1883
1884 // TypeList - Used for struct declarations and as a basis for function type 
1885 // declaration type lists
1886 //
1887 TypeListI 
1888   : UpRTypes {
1889     $$ = new std::list<PATypeInfo>();
1890     $$->push_back($1); 
1891   }
1892   | TypeListI ',' UpRTypes {
1893     ($$=$1)->push_back($3);
1894   }
1895   ;
1896
1897 // ArgTypeList - List of types for a function type declaration...
1898 ArgTypeListI 
1899   : TypeListI
1900   | TypeListI ',' DOTDOTDOT {
1901     PATypeInfo VoidTI;
1902     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1903     VoidTI.S = Signless;
1904     ($$=$1)->push_back(VoidTI);
1905   }
1906   | DOTDOTDOT {
1907     $$ = new std::list<PATypeInfo>();
1908     PATypeInfo VoidTI;
1909     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1910     VoidTI.S = Signless;
1911     $$->push_back(VoidTI);
1912   }
1913   | /*empty*/ {
1914     $$ = new std::list<PATypeInfo>();
1915   }
1916   ;
1917
1918 // ConstVal - The various declarations that go into the constant pool.  This
1919 // production is used ONLY to represent constants that show up AFTER a 'const',
1920 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1921 // into other expressions (such as integers and constexprs) are handled by the
1922 // ResolvedVal, ValueRef and ConstValueRef productions.
1923 //
1924 ConstVal
1925   : Types '[' ConstVector ']' { // Nonempty unsized arr
1926     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1927     if (ATy == 0)
1928       error("Cannot make array constant with type: '" + 
1929             $1.PAT->get()->getDescription() + "'");
1930     const Type *ETy = ATy->getElementType();
1931     int NumElements = ATy->getNumElements();
1932
1933     // Verify that we have the correct size...
1934     if (NumElements != -1 && NumElements != (int)$3->size())
1935       error("Type mismatch: constant sized array initialized with " +
1936             utostr($3->size()) +  " arguments, but has size of " + 
1937             itostr(NumElements) + "");
1938
1939     // Verify all elements are correct type!
1940     std::vector<Constant*> Elems;
1941     for (unsigned i = 0; i < $3->size(); i++) {
1942       Constant *C = (*$3)[i].C;
1943       const Type* ValTy = C->getType();
1944       if (ETy != ValTy)
1945         error("Element #" + utostr(i) + " is not of type '" + 
1946               ETy->getDescription() +"' as required!\nIt is of type '"+
1947               ValTy->getDescription() + "'");
1948       Elems.push_back(C);
1949     }
1950     $$.C = ConstantArray::get(ATy, Elems);
1951     $$.S = $1.S;
1952     delete $1.PAT; 
1953     delete $3;
1954   }
1955   | Types '[' ']' {
1956     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1957     if (ATy == 0)
1958       error("Cannot make array constant with type: '" + 
1959             $1.PAT->get()->getDescription() + "'");
1960     int NumElements = ATy->getNumElements();
1961     if (NumElements != -1 && NumElements != 0) 
1962       error("Type mismatch: constant sized array initialized with 0"
1963             " arguments, but has size of " + itostr(NumElements) +"");
1964     $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1965     $$.S = $1.S;
1966     delete $1.PAT;
1967   }
1968   | Types 'c' STRINGCONSTANT {
1969     const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1970     if (ATy == 0)
1971       error("Cannot make array constant with type: '" + 
1972             $1.PAT->get()->getDescription() + "'");
1973     int NumElements = ATy->getNumElements();
1974     const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1975     if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1976       error("String arrays require type i8, not '" + ETy->getDescription() + 
1977             "'");
1978     char *EndStr = UnEscapeLexed($3, true);
1979     if (NumElements != -1 && NumElements != (EndStr-$3))
1980       error("Can't build string constant of size " + 
1981             itostr((int)(EndStr-$3)) + " when array has size " + 
1982             itostr(NumElements) + "");
1983     std::vector<Constant*> Vals;
1984     for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1985       Vals.push_back(ConstantInt::get(ETy, *C));
1986     free($3);
1987     $$.C = ConstantArray::get(ATy, Vals);
1988     $$.S = $1.S;
1989     delete $1.PAT;
1990   }
1991   | Types '<' ConstVector '>' { // Nonempty unsized arr
1992     const PackedType *PTy = dyn_cast<PackedType>($1.PAT->get());
1993     if (PTy == 0)
1994       error("Cannot make packed constant with type: '" + 
1995             $1.PAT->get()->getDescription() + "'");
1996     const Type *ETy = PTy->getElementType();
1997     int NumElements = PTy->getNumElements();
1998     // Verify that we have the correct size...
1999     if (NumElements != -1 && NumElements != (int)$3->size())
2000       error("Type mismatch: constant sized packed initialized with " +
2001             utostr($3->size()) +  " arguments, but has size of " + 
2002             itostr(NumElements) + "");
2003     // Verify all elements are correct type!
2004     std::vector<Constant*> Elems;
2005     for (unsigned i = 0; i < $3->size(); i++) {
2006       Constant *C = (*$3)[i].C;
2007       const Type* ValTy = C->getType();
2008       if (ETy != ValTy)
2009         error("Element #" + utostr(i) + " is not of type '" + 
2010               ETy->getDescription() +"' as required!\nIt is of type '"+
2011               ValTy->getDescription() + "'");
2012       Elems.push_back(C);
2013     }
2014     $$.C = ConstantPacked::get(PTy, Elems);
2015     $$.S = $1.S;
2016     delete $1.PAT;
2017     delete $3;
2018   }
2019   | Types '{' ConstVector '}' {
2020     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2021     if (STy == 0)
2022       error("Cannot make struct constant with type: '" + 
2023             $1.PAT->get()->getDescription() + "'");
2024     if ($3->size() != STy->getNumContainedTypes())
2025       error("Illegal number of initializers for structure type");
2026
2027     // Check to ensure that constants are compatible with the type initializer!
2028     std::vector<Constant*> Fields;
2029     for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2030       Constant *C = (*$3)[i].C;
2031       if (C->getType() != STy->getElementType(i))
2032         error("Expected type '" + STy->getElementType(i)->getDescription() +
2033               "' for element #" + utostr(i) + " of structure initializer");
2034       Fields.push_back(C);
2035     }
2036     $$.C = ConstantStruct::get(STy, Fields);
2037     $$.S = $1.S;
2038     delete $1.PAT;
2039     delete $3;
2040   }
2041   | Types '{' '}' {
2042     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2043     if (STy == 0)
2044       error("Cannot make struct constant with type: '" + 
2045               $1.PAT->get()->getDescription() + "'");
2046     if (STy->getNumContainedTypes() != 0)
2047       error("Illegal number of initializers for structure type");
2048     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2049     $$.S = $1.S;
2050     delete $1.PAT;
2051   }
2052   | Types '<' '{' ConstVector '}' '>' {
2053     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2054     if (STy == 0)
2055       error("Cannot make packed struct constant with type: '" + 
2056             $1.PAT->get()->getDescription() + "'");
2057     if ($4->size() != STy->getNumContainedTypes())
2058       error("Illegal number of initializers for packed structure type");
2059
2060     // Check to ensure that constants are compatible with the type initializer!
2061     std::vector<Constant*> Fields;
2062     for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2063       Constant *C = (*$4)[i].C;
2064       if (C->getType() != STy->getElementType(i))
2065         error("Expected type '" + STy->getElementType(i)->getDescription() +
2066               "' for element #" + utostr(i) + " of packed struct initializer");
2067       Fields.push_back(C);
2068     }
2069     $$.C = ConstantStruct::get(STy, Fields);
2070     $$.S = $1.S;
2071     delete $1.PAT; 
2072     delete $4;
2073   }
2074   | Types '<' '{' '}' '>' {
2075     const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2076     if (STy == 0)
2077       error("Cannot make packed struct constant with type: '" + 
2078               $1.PAT->get()->getDescription() + "'");
2079     if (STy->getNumContainedTypes() != 0)
2080       error("Illegal number of initializers for packed structure type");
2081     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2082     $$.S = $1.S;
2083     delete $1.PAT;
2084   }
2085   | Types NULL_TOK {
2086     const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2087     if (PTy == 0)
2088       error("Cannot make null pointer constant with type: '" + 
2089             $1.PAT->get()->getDescription() + "'");
2090     $$.C = ConstantPointerNull::get(PTy);
2091     $$.S = $1.S;
2092     delete $1.PAT;
2093   }
2094   | Types UNDEF {
2095     $$.C = UndefValue::get($1.PAT->get());
2096     $$.S = $1.S;
2097     delete $1.PAT;
2098   }
2099   | Types SymbolicValueRef {
2100     const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2101     if (Ty == 0)
2102       error("Global const reference must be a pointer type, not" +
2103             $1.PAT->get()->getDescription());
2104
2105     // ConstExprs can exist in the body of a function, thus creating
2106     // GlobalValues whenever they refer to a variable.  Because we are in
2107     // the context of a function, getExistingValue will search the functions
2108     // symbol table instead of the module symbol table for the global symbol,
2109     // which throws things all off.  To get around this, we just tell
2110     // getExistingValue that we are at global scope here.
2111     //
2112     Function *SavedCurFn = CurFun.CurrentFunction;
2113     CurFun.CurrentFunction = 0;
2114     Value *V = getExistingValue(Ty, $2);
2115     CurFun.CurrentFunction = SavedCurFn;
2116
2117     // If this is an initializer for a constant pointer, which is referencing a
2118     // (currently) undefined variable, create a stub now that shall be replaced
2119     // in the future with the right type of variable.
2120     //
2121     if (V == 0) {
2122       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2123       const PointerType *PT = cast<PointerType>(Ty);
2124
2125       // First check to see if the forward references value is already created!
2126       PerModuleInfo::GlobalRefsType::iterator I =
2127         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2128     
2129       if (I != CurModule.GlobalRefs.end()) {
2130         V = I->second;             // Placeholder already exists, use it...
2131         $2.destroy();
2132       } else {
2133         std::string Name;
2134         if ($2.Type == ValID::NameVal) Name = $2.Name;
2135
2136         // Create the forward referenced global.
2137         GlobalValue *GV;
2138         if (const FunctionType *FTy = 
2139                  dyn_cast<FunctionType>(PT->getElementType())) {
2140           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2141                             CurModule.CurrentModule);
2142         } else {
2143           GV = new GlobalVariable(PT->getElementType(), false,
2144                                   GlobalValue::ExternalLinkage, 0,
2145                                   Name, CurModule.CurrentModule);
2146         }
2147
2148         // Keep track of the fact that we have a forward ref to recycle it
2149         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2150         V = GV;
2151       }
2152     }
2153     $$.C = cast<GlobalValue>(V);
2154     $$.S = $1.S;
2155     delete $1.PAT;            // Free the type handle
2156   }
2157   | Types ConstExpr {
2158     if ($1.PAT->get() != $2.C->getType())
2159       error("Mismatched types for constant expression");
2160     $$ = $2;
2161     $$.S = $1.S;
2162     delete $1.PAT;
2163   }
2164   | Types ZEROINITIALIZER {
2165     const Type *Ty = $1.PAT->get();
2166     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2167       error("Cannot create a null initialized value of this type");
2168     $$.C = Constant::getNullValue(Ty);
2169     $$.S = $1.S;
2170     delete $1.PAT;
2171   }
2172   | SIntType EINT64VAL {      // integral constants
2173     const Type *Ty = $1.T;
2174     if (!ConstantInt::isValueValidForType(Ty, $2))
2175       error("Constant value doesn't fit in type");
2176     $$.C = ConstantInt::get(Ty, $2);
2177     $$.S = Signed;
2178   }
2179   | UIntType EUINT64VAL {            // integral constants
2180     const Type *Ty = $1.T;
2181     if (!ConstantInt::isValueValidForType(Ty, $2))
2182       error("Constant value doesn't fit in type");
2183     $$.C = ConstantInt::get(Ty, $2);
2184     $$.S = Unsigned;
2185   }
2186   | BOOL TRUETOK {                      // Boolean constants
2187     $$.C = ConstantInt::get(Type::Int1Ty, true);
2188     $$.S = Unsigned;
2189   }
2190   | BOOL FALSETOK {                     // Boolean constants
2191     $$.C = ConstantInt::get(Type::Int1Ty, false);
2192     $$.S = Unsigned;
2193   }
2194   | FPType FPVAL {                   // Float & Double constants
2195     if (!ConstantFP::isValueValidForType($1.T, $2))
2196       error("Floating point constant invalid for type");
2197     $$.C = ConstantFP::get($1.T, $2);
2198     $$.S = Signless;
2199   }
2200   ;
2201
2202 ConstExpr
2203   : CastOps '(' ConstVal TO Types ')' {
2204     const Type* SrcTy = $3.C->getType();
2205     const Type* DstTy = $5.PAT->get();
2206     Signedness SrcSign = $3.S;
2207     Signedness DstSign = $5.S;
2208     if (!SrcTy->isFirstClassType())
2209       error("cast constant expression from a non-primitive type: '" +
2210             SrcTy->getDescription() + "'");
2211     if (!DstTy->isFirstClassType())
2212       error("cast constant expression to a non-primitive type: '" +
2213             DstTy->getDescription() + "'");
2214     $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2215     $$.S = DstSign;
2216     delete $5.PAT;
2217   }
2218   | GETELEMENTPTR '(' ConstVal IndexList ')' {
2219     const Type *Ty = $3.C->getType();
2220     if (!isa<PointerType>(Ty))
2221       error("GetElementPtr requires a pointer operand");
2222
2223     std::vector<Value*> VIndices;
2224     std::vector<Constant*> CIndices;
2225     upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2226
2227     delete $4;
2228     $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2229     $$.S = Signless;
2230   }
2231   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2232     if (!$3.C->getType()->isInteger() ||
2233         cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2234       error("Select condition must be bool type");
2235     if ($5.C->getType() != $7.C->getType())
2236       error("Select operand types must match");
2237     $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2238     $$.S = Unsigned;
2239   }
2240   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2241     const Type *Ty = $3.C->getType();
2242     if (Ty != $5.C->getType())
2243       error("Binary operator types must match");
2244     // First, make sure we're dealing with the right opcode by upgrading from
2245     // obsolete versions.
2246     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2247
2248     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2249     // To retain backward compatibility with these early compilers, we emit a
2250     // cast to the appropriate integer type automatically if we are in the
2251     // broken case.  See PR424 for more information.
2252     if (!isa<PointerType>(Ty)) {
2253       $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2254     } else {
2255       const Type *IntPtrTy = 0;
2256       switch (CurModule.CurrentModule->getPointerSize()) {
2257       case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2258       case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2259       default: error("invalid pointer binary constant expr");
2260       }
2261       $$.C = ConstantExpr::get(Opcode, 
2262              ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2263              ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2264       $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2265     }
2266     $$.S = $3.S; 
2267   }
2268   | LogicalOps '(' ConstVal ',' ConstVal ')' {
2269     const Type* Ty = $3.C->getType();
2270     if (Ty != $5.C->getType())
2271       error("Logical operator types must match");
2272     if (!Ty->isInteger()) {
2273       if (!isa<PackedType>(Ty) || 
2274           !cast<PackedType>(Ty)->getElementType()->isInteger())
2275         error("Logical operator requires integer operands");
2276     }
2277     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2278     $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2279     $$.S = $3.S;
2280   }
2281   | SetCondOps '(' ConstVal ',' ConstVal ')' {
2282     const Type* Ty = $3.C->getType();
2283     if (Ty != $5.C->getType())
2284       error("setcc operand types must match");
2285     unsigned short pred;
2286     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2287     $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2288     $$.S = Unsigned;
2289   }
2290   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2291     if ($4.C->getType() != $6.C->getType()) 
2292       error("icmp operand types must match");
2293     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2294     $$.S = Unsigned;
2295   }
2296   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2297     if ($4.C->getType() != $6.C->getType()) 
2298       error("fcmp operand types must match");
2299     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2300     $$.S = Unsigned;
2301   }
2302   | ShiftOps '(' ConstVal ',' ConstVal ')' {
2303     if (!$5.C->getType()->isInteger() ||
2304         cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2305       error("Shift count for shift constant must be unsigned byte");
2306     const Type* Ty = $3.C->getType();
2307     if (!$3.C->getType()->isInteger())
2308       error("Shift constant expression requires integer operand");
2309     Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2310     $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2311     $$.S = $3.S;
2312   }
2313   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2314     if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2315       error("Invalid extractelement operands");
2316     $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2317     $$.S = $3.S;
2318   }
2319   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2320     if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2321       error("Invalid insertelement operands");
2322     $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2323     $$.S = $3.S;
2324   }
2325   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2326     if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2327       error("Invalid shufflevector operands");
2328     $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2329     $$.S = $3.S;
2330   }
2331   ;
2332
2333
2334 // ConstVector - A list of comma separated constants.
2335 ConstVector 
2336   : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2337   | ConstVal {
2338     $$ = new std::vector<ConstInfo>();
2339     $$->push_back($1);
2340   }
2341   ;
2342
2343
2344 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2345 GlobalType 
2346   : GLOBAL { $$ = false; } 
2347   | CONSTANT { $$ = true; }
2348   ;
2349
2350
2351 //===----------------------------------------------------------------------===//
2352 //                             Rules to match Modules
2353 //===----------------------------------------------------------------------===//
2354
2355 // Module rule: Capture the result of parsing the whole file into a result
2356 // variable...
2357 //
2358 Module 
2359   : FunctionList {
2360     $$ = ParserResult = $1;
2361     CurModule.ModuleDone();
2362   }
2363   ;
2364
2365 // FunctionList - A list of functions, preceeded by a constant pool.
2366 //
2367 FunctionList 
2368   : FunctionList Function { $$ = $1; CurFun.FunctionDone(); } 
2369   | FunctionList FunctionProto { $$ = $1; }
2370   | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }  
2371   | FunctionList IMPLEMENTATION { $$ = $1; }
2372   | ConstPool {
2373     $$ = CurModule.CurrentModule;
2374     // Emit an error if there are any unresolved types left.
2375     if (!CurModule.LateResolveTypes.empty()) {
2376       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2377       if (DID.Type == ValID::NameVal) {
2378         error("Reference to an undefined type: '"+DID.getName() + "'");
2379       } else {
2380         error("Reference to an undefined type: #" + itostr(DID.Num));
2381       }
2382     }
2383   }
2384   ;
2385
2386 // ConstPool - Constants with optional names assigned to them.
2387 ConstPool 
2388   : ConstPool OptAssign TYPE TypesV {
2389     // Eagerly resolve types.  This is not an optimization, this is a
2390     // requirement that is due to the fact that we could have this:
2391     //
2392     // %list = type { %list * }
2393     // %list = type { %list * }    ; repeated type decl
2394     //
2395     // If types are not resolved eagerly, then the two types will not be
2396     // determined to be the same type!
2397     //
2398     const Type* Ty = $4.PAT->get();
2399     ResolveTypeTo($2, Ty);
2400
2401     if (!setTypeName(Ty, $2) && !$2) {
2402       // If this is a named type that is not a redefinition, add it to the slot
2403       // table.
2404       CurModule.Types.push_back(Ty);
2405     }
2406     delete $4.PAT;
2407   }
2408   | ConstPool FunctionProto {       // Function prototypes can be in const pool
2409   }
2410   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
2411   }
2412   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2413     if ($5.C == 0) 
2414       error("Global value initializer is not a constant");
2415     CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2416   } GlobalVarAttributes {
2417     CurGV = 0;
2418   }
2419   | ConstPool OptAssign EXTERNAL GlobalType Types {
2420     const Type *Ty = $5.PAT->get();
2421     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2422     delete $5.PAT;
2423   } GlobalVarAttributes {
2424     CurGV = 0;
2425   }
2426   | ConstPool OptAssign DLLIMPORT GlobalType Types {
2427     const Type *Ty = $5.PAT->get();
2428     CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2429     delete $5.PAT;
2430   } GlobalVarAttributes {
2431     CurGV = 0;
2432   }
2433   | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2434     const Type *Ty = $5.PAT->get();
2435     CurGV = 
2436       ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2437     delete $5.PAT;
2438   } GlobalVarAttributes {
2439     CurGV = 0;
2440   }
2441   | ConstPool TARGET TargetDefinition { 
2442   }
2443   | ConstPool DEPLIBS '=' LibrariesDefinition {
2444   }
2445   | /* empty: end of list */ { 
2446   }
2447   ;
2448
2449 AsmBlock 
2450   : STRINGCONSTANT {
2451     const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2452     char *EndStr = UnEscapeLexed($1, true);
2453     std::string NewAsm($1, EndStr);
2454     free($1);
2455
2456     if (AsmSoFar.empty())
2457       CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2458     else
2459       CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2460   }
2461   ;
2462
2463 BigOrLittle 
2464   : BIG    { $$ = Module::BigEndian; }
2465   | LITTLE { $$ = Module::LittleEndian; }
2466   ;
2467
2468 TargetDefinition 
2469   : ENDIAN '=' BigOrLittle {
2470     CurModule.setEndianness($3);
2471   }
2472   | POINTERSIZE '=' EUINT64VAL {
2473     if ($3 == 32)
2474       CurModule.setPointerSize(Module::Pointer32);
2475     else if ($3 == 64)
2476       CurModule.setPointerSize(Module::Pointer64);
2477     else
2478       error("Invalid pointer size: '" + utostr($3) + "'");
2479   }
2480   | TRIPLE '=' STRINGCONSTANT {
2481     CurModule.CurrentModule->setTargetTriple($3);
2482     free($3);
2483   }
2484   | DATALAYOUT '=' STRINGCONSTANT {
2485     CurModule.CurrentModule->setDataLayout($3);
2486     free($3);
2487   }
2488   ;
2489
2490 LibrariesDefinition 
2491   : '[' LibList ']'
2492   ;
2493
2494 LibList 
2495   : LibList ',' STRINGCONSTANT {
2496       CurModule.CurrentModule->addLibrary($3);
2497       free($3);
2498   }
2499   | STRINGCONSTANT {
2500     CurModule.CurrentModule->addLibrary($1);
2501     free($1);
2502   }
2503   | /* empty: end of list */ { }
2504   ;
2505
2506 //===----------------------------------------------------------------------===//
2507 //                       Rules to match Function Headers
2508 //===----------------------------------------------------------------------===//
2509
2510 Name 
2511   : VAR_ID | STRINGCONSTANT
2512   ;
2513
2514 OptName 
2515   : Name 
2516   | /*empty*/ { $$ = 0; }
2517   ;
2518
2519 ArgVal 
2520   : Types OptName {
2521     if ($1.PAT->get() == Type::VoidTy)
2522       error("void typed arguments are invalid");
2523     $$ = new std::pair<PATypeInfo, char*>($1, $2);
2524   }
2525   ;
2526
2527 ArgListH 
2528   : ArgListH ',' ArgVal {
2529     $$ = $1;
2530     $$->push_back(*$3);
2531     delete $3;
2532   }
2533   | ArgVal {
2534     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2535     $$->push_back(*$1);
2536     delete $1;
2537   }
2538   ;
2539
2540 ArgList 
2541   : ArgListH { $$ = $1; }
2542   | ArgListH ',' DOTDOTDOT {
2543     $$ = $1;
2544     PATypeInfo VoidTI;
2545     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2546     VoidTI.S = Signless;
2547     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2548   }
2549   | DOTDOTDOT {
2550     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2551     PATypeInfo VoidTI;
2552     VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2553     VoidTI.S = Signless;
2554     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2555   }
2556   | /* empty */ { $$ = 0; }
2557   ;
2558
2559 FunctionHeaderH 
2560   : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2561     UnEscapeLexed($3);
2562     std::string FunctionName($3);
2563     free($3);  // Free strdup'd memory!
2564
2565     const Type* RetTy = $2.PAT->get();
2566     
2567     if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2568       error("LLVM functions cannot return aggregate types");
2569
2570     std::vector<const Type*> ParamTyList;
2571
2572     // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2573     // i8*. We check here for those names and override the parameter list
2574     // types to ensure the prototype is correct.
2575     if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2576       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2577     } else if (FunctionName == "llvm.va_copy") {
2578       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2579       ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2580     } else if ($5) {   // If there are arguments...
2581       for (std::vector<std::pair<PATypeInfo,char*> >::iterator 
2582            I = $5->begin(), E = $5->end(); I != E; ++I) {
2583         const Type *Ty = I->first.PAT->get();
2584         ParamTyList.push_back(Ty);
2585       }
2586     }
2587
2588     bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2589     if (isVarArg) 
2590       ParamTyList.pop_back();
2591
2592     // Convert the CSRet calling convention into the corresponding parameter
2593     // attribute.
2594     FunctionType::ParamAttrsList ParamAttrs;
2595     if ($1 == OldCallingConv::CSRet) {
2596       ParamAttrs.push_back(FunctionType::NoAttributeSet);     // result
2597       ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2598     }
2599
2600     const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
2601                                                ParamAttrs);
2602     const PointerType *PFT = PointerType::get(FT);
2603     delete $2.PAT;
2604
2605     ValID ID;
2606     if (!FunctionName.empty()) {
2607       ID = ValID::create((char*)FunctionName.c_str());
2608     } else {
2609       ID = ValID::create((int)CurModule.Values[PFT].size());
2610     }
2611
2612     Function *Fn = 0;
2613     Module* M = CurModule.CurrentModule;
2614
2615     // See if this function was forward referenced.  If so, recycle the object.
2616     if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2617       // Move the function to the end of the list, from whereever it was 
2618       // previously inserted.
2619       Fn = cast<Function>(FWRef);
2620       M->getFunctionList().remove(Fn);
2621       M->getFunctionList().push_back(Fn);
2622     } else if (!FunctionName.empty()) {
2623       GlobalValue *Conflict = M->getFunction(FunctionName);
2624       if (!Conflict)
2625         Conflict = M->getNamedGlobal(FunctionName);
2626       if (Conflict && PFT == Conflict->getType()) {
2627         if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2628           // We have two function definitions that conflict, same type, same
2629           // name. We should really check to make sure that this is the result
2630           // of integer type planes collapsing and generate an error if it is
2631           // not, but we'll just rename on the assumption that it is. However,
2632           // let's do it intelligently and rename the internal linkage one
2633           // if there is one.
2634           std::string NewName(makeNameUnique(FunctionName));
2635           if (Conflict->hasInternalLinkage()) {
2636             Conflict->setName(NewName);
2637             RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2638             CurModule.RenameMap[Key] = NewName;
2639             Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2640             InsertValue(Fn, CurModule.Values);
2641           } else {
2642             Fn = new Function(FT, CurFun.Linkage, NewName, M);
2643             InsertValue(Fn, CurModule.Values);
2644             RenameMapKey Key = std::make_pair(FunctionName,PFT);
2645             CurModule.RenameMap[Key] = NewName;
2646           }
2647         } else {
2648           // If they are not both definitions, then just use the function we
2649           // found since the types are the same.
2650           Fn = cast<Function>(Conflict);
2651
2652           // Make sure to strip off any argument names so we can't get 
2653           // conflicts.
2654           if (Fn->isDeclaration())
2655             for (Function::arg_iterator AI = Fn->arg_begin(), 
2656                  AE = Fn->arg_end(); AI != AE; ++AI)
2657               AI->setName("");
2658         }
2659       } else if (Conflict) {
2660         // We have two globals with the same name and  different types. 
2661         // Previously, this was permitted because the symbol table had 
2662         // "type planes" and names only needed to be distinct within a 
2663         // type plane. After PR411 was fixed, this is no loner the case. 
2664         // To resolve this we must rename one of the two. 
2665         if (Conflict->hasInternalLinkage()) {
2666           // We can safely renamed the Conflict.
2667           Conflict->setName(makeNameUnique(Conflict->getName()));
2668           RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2669           CurModule.RenameMap[Key] = Conflict->getName();
2670           Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2671           InsertValue(Fn, CurModule.Values);
2672         } else if (CurFun.Linkage == GlobalValue::InternalLinkage) {
2673           // We can safely rename the function we're defining
2674           std::string NewName = makeNameUnique(FunctionName);
2675           Fn = new Function(FT, CurFun.Linkage, NewName, M);
2676           InsertValue(Fn, CurModule.Values);
2677           RenameMapKey Key = std::make_pair(FunctionName,PFT);
2678           CurModule.RenameMap[Key] = NewName;
2679         } else {
2680           // We can't quietly rename either of these things, but we must
2681           // rename one of them. Generate a warning about the renaming and
2682           // elect to rename the thing we're now defining.
2683           std::string NewName = makeNameUnique(FunctionName);
2684           warning("Renaming function '" + FunctionName + "' as '" + NewName +
2685                   "' may cause linkage errors");
2686           Fn = new Function(FT, CurFun.Linkage, NewName, M);
2687           InsertValue(Fn, CurModule.Values);
2688           RenameMapKey Key = std::make_pair(FunctionName,PFT);
2689           CurModule.RenameMap[Key] = NewName;
2690         }
2691       } else {
2692         // There's no conflict, just define the function
2693         Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2694         InsertValue(Fn, CurModule.Values);
2695       }
2696     }
2697
2698     CurFun.FunctionStart(Fn);
2699
2700     if (CurFun.isDeclare) {
2701       // If we have declaration, always overwrite linkage.  This will allow us 
2702       // to correctly handle cases, when pointer to function is passed as 
2703       // argument to another function.
2704       Fn->setLinkage(CurFun.Linkage);
2705     }
2706     Fn->setCallingConv(upgradeCallingConv($1));
2707     Fn->setAlignment($8);
2708     if ($7) {
2709       Fn->setSection($7);
2710       free($7);
2711     }
2712
2713     // Add all of the arguments we parsed to the function...
2714     if ($5) {                     // Is null if empty...
2715       if (isVarArg) {  // Nuke the last entry
2716         assert($5->back().first.PAT->get() == Type::VoidTy && 
2717                $5->back().second == 0 && "Not a varargs marker");
2718         delete $5->back().first.PAT;
2719         $5->pop_back();  // Delete the last entry
2720       }
2721       Function::arg_iterator ArgIt = Fn->arg_begin();
2722       Function::arg_iterator ArgEnd = Fn->arg_end();
2723       std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2724       std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2725       for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2726         delete I->first.PAT;                      // Delete the typeholder...
2727         setValueName(ArgIt, I->second);           // Insert arg into symtab...
2728         InsertValue(ArgIt);
2729       }
2730       delete $5;                     // We're now done with the argument list
2731     }
2732   }
2733   ;
2734
2735 BEGIN 
2736   : BEGINTOK | '{'                // Allow BEGIN or '{' to start a function
2737   ;
2738
2739 FunctionHeader 
2740   : OptLinkage FunctionHeaderH BEGIN {
2741     $$ = CurFun.CurrentFunction;
2742
2743     // Make sure that we keep track of the linkage type even if there was a
2744     // previous "declare".
2745     $$->setLinkage($1);
2746   }
2747   ;
2748
2749 END 
2750   : ENDTOK | '}'                    // Allow end of '}' to end a function
2751   ;
2752
2753 Function 
2754   : BasicBlockList END {
2755     $$ = $1;
2756   };
2757
2758 FnDeclareLinkage
2759   : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
2760   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
2761   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
2762   ;
2763   
2764 FunctionProto 
2765   : DECLARE { CurFun.isDeclare = true; } 
2766      FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
2767     $$ = CurFun.CurrentFunction;
2768     CurFun.FunctionDone();
2769     
2770   }
2771   ;
2772
2773 //===----------------------------------------------------------------------===//
2774 //                        Rules to match Basic Blocks
2775 //===----------------------------------------------------------------------===//
2776
2777 OptSideEffect 
2778   : /* empty */ { $$ = false; }
2779   | SIDEEFFECT { $$ = true; }
2780   ;
2781
2782 ConstValueRef 
2783     // A reference to a direct constant
2784   : ESINT64VAL {    $$ = ValID::create($1); }
2785   | EUINT64VAL { $$ = ValID::create($1); }
2786   | FPVAL { $$ = ValID::create($1); } 
2787   | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); } 
2788   | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2789   | NULL_TOK { $$ = ValID::createNull(); }
2790   | UNDEF { $$ = ValID::createUndef(); }
2791   | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2792   | '<' ConstVector '>' { // Nonempty unsized packed vector
2793     const Type *ETy = (*$2)[0].C->getType();
2794     int NumElements = $2->size(); 
2795     PackedType* pt = PackedType::get(ETy, NumElements);
2796     PATypeHolder* PTy = new PATypeHolder(
2797       HandleUpRefs(PackedType::get(ETy, NumElements)));
2798     
2799     // Verify all elements are correct type!
2800     std::vector<Constant*> Elems;
2801     for (unsigned i = 0; i < $2->size(); i++) {
2802       Constant *C = (*$2)[i].C;
2803       const Type *CTy = C->getType();
2804       if (ETy != CTy)
2805         error("Element #" + utostr(i) + " is not of type '" + 
2806               ETy->getDescription() +"' as required!\nIt is of type '" +
2807               CTy->getDescription() + "'");
2808       Elems.push_back(C);
2809     }
2810     $$ = ValID::create(ConstantPacked::get(pt, Elems));
2811     delete PTy; delete $2;
2812   }
2813   | ConstExpr {
2814     $$ = ValID::create($1.C);
2815   }
2816   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2817     char *End = UnEscapeLexed($3, true);
2818     std::string AsmStr = std::string($3, End);
2819     End = UnEscapeLexed($5, true);
2820     std::string Constraints = std::string($5, End);
2821     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2822     free($3);
2823     free($5);
2824   }
2825   ;
2826
2827 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2828 // another value.
2829 //
2830 SymbolicValueRef 
2831   : INTVAL {  $$ = ValID::create($1); }
2832   | Name   {  $$ = ValID::create($1); }
2833   ;
2834
2835 // ValueRef - A reference to a definition... either constant or symbolic
2836 ValueRef 
2837   : SymbolicValueRef | ConstValueRef
2838   ;
2839
2840
2841 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2842 // type immediately preceeds the value reference, and allows complex constant
2843 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2844 ResolvedVal 
2845   : Types ValueRef { 
2846     const Type *Ty = $1.PAT->get();
2847     $$.S = $1.S;
2848     $$.V = getVal(Ty, $2); 
2849     delete $1.PAT;
2850   }
2851   ;
2852
2853 BasicBlockList 
2854   : BasicBlockList BasicBlock {
2855     $$ = $1;
2856   }
2857   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2858     $$ = $1;
2859   };
2860
2861
2862 // Basic blocks are terminated by branching instructions: 
2863 // br, br/cc, switch, ret
2864 //
2865 BasicBlock 
2866   : InstructionList OptAssign BBTerminatorInst  {
2867     setValueName($3, $2);
2868     InsertValue($3);
2869     $1->getInstList().push_back($3);
2870     InsertValue($1);
2871     $$ = $1;
2872   }
2873   ;
2874
2875 InstructionList
2876   : InstructionList Inst {
2877     if ($2.I)
2878       $1->getInstList().push_back($2.I);
2879     $$ = $1;
2880   }
2881   | /* empty */ {
2882     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2883     // Make sure to move the basic block to the correct location in the
2884     // function, instead of leaving it inserted wherever it was first
2885     // referenced.
2886     Function::BasicBlockListType &BBL = 
2887       CurFun.CurrentFunction->getBasicBlockList();
2888     BBL.splice(BBL.end(), BBL, $$);
2889   }
2890   | LABELSTR {
2891     $$ = CurBB = getBBVal(ValID::create($1), true);
2892     // Make sure to move the basic block to the correct location in the
2893     // function, instead of leaving it inserted wherever it was first
2894     // referenced.
2895     Function::BasicBlockListType &BBL = 
2896       CurFun.CurrentFunction->getBasicBlockList();
2897     BBL.splice(BBL.end(), BBL, $$);
2898   }
2899   ;
2900
2901 Unwind : UNWIND | EXCEPT;
2902
2903 BBTerminatorInst 
2904   : RET ResolvedVal {              // Return with a result...
2905     $$ = new ReturnInst($2.V);
2906   }
2907   | RET VOID {                                       // Return with no result...
2908     $$ = new ReturnInst();
2909   }
2910   | BR LABEL ValueRef {                         // Unconditional Branch...
2911     BasicBlock* tmpBB = getBBVal($3);
2912     $$ = new BranchInst(tmpBB);
2913   }                                                  // Conditional Branch...
2914   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2915     BasicBlock* tmpBBA = getBBVal($6);
2916     BasicBlock* tmpBBB = getBBVal($9);
2917     Value* tmpVal = getVal(Type::Int1Ty, $3);
2918     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2919   }
2920   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2921     Value* tmpVal = getVal($2.T, $3);
2922     BasicBlock* tmpBB = getBBVal($6);
2923     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2924     $$ = S;
2925     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2926       E = $8->end();
2927     for (; I != E; ++I) {
2928       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2929           S->addCase(CI, I->second);
2930       else
2931         error("Switch case is constant, but not a simple integer");
2932     }
2933     delete $8;
2934   }
2935   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2936     Value* tmpVal = getVal($2.T, $3);
2937     BasicBlock* tmpBB = getBBVal($6);
2938     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2939     $$ = S;
2940   }
2941   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2942     TO LABEL ValueRef Unwind LABEL ValueRef {
2943     const PointerType *PFTy;
2944     const FunctionType *Ty;
2945
2946     if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
2947         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2948       // Pull out the types of all of the arguments...
2949       std::vector<const Type*> ParamTypes;
2950       if ($6) {
2951         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2952              I != E; ++I)
2953           ParamTypes.push_back((*I).V->getType());
2954       }
2955       FunctionType::ParamAttrsList ParamAttrs;
2956       if ($2 == OldCallingConv::CSRet) {
2957         ParamAttrs.push_back(FunctionType::NoAttributeSet);
2958         ParamAttrs.push_back(FunctionType::StructRetAttribute);
2959       }
2960       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2961       if (isVarArg) ParamTypes.pop_back();
2962       Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
2963       PFTy = PointerType::get(Ty);
2964     }
2965     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2966     BasicBlock *Normal = getBBVal($10);
2967     BasicBlock *Except = getBBVal($13);
2968
2969     // Create the call node...
2970     if (!$6) {                                   // Has no arguments?
2971       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2972     } else {                                     // Has arguments?
2973       // Loop through FunctionType's arguments and ensure they are specified
2974       // correctly!
2975       //
2976       FunctionType::param_iterator I = Ty->param_begin();
2977       FunctionType::param_iterator E = Ty->param_end();
2978       std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2979
2980       std::vector<Value*> Args;
2981       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2982         if ((*ArgI).V->getType() != *I)
2983           error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2984                 (*I)->getDescription() + "'");
2985         Args.push_back((*ArgI).V);
2986       }
2987
2988       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2989         error("Invalid number of parameters detected");
2990
2991       $$ = new InvokeInst(V, Normal, Except, Args);
2992     }
2993     cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
2994     delete $3.PAT;
2995     delete $6;
2996   }
2997   | Unwind {
2998     $$ = new UnwindInst();
2999   }
3000   | UNREACHABLE {
3001     $$ = new UnreachableInst();
3002   }
3003   ;
3004
3005 JumpTable 
3006   : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3007     $$ = $1;
3008     Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3009     
3010     if (V == 0)
3011       error("May only switch on a constant pool value");
3012
3013     BasicBlock* tmpBB = getBBVal($6);
3014     $$->push_back(std::make_pair(V, tmpBB));
3015   }
3016   | IntType ConstValueRef ',' LABEL ValueRef {
3017     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3018     Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3019
3020     if (V == 0)
3021       error("May only switch on a constant pool value");
3022
3023     BasicBlock* tmpBB = getBBVal($5);
3024     $$->push_back(std::make_pair(V, tmpBB)); 
3025   }
3026   ;
3027
3028 Inst 
3029   : OptAssign InstVal {
3030     bool omit = false;
3031     if ($1)
3032       if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3033         if (BCI->getSrcTy() == BCI->getDestTy() && 
3034             BCI->getOperand(0)->getName() == $1)
3035           // This is a useless bit cast causing a name redefinition. It is
3036           // a bit cast from a type to the same type of an operand with the
3037           // same name as the name we would give this instruction. Since this
3038           // instruction results in no code generation, it is safe to omit
3039           // the instruction. This situation can occur because of collapsed
3040           // type planes. For example:
3041           //   %X = add int %Y, %Z
3042           //   %X = cast int %Y to uint
3043           // After upgrade, this looks like:
3044           //   %X = add i32 %Y, %Z
3045           //   %X = bitcast i32 to i32
3046           // The bitcast is clearly useless so we omit it.
3047           omit = true;
3048     if (omit) {
3049       $$.I = 0;
3050       $$.S = Signless;
3051     } else {
3052       setValueName($2.I, $1);
3053       InsertValue($2.I);
3054       $$ = $2;
3055     }
3056   };
3057
3058 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
3059     $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3060     $$.S = $1.S;
3061     Value* tmpVal = getVal($1.PAT->get(), $3);
3062     BasicBlock* tmpBB = getBBVal($5);
3063     $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3064     delete $1.PAT;
3065   }
3066   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3067     $$ = $1;
3068     Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3069     BasicBlock* tmpBB = getBBVal($6);
3070     $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3071   }
3072   ;
3073
3074 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
3075     $$ = new std::vector<ValueInfo>();
3076     $$->push_back($1);
3077   }
3078   | ValueRefList ',' ResolvedVal {
3079     $$ = $1;
3080     $1->push_back($3);
3081   };
3082
3083 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3084 ValueRefListE 
3085   : ValueRefList 
3086   | /*empty*/ { $$ = 0; }
3087   ;
3088
3089 OptTailCall 
3090   : TAIL CALL {
3091     $$ = true;
3092   }
3093   | CALL {
3094     $$ = false;
3095   }
3096   ;
3097
3098 InstVal 
3099   : ArithmeticOps Types ValueRef ',' ValueRef {
3100     const Type* Ty = $2.PAT->get();
3101     if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3102       error("Arithmetic operator requires integer, FP, or packed operands");
3103     if (isa<PackedType>(Ty) && 
3104         ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3105       error("Remainder not supported on packed types");
3106     // Upgrade the opcode from obsolete versions before we do anything with it.
3107     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3108     Value* val1 = getVal(Ty, $3); 
3109     Value* val2 = getVal(Ty, $5);
3110     $$.I = BinaryOperator::create(Opcode, val1, val2);
3111     if ($$.I == 0)
3112       error("binary operator returned null");
3113     $$.S = $2.S;
3114     delete $2.PAT;
3115   }
3116   | LogicalOps Types ValueRef ',' ValueRef {
3117     const Type *Ty = $2.PAT->get();
3118     if (!Ty->isInteger()) {
3119       if (!isa<PackedType>(Ty) ||
3120           !cast<PackedType>(Ty)->getElementType()->isInteger())
3121         error("Logical operator requires integral operands");
3122     }
3123     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3124     Value* tmpVal1 = getVal(Ty, $3);
3125     Value* tmpVal2 = getVal(Ty, $5);
3126     $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3127     if ($$.I == 0)
3128       error("binary operator returned null");
3129     $$.S = $2.S;
3130     delete $2.PAT;
3131   }
3132   | SetCondOps Types ValueRef ',' ValueRef {
3133     const Type* Ty = $2.PAT->get();
3134     if(isa<PackedType>(Ty))
3135       error("PackedTypes currently not supported in setcc instructions");
3136     unsigned short pred;
3137     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3138     Value* tmpVal1 = getVal(Ty, $3);
3139     Value* tmpVal2 = getVal(Ty, $5);
3140     $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3141     if ($$.I == 0)
3142       error("binary operator returned null");
3143     $$.S = Unsigned;
3144     delete $2.PAT;
3145   }
3146   | ICMP IPredicates Types ValueRef ',' ValueRef {
3147     const Type *Ty = $3.PAT->get();
3148     if (isa<PackedType>(Ty)) 
3149       error("PackedTypes currently not supported in icmp instructions");
3150     else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3151       error("icmp requires integer or pointer typed operands");
3152     Value* tmpVal1 = getVal(Ty, $4);
3153     Value* tmpVal2 = getVal(Ty, $6);
3154     $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3155     $$.S = Unsigned;
3156     delete $3.PAT;
3157   }
3158   | FCMP FPredicates Types ValueRef ',' ValueRef {
3159     const Type *Ty = $3.PAT->get();
3160     if (isa<PackedType>(Ty))
3161       error("PackedTypes currently not supported in fcmp instructions");
3162     else if (!Ty->isFloatingPoint())
3163       error("fcmp instruction requires floating point operands");
3164     Value* tmpVal1 = getVal(Ty, $4);
3165     Value* tmpVal2 = getVal(Ty, $6);
3166     $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3167     $$.S = Unsigned;
3168     delete $3.PAT;
3169   }
3170   | NOT ResolvedVal {
3171     warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3172     const Type *Ty = $2.V->getType();
3173     Value *Ones = ConstantInt::getAllOnesValue(Ty);
3174     if (Ones == 0)
3175       error("Expected integral type for not instruction");
3176     $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3177     if ($$.I == 0)
3178       error("Could not create a xor instruction");
3179     $$.S = $2.S
3180   }
3181   | ShiftOps ResolvedVal ',' ResolvedVal {
3182     if (!$4.V->getType()->isInteger() ||
3183         cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3184       error("Shift amount must be int8");
3185     const Type* Ty = $2.V->getType();
3186     if (!Ty->isInteger())
3187       error("Shift constant expression requires integer operand");
3188     Value* ShiftAmt = 0;
3189     if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3190       if (Constant *C = dyn_cast<Constant>($4.V))
3191         ShiftAmt = ConstantExpr::getZExt(C, Ty);
3192       else
3193         ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3194     else
3195       ShiftAmt = $4.V;
3196     $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3197     $$.S = $2.S;
3198   }
3199   | CastOps ResolvedVal TO Types {
3200     const Type *DstTy = $4.PAT->get();
3201     if (!DstTy->isFirstClassType())
3202       error("cast instruction to a non-primitive type: '" +
3203             DstTy->getDescription() + "'");
3204     $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3205     $$.S = $4.S;
3206     delete $4.PAT;
3207   }
3208   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3209     if (!$2.V->getType()->isInteger() ||
3210         cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3211       error("select condition must be bool");
3212     if ($4.V->getType() != $6.V->getType())
3213       error("select value types should match");
3214     $$.I = new SelectInst($2.V, $4.V, $6.V);
3215     $$.S = $2.S;
3216   }
3217   | VAARG ResolvedVal ',' Types {
3218     const Type *Ty = $4.PAT->get();
3219     NewVarArgs = true;
3220     $$.I = new VAArgInst($2.V, Ty);
3221     $$.S = $4.S;
3222     delete $4.PAT;
3223   }
3224   | VAARG_old ResolvedVal ',' Types {
3225     const Type* ArgTy = $2.V->getType();
3226     const Type* DstTy = $4.PAT->get();
3227     ObsoleteVarArgs = true;
3228     Function* NF = cast<Function>(CurModule.CurrentModule->
3229       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3230
3231     //b = vaarg a, t -> 
3232     //foo = alloca 1 of t
3233     //bar = vacopy a 
3234     //store bar -> foo
3235     //b = vaarg foo, t
3236     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3237     CurBB->getInstList().push_back(foo);
3238     CallInst* bar = new CallInst(NF, $2.V);
3239     CurBB->getInstList().push_back(bar);
3240     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3241     $$.I = new VAArgInst(foo, DstTy);
3242     $$.S = $4.S;
3243     delete $4.PAT;
3244   }
3245   | VANEXT_old ResolvedVal ',' Types {
3246     const Type* ArgTy = $2.V->getType();
3247     const Type* DstTy = $4.PAT->get();
3248     ObsoleteVarArgs = true;
3249     Function* NF = cast<Function>(CurModule.CurrentModule->
3250       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3251
3252     //b = vanext a, t ->
3253     //foo = alloca 1 of t
3254     //bar = vacopy a
3255     //store bar -> foo
3256     //tmp = vaarg foo, t
3257     //b = load foo
3258     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3259     CurBB->getInstList().push_back(foo);
3260     CallInst* bar = new CallInst(NF, $2.V);
3261     CurBB->getInstList().push_back(bar);
3262     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3263     Instruction* tmp = new VAArgInst(foo, DstTy);
3264     CurBB->getInstList().push_back(tmp);
3265     $$.I = new LoadInst(foo);
3266     $$.S = $4.S;
3267     delete $4.PAT;
3268   }
3269   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3270     if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3271       error("Invalid extractelement operands");
3272     $$.I = new ExtractElementInst($2.V, $4.V);
3273     $$.S = $2.S;
3274   }
3275   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3276     if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3277       error("Invalid insertelement operands");
3278     $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3279     $$.S = $2.S;
3280   }
3281   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3282     if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3283       error("Invalid shufflevector operands");
3284     $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3285     $$.S = $2.S;
3286   }
3287   | PHI_TOK PHIList {
3288     const Type *Ty = $2.P->front().first->getType();
3289     if (!Ty->isFirstClassType())
3290       error("PHI node operands must be of first class type");
3291     PHINode *PHI = new PHINode(Ty);
3292     PHI->reserveOperandSpace($2.P->size());
3293     while ($2.P->begin() != $2.P->end()) {
3294       if ($2.P->front().first->getType() != Ty) 
3295         error("All elements of a PHI node must be of the same type");
3296       PHI->addIncoming($2.P->front().first, $2.P->front().second);
3297       $2.P->pop_front();
3298     }
3299     $$.I = PHI;
3300     $$.S = $2.S;
3301     delete $2.P;  // Free the list...
3302   }
3303   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
3304
3305     // Handle the short call syntax
3306     const PointerType *PFTy;
3307     const FunctionType *FTy;
3308     if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3309         !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3310       // Pull out the types of all of the arguments...
3311       std::vector<const Type*> ParamTypes;
3312       if ($6) {
3313         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3314              I != E; ++I)
3315           ParamTypes.push_back((*I).V->getType());
3316       }
3317
3318       FunctionType::ParamAttrsList ParamAttrs;
3319       if ($2 == OldCallingConv::CSRet) {
3320         ParamAttrs.push_back(FunctionType::NoAttributeSet);
3321         ParamAttrs.push_back(FunctionType::StructRetAttribute);
3322       }
3323       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3324       if (isVarArg) ParamTypes.pop_back();
3325
3326       const Type *RetTy = $3.PAT->get();
3327       if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3328         error("Functions cannot return aggregate types");
3329
3330       FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3331       PFTy = PointerType::get(FTy);
3332     }
3333
3334     // First upgrade any intrinsic calls.
3335     std::vector<Value*> Args;
3336     if ($6)
3337       for (unsigned i = 0, e = $6->size(); i < e; ++i) 
3338         Args.push_back((*$6)[i].V);
3339     Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3340
3341     // If we got an upgraded intrinsic
3342     if (Inst) {
3343       $$.I = Inst;
3344       $$.S = Signless;
3345     } else {
3346       // Get the function we're calling
3347       Value *V = getVal(PFTy, $4);
3348
3349       // Check the argument values match
3350       if (!$6) {                                   // Has no arguments?
3351         // Make sure no arguments is a good thing!
3352         if (FTy->getNumParams() != 0)
3353           error("No arguments passed to a function that expects arguments");
3354       } else {                                     // Has arguments?
3355         // Loop through FunctionType's arguments and ensure they are specified
3356         // correctly!
3357         //
3358         FunctionType::param_iterator I = FTy->param_begin();
3359         FunctionType::param_iterator E = FTy->param_end();
3360         std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3361
3362         for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3363           if ((*ArgI).V->getType() != *I)
3364             error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3365                   (*I)->getDescription() + "'");
3366
3367         if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3368           error("Invalid number of parameters detected");
3369       }
3370
3371       // Create the call instruction
3372       CallInst *CI = new CallInst(V, Args);
3373       CI->setTailCall($1);
3374       CI->setCallingConv(upgradeCallingConv($2));
3375       $$.I = CI;
3376       $$.S = $3.S;
3377     }
3378     delete $3.PAT;
3379     delete $6;
3380   }
3381   | MemoryInst {
3382     $$ = $1;
3383   }
3384   ;
3385
3386
3387 // IndexList - List of indices for GEP based instructions...
3388 IndexList 
3389   : ',' ValueRefList { $$ = $2; } 
3390   | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3391   ;
3392
3393 OptVolatile 
3394   : VOLATILE { $$ = true; }
3395   | /* empty */ { $$ = false; }
3396   ;
3397
3398 MemoryInst 
3399   : MALLOC Types OptCAlign {
3400     const Type *Ty = $2.PAT->get();
3401     $$.S = $2.S;
3402     $$.I = new MallocInst(Ty, 0, $3);
3403     delete $2.PAT;
3404   }
3405   | MALLOC Types ',' UINT ValueRef OptCAlign {
3406     const Type *Ty = $2.PAT->get();
3407     $$.S = $2.S;
3408     $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3409     delete $2.PAT;
3410   }
3411   | ALLOCA Types OptCAlign {
3412     const Type *Ty = $2.PAT->get();
3413     $$.S = $2.S;
3414     $$.I = new AllocaInst(Ty, 0, $3);
3415     delete $2.PAT;
3416   }
3417   | ALLOCA Types ',' UINT ValueRef OptCAlign {
3418     const Type *Ty = $2.PAT->get();
3419     $$.S = $2.S;
3420     $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3421     delete $2.PAT;
3422   }
3423   | FREE ResolvedVal {
3424     const Type *PTy = $2.V->getType();
3425     if (!isa<PointerType>(PTy))
3426       error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3427     $$.I = new FreeInst($2.V);
3428     $$.S = Signless;
3429   }
3430   | OptVolatile LOAD Types ValueRef {
3431     const Type* Ty = $3.PAT->get();
3432     $$.S = $3.S;
3433     if (!isa<PointerType>(Ty))
3434       error("Can't load from nonpointer type: " + Ty->getDescription());
3435     if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3436       error("Can't load from pointer of non-first-class type: " +
3437                      Ty->getDescription());
3438     Value* tmpVal = getVal(Ty, $4);
3439     $$.I = new LoadInst(tmpVal, "", $1);
3440     delete $3.PAT;
3441   }
3442   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3443     const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3444     if (!PTy)
3445       error("Can't store to a nonpointer type: " + 
3446              $5.PAT->get()->getDescription());
3447     const Type *ElTy = PTy->getElementType();
3448     Value *StoreVal = $3.V;
3449     Value* tmpVal = getVal(PTy, $6);
3450     if (ElTy != $3.V->getType()) {
3451       StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3452       if (!StoreVal)
3453         error("Can't store '" + $3.V->getType()->getDescription() +
3454               "' into space of type '" + ElTy->getDescription() + "'");
3455       else {
3456         PTy = PointerType::get(StoreVal->getType());
3457         if (Constant *C = dyn_cast<Constant>(tmpVal))
3458           tmpVal = ConstantExpr::getBitCast(C, PTy);
3459         else
3460           tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3461       }
3462     }
3463     $$.I = new StoreInst(StoreVal, tmpVal, $1);
3464     $$.S = Signless;
3465     delete $5.PAT;
3466   }
3467   | GETELEMENTPTR Types ValueRef IndexList {
3468     const Type* Ty = $2.PAT->get();
3469     if (!isa<PointerType>(Ty))
3470       error("getelementptr insn requires pointer operand");
3471
3472     std::vector<Value*> VIndices;
3473     upgradeGEPIndices(Ty, $4, VIndices);
3474
3475     Value* tmpVal = getVal(Ty, $3);
3476     $$.I = new GetElementPtrInst(tmpVal, VIndices);
3477     $$.S = Signless;
3478     delete $2.PAT;
3479     delete $4;
3480   };
3481
3482
3483 %%
3484
3485 int yyerror(const char *ErrorMsg) {
3486   std::string where 
3487     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3488                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3489   std::string errMsg = where + "error: " + std::string(ErrorMsg);
3490   if (yychar != YYEMPTY && yychar != 0)
3491     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3492               "'.";
3493   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3494   std::cout << "llvm-upgrade: parse failed.\n";
3495   exit(1);
3496 }
3497
3498 void warning(const std::string& ErrorMsg) {
3499   std::string where 
3500     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3501                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3502   std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3503   if (yychar != YYEMPTY && yychar != 0)
3504     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3505               "'.";
3506   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3507 }
3508
3509 void error(const std::string& ErrorMsg, int LineNo) {
3510   if (LineNo == -1) LineNo = Upgradelineno;
3511   Upgradelineno = LineNo;
3512   yyerror(ErrorMsg.c_str());
3513 }
3514