d5292a0464ad8ba6e72bf1b2f3a9aaeeaba29ffa
[oota-llvm.git] / tools / llvm-upgrade / UpgradeParser.y
1 //===-- UpgradeParser.y - Upgrade parser for llvm assmbly -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM 1.9 assembly language.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "UpgradeInternals.h"
16 #include <algorithm>
17 #include <map>
18 #include <utility>
19 #include <iostream>
20
21 #define YYERROR_VERBOSE 1
22 #define YYINCLUDED_STDLIB_H
23 #define YYDEBUG 1
24
25 int yylex();                       // declaration" of xxx warnings.
26 int yyparse();
27 extern int yydebug;
28
29 static std::string CurFilename;
30 static std::ostream *O = 0;
31 std::istream* LexInput = 0;
32 unsigned SizeOfPointer = 32;
33 static uint64_t unique = 1;
34
35 // This bool controls whether attributes are ever added to function declarations
36 // definitions and calls.
37 static bool AddAttributes = false;
38
39 // This bool is used to communicate between the InstVal and Inst rules about
40 // whether or not a cast should be deleted. When the flag is set, InstVal has
41 // determined that the cast is a candidate. However, it can only be deleted if
42 // the value being casted is the same value name as the instruction. The Inst
43 // rule makes that comparison if the flag is set and comments out the
44 // instruction if they match.
45 static bool deleteUselessCastFlag = false;
46 static std::string* deleteUselessCastName = 0;
47
48 typedef std::vector<const TypeInfo*> TypeVector;
49 static TypeVector EnumeratedTypes;
50 typedef std::map<std::string,const TypeInfo*> TypeMap;
51 static TypeMap NamedTypes;
52 typedef std::map<const TypeInfo*,std::string> TypePlaneMap;
53 typedef std::map<std::string,TypePlaneMap> GlobalsTypeMap;
54 static GlobalsTypeMap Globals;
55
56 static void warning(const std::string& msg);
57
58 void destroy(ValueList* VL) {
59   while (!VL->empty()) {
60     ValueInfo& VI = VL->back();
61     VI.destroy();
62     VL->pop_back();
63   }
64   delete VL;
65 }
66
67 void UpgradeAssembly(const std::string &infile, std::istream& in, 
68                      std::ostream &out, bool debug, bool addAttrs)
69 {
70   Upgradelineno = 1; 
71   CurFilename = infile;
72   LexInput = &in;
73   yydebug = debug;
74   AddAttributes = addAttrs;
75   O = &out;
76
77   if (yyparse()) {
78     std::cerr << "Parse failed.\n";
79     out << "llvm-upgrade parse failed.\n";
80     exit(1);
81   }
82 }
83
84 TypeInfo::TypeRegMap TypeInfo::registry;
85
86 const TypeInfo* TypeInfo::get(const std::string &newType, Types oldType) {
87   TypeInfo* Ty = new TypeInfo();
88   Ty->newTy = newType;
89   Ty->oldTy = oldType;
90   return add_new_type(Ty);
91 }
92
93 const TypeInfo* TypeInfo::get(const std::string& newType, Types oldType, 
94                               const TypeInfo* eTy, const TypeInfo* rTy) {
95   TypeInfo* Ty= new TypeInfo();
96   Ty->newTy = newType;
97   Ty->oldTy = oldType;
98   Ty->elemTy = const_cast<TypeInfo*>(eTy);
99   Ty->resultTy = const_cast<TypeInfo*>(rTy);
100   return add_new_type(Ty);
101 }
102
103 const TypeInfo* TypeInfo::get(const std::string& newType, Types oldType, 
104                               const TypeInfo *eTy, uint64_t elems) {
105   TypeInfo* Ty = new TypeInfo();
106   Ty->newTy = newType;
107   Ty->oldTy = oldType;
108   Ty->elemTy = const_cast<TypeInfo*>(eTy);
109   Ty->nelems = elems;
110   return  add_new_type(Ty);
111 }
112
113 const TypeInfo* TypeInfo::get(const std::string& newType, Types oldType, 
114                               TypeList* TL) {
115   TypeInfo* Ty = new TypeInfo();
116   Ty->newTy = newType;
117   Ty->oldTy = oldType;
118   Ty->elements = TL;
119   return add_new_type(Ty);
120 }
121
122 const TypeInfo* TypeInfo::get(const std::string& newType, const TypeInfo* resTy,
123                               TypeList* TL) {
124   TypeInfo* Ty = new TypeInfo();
125   Ty->newTy = newType;
126   Ty->oldTy = FunctionTy;
127   Ty->resultTy = const_cast<TypeInfo*>(resTy);
128   Ty->elements = TL;
129   return add_new_type(Ty);
130 }
131
132 const TypeInfo* TypeInfo::resolve() const {
133   if (isUnresolved()) {
134     if (getNewTy()[0] == '%' && isdigit(getNewTy()[1])) {
135       unsigned ref = atoi(&((getNewTy().c_str())[1])); // skip the %
136       if (ref < EnumeratedTypes.size()) {
137         return EnumeratedTypes[ref];
138       } else {
139         std::string msg("Can't resolve numbered type: ");
140         msg += getNewTy();
141         yyerror(msg.c_str());
142       }
143     } else {
144       TypeMap::iterator I = NamedTypes.find(getNewTy());
145       if (I != NamedTypes.end()) {
146         return I->second;
147       } else {
148         std::string msg("Cannot resolve type: ");
149         msg += getNewTy();
150         yyerror(msg.c_str());
151       }
152     }
153   }
154   // otherwise its already resolved.
155   return this;
156 }
157
158 bool TypeInfo::operator<(const TypeInfo& that) const {
159   if (this == &that)
160     return false;
161   if (oldTy != that.oldTy)
162     return oldTy < that.oldTy;
163   switch (oldTy) {
164     case UpRefTy: {
165       unsigned thisUp = this->getUpRefNum();
166       unsigned thatUp = that.getUpRefNum();
167       return thisUp < thatUp;
168     }
169     case PackedTy:
170     case ArrayTy:
171       if (this->nelems != that.nelems)
172         return nelems < that.nelems;
173     case PointerTy: {
174       const TypeInfo* thisTy = this->elemTy;
175       const TypeInfo* thatTy = that.elemTy;
176       return *thisTy < *thatTy;
177     }
178     case FunctionTy: {
179       const TypeInfo* thisTy = this->resultTy;
180       const TypeInfo* thatTy = that.resultTy;
181       if (!thisTy->sameOldTyAs(thatTy))
182         return *thisTy < *thatTy;
183       /* FALL THROUGH */
184     }
185     case StructTy:
186     case PackedStructTy: {
187       if (elements->size() != that.elements->size())
188         return elements->size() < that.elements->size();
189       for (unsigned i = 0; i < elements->size(); i++) {
190         const TypeInfo* thisTy = (*this->elements)[i];
191         const TypeInfo* thatTy = (*that.elements)[i];
192         if (!thisTy->sameOldTyAs(thatTy))
193           return *thisTy < *thatTy;
194       }
195       break;
196     }
197     case UnresolvedTy:
198       return this->newTy < that.newTy;
199     default:
200       break;
201   }
202   return false; 
203 }
204
205 bool TypeInfo::sameOldTyAs(const TypeInfo* that) const {
206   if (that == 0)
207     return false;
208   if ( this == that ) 
209     return true;
210   if (oldTy != that->oldTy)
211     return false;
212   switch (oldTy) {
213     case PackedTy:
214     case ArrayTy:
215       if (nelems != that->nelems)
216         return false;
217       /* FALL THROUGH */
218     case PointerTy: {
219       const TypeInfo* thisTy = this->elemTy;
220       const TypeInfo* thatTy = that->elemTy;
221       return thisTy->sameOldTyAs(thatTy);
222     }
223     case FunctionTy: {
224       const TypeInfo* thisTy = this->resultTy;
225       const TypeInfo* thatTy = that->resultTy;
226       if (!thisTy->sameOldTyAs(thatTy))
227         return false;
228       /* FALL THROUGH */
229     }
230     case StructTy:
231     case PackedStructTy: {
232       if (elements->size() != that->elements->size())
233         return false;
234       for (unsigned i = 0; i < elements->size(); i++) {
235         const TypeInfo* thisTy = (*this->elements)[i];
236         const TypeInfo* thatTy = (*that->elements)[i];
237         if (!thisTy->sameOldTyAs(thatTy))
238           return false;
239       }
240       return true;
241     }
242     case UnresolvedTy:
243       return this->newTy == that->newTy;
244     default:
245       return true; // for all others oldTy == that->oldTy is sufficient
246   }
247   return true;
248 }
249
250 bool TypeInfo::isUnresolvedDeep() const {
251   switch (oldTy) {
252     case UnresolvedTy: 
253       return true;
254     case PackedTy:
255     case ArrayTy:
256     case PointerTy:
257       return elemTy->isUnresolvedDeep();
258     case PackedStructTy:
259     case StructTy:
260       for (unsigned i = 0; i < elements->size(); i++)
261         if ((*elements)[i]->isUnresolvedDeep())
262           return true;
263       return false;
264     default:
265       return false;
266   }
267 }
268
269 unsigned TypeInfo::getBitWidth() const {
270   switch (oldTy) {
271     default:
272     case LabelTy:
273     case VoidTy : return 0;
274     case BoolTy : return 1;
275     case SByteTy: case UByteTy : return 8;
276     case ShortTy: case UShortTy : return 16;
277     case IntTy: case UIntTy: case FloatTy: return 32;
278     case LongTy: case ULongTy: case DoubleTy : return 64;
279     case PointerTy: return SizeOfPointer; // global var
280     case PackedTy: 
281     case ArrayTy: 
282       return nelems * elemTy->getBitWidth();
283     case StructTy:
284     case PackedStructTy: {
285       uint64_t size = 0;
286       for (unsigned i = 0; i < elements->size(); i++) {
287         size += (*elements)[i]->getBitWidth();
288       }
289       return size;
290     }
291   }
292 }
293
294 const TypeInfo* TypeInfo::getIndexedType(const ValueInfo&  VI) const {
295   if (isStruct()) {
296     if (VI.isConstant() && VI.type->isInteger()) {
297       size_t pos = VI.val->find(' ') + 1;
298       if (pos < VI.val->size()) {
299         uint64_t idx = atoi(VI.val->substr(pos).c_str());
300         return (*elements)[idx];
301       } else {
302         yyerror("Invalid value for constant integer");
303         return 0;
304       }
305     } else {
306       yyerror("Structure requires constant index");
307       return 0;
308     }
309   }
310   if (isArray() || isPacked() || isPointer())
311     return elemTy;
312   yyerror("Invalid type for getIndexedType");
313   return 0;
314 }
315
316 TypeInfo& TypeInfo::operator=(const TypeInfo& that) {
317   oldTy = that.oldTy;
318   nelems = that.nelems;
319   newTy = that.newTy;
320   elemTy = that.elemTy;
321   resultTy = that.resultTy;
322   if (that.elements) {
323     elements = new TypeList(that.elements->size());
324     *elements = *that.elements;
325   } else {
326     elements = 0;
327   }
328   return *this;
329 }
330
331 const TypeInfo* TypeInfo::add_new_type(TypeInfo* newTy) {
332   TypeRegMap::iterator I = registry.find(newTy);
333   if (I != registry.end()) {
334     delete newTy;
335     return *I;
336   }
337   registry.insert(newTy);
338   return newTy;
339 }
340
341 static const char* getCastOpcode(
342   std::string& Source, const TypeInfo* SrcTy, const TypeInfo* DstTy) 
343 {
344   unsigned SrcBits = SrcTy->getBitWidth();
345   unsigned DstBits = DstTy->getBitWidth();
346   const char* opcode = "bitcast";
347   // Run through the possibilities ...
348   if (DstTy->isIntegral()) {                        // Casting to integral
349     if (SrcTy->isIntegral()) {                      // Casting from integral
350       if (DstBits < SrcBits)
351         opcode = "trunc";
352       else if (DstBits > SrcBits) {                // its an extension
353         if (SrcTy->isSigned())
354           opcode ="sext";                          // signed -> SEXT
355         else
356           opcode = "zext";                         // unsigned -> ZEXT
357       } else {
358         opcode = "bitcast";                        // Same size, No-op cast
359       }
360     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
361       if (DstTy->isSigned()) 
362         opcode = "fptosi";                         // FP -> sint
363       else
364         opcode = "fptoui";                         // FP -> uint 
365     } else if (SrcTy->isPacked()) {
366       assert(DstBits == SrcTy->getBitWidth() &&
367                "Casting packed to integer of different width");
368         opcode = "bitcast";                        // same size, no-op cast
369     } else {
370       assert(SrcTy->isPointer() &&
371              "Casting from a value that is not first-class type");
372       opcode = "ptrtoint";                         // ptr -> int
373     }
374   } else if (DstTy->isFloatingPoint()) {           // Casting to floating pt
375     if (SrcTy->isIntegral()) {                     // Casting from integral
376       if (SrcTy->isSigned())
377         opcode = "sitofp";                         // sint -> FP
378       else
379         opcode = "uitofp";                         // uint -> FP
380     } else if (SrcTy->isFloatingPoint()) {         // Casting from floating pt
381       if (DstBits < SrcBits) {
382         opcode = "fptrunc";                        // FP -> smaller FP
383       } else if (DstBits > SrcBits) {
384         opcode = "fpext";                          // FP -> larger FP
385       } else  {
386         opcode ="bitcast";                         // same size, no-op cast
387       }
388     } else if (SrcTy->isPacked()) {
389       assert(DstBits == SrcTy->getBitWidth() &&
390              "Casting packed to floating point of different width");
391         opcode = "bitcast";                        // same size, no-op cast
392     } else {
393       assert(0 && "Casting pointer or non-first class to float");
394     }
395   } else if (DstTy->isPacked()) {
396     if (SrcTy->isPacked()) {
397       assert(DstTy->getBitWidth() == SrcTy->getBitWidth() &&
398              "Casting packed to packed of different widths");
399       opcode = "bitcast";                          // packed -> packed
400     } else if (DstTy->getBitWidth() == SrcBits) {
401       opcode = "bitcast";                          // float/int -> packed
402     } else {
403       assert(!"Illegal cast to packed (wrong type or size)");
404     }
405   } else if (DstTy->isPointer()) {
406     if (SrcTy->isPointer()) {
407       opcode = "bitcast";                          // ptr -> ptr
408     } else if (SrcTy->isIntegral()) {
409       opcode = "inttoptr";                         // int -> ptr
410     } else {
411       assert(!"Casting invalid type to pointer");
412     }
413   } else {
414     assert(!"Casting to type that is not first-class");
415   }
416   return opcode;
417 }
418
419 static std::string getCastUpgrade(const std::string& Src, const TypeInfo* SrcTy,
420                                   const TypeInfo* DstTy, bool isConst)
421 {
422   std::string Result;
423   std::string Source = Src;
424   if (SrcTy->isFloatingPoint() && DstTy->isPointer()) {
425     // fp -> ptr cast is no longer supported but we must upgrade this
426     // by doing a double cast: fp -> int -> ptr
427     if (isConst)
428       Source = "i64 fptoui(" + Source + " to i64)";
429     else {
430       *O << "    %cast_upgrade" << unique << " = fptoui " << Source 
431          << " to i64\n";
432       Source = "i64 %cast_upgrade" + llvm::utostr(unique);
433     }
434     // Update the SrcTy for the getCastOpcode call below
435     SrcTy = TypeInfo::get("i64", ULongTy);
436   } else if (DstTy->isBool()) {
437     // cast type %x to bool was previously defined as setne type %x, null
438     // The cast semantic is now to truncate, not compare so we must retain
439     // the original intent by replacing the cast with a setne
440     const char* comparator = SrcTy->isPointer() ? ", null" : 
441       (SrcTy->isFloatingPoint() ? ", 0.0" : 
442        (SrcTy->isBool() ? ", false" : ", 0"));
443     const char* compareOp = SrcTy->isFloatingPoint() ? "fcmp one " : "icmp ne ";
444     if (isConst) { 
445       Result = "(" + Source + comparator + ")";
446       Result = compareOp + Result;
447     } else
448       Result = compareOp + Source + comparator;
449     return Result; // skip cast processing below
450   }
451   SrcTy = SrcTy->resolve();
452   DstTy = DstTy->resolve();
453   std::string Opcode(getCastOpcode(Source, SrcTy, DstTy));
454   if (isConst)
455     Result += Opcode + "( " + Source + " to " + DstTy->getNewTy() + ")";
456   else
457     Result += Opcode + " " + Source + " to " + DstTy->getNewTy();
458   return Result;
459 }
460
461 const char* getDivRemOpcode(const std::string& opcode, const TypeInfo* TI) {
462   const char* op = opcode.c_str();
463   const TypeInfo* Ty = TI->resolve();
464   if (Ty->isPacked())
465     Ty = Ty->getElementType();
466   if (opcode == "div")
467     if (Ty->isFloatingPoint())
468       op = "fdiv";
469     else if (Ty->isUnsigned())
470       op = "udiv";
471     else if (Ty->isSigned())
472       op = "sdiv";
473     else
474       yyerror("Invalid type for div instruction");
475   else if (opcode == "rem")
476     if (Ty->isFloatingPoint())
477       op = "frem";
478     else if (Ty->isUnsigned())
479       op = "urem";
480     else if (Ty->isSigned())
481       op = "srem";
482     else
483       yyerror("Invalid type for rem instruction");
484   return op;
485 }
486
487 std::string 
488 getCompareOp(const std::string& setcc, const TypeInfo* TI) {
489   assert(setcc.length() == 5);
490   char cc1 = setcc[3];
491   char cc2 = setcc[4];
492   assert(cc1 == 'e' || cc1 == 'n' || cc1 == 'l' || cc1 == 'g');
493   assert(cc2 == 'q' || cc2 == 'e' || cc2 == 'e' || cc2 == 't');
494   std::string result("xcmp xxx");
495   result[6] = cc1;
496   result[7] = cc2;
497   if (TI->isFloatingPoint()) {
498     result[0] = 'f';
499     result[5] = 'o';
500     if (cc1 == 'n')
501       result[5] = 'u'; // NE maps to unordered
502     else
503       result[5] = 'o'; // everything else maps to ordered
504   } else if (TI->isIntegral() || TI->isPointer()) {
505     result[0] = 'i';
506     if ((cc1 == 'e' && cc2 == 'q') || (cc1 == 'n' && cc2 == 'e'))
507       result.erase(5,1);
508     else if (TI->isSigned())
509       result[5] = 's';
510     else if (TI->isUnsigned() || TI->isPointer() || TI->isBool())
511       result[5] = 'u';
512     else
513       yyerror("Invalid integral type for setcc");
514   }
515   return result;
516 }
517
518 static const TypeInfo* getFunctionReturnType(const TypeInfo* PFTy) {
519   PFTy = PFTy->resolve();
520   if (PFTy->isPointer()) {
521     const TypeInfo* ElemTy = PFTy->getElementType();
522     ElemTy = ElemTy->resolve();
523     if (ElemTy->isFunction())
524       return ElemTy->getResultType();
525   } else if (PFTy->isFunction()) {
526     return PFTy->getResultType();
527   }
528   return PFTy;
529 }
530
531 typedef std::vector<const TypeInfo*> UpRefStack;
532 static const TypeInfo* ResolveUpReference(const TypeInfo* Ty, 
533                                           UpRefStack* stack) {
534   assert(Ty->isUpReference() && "Can't resolve a non-upreference");
535   unsigned upref = Ty->getUpRefNum();
536   assert(upref < stack->size() && "Invalid up reference");
537   return (*stack)[upref - stack->size() - 1];
538 }
539
540 static const TypeInfo* getGEPIndexedType(const TypeInfo* PTy, ValueList* idxs) {
541   const TypeInfo* Result = PTy = PTy->resolve();
542   assert(PTy->isPointer() && "GEP Operand is not a pointer?");
543   UpRefStack stack;
544   for (unsigned i = 0; i < idxs->size(); ++i) {
545     if (Result->isComposite()) {
546       Result = Result->getIndexedType((*idxs)[i]);
547       Result = Result->resolve();
548       stack.push_back(Result);
549     } else
550       yyerror("Invalid type for index");
551   }
552   // Resolve upreferences so we can return a more natural type
553   if (Result->isPointer()) {
554     if (Result->getElementType()->isUpReference()) {
555       stack.push_back(Result);
556       Result = ResolveUpReference(Result->getElementType(), &stack);
557     }
558   } else if (Result->isUpReference()) {
559     Result = ResolveUpReference(Result->getElementType(), &stack);
560   }
561   return Result->getPointerType();
562 }
563
564 static std::string makeUniqueName(const std::string *Name, bool isSigned) {
565   const char *suffix = ".u";
566   if (isSigned)
567     suffix = ".s";
568   if ((*Name)[Name->size()-1] == '"') {
569     std::string Result(*Name);
570     Result.insert(Name->size()-1, suffix);
571     return Result;
572   }
573   return *Name + suffix;
574 }
575
576 // This function handles appending .u or .s to integer value names that
577 // were previously unsigned or signed, respectively. This avoids name
578 // collisions since the unsigned and signed type planes have collapsed
579 // into a single signless type plane.
580 static std::string getUniqueName(const std::string *Name, const TypeInfo* Ty,
581                                  bool isGlobal = false) {
582
583   // If its not a symbolic name, don't modify it, probably a constant val.
584   if ((*Name)[0] != '%' && (*Name)[0] != '"')
585     return *Name;
586
587   // If its a numeric reference, just leave it alone.
588   if (isdigit((*Name)[1]))
589     return *Name;
590
591   // Resolve the type
592   Ty = Ty->resolve(); 
593
594   // If its a global name, get its uniquified name, if any
595   GlobalsTypeMap::iterator GI = Globals.find(*Name);
596   if (GI != Globals.end()) {
597     TypePlaneMap::iterator TPI = GI->second.begin();
598     TypePlaneMap::iterator TPE = GI->second.end();
599     for ( ; TPI != TPE ; ++TPI) {
600       if (TPI->first->sameNewTyAs(Ty)) 
601         return TPI->second;
602     }
603   }
604
605   if (isGlobal) {
606     // We didn't find a global name, but if its supposed to be global then all 
607     // we can do is return the name. This is probably a forward reference of a 
608     // global value that hasn't been defined yet. Since we have no definition
609     // we don't know its linkage class. Just assume its an external and the name
610     // shouldn't change.
611     return *Name;
612   }
613
614   // Remove as many levels of pointer nesting that we have.
615   if (Ty->isPointer()) {
616     // Avoid infinite loops in recursive types
617     const TypeInfo* Last = 0;
618     while (Ty->isPointer() && !Ty->sameOldTyAs(Last)) {
619       Last = Ty;
620       Ty = Ty->getElementType()->resolve();
621     }
622   }
623
624   // Default the result to the current name
625   std::string Result = *Name; 
626
627   // Now deal with the underlying type
628   if (Ty->isInteger()) {
629     // If its an integer type, make the name unique
630     Result = makeUniqueName(Name, Ty->isSigned());
631   } else if (Ty->isArray() || Ty->isPacked()) {
632     Ty = Ty->getElementType();
633     if (Ty->isInteger())
634       Result = makeUniqueName(Name, Ty->isSigned());
635   } else if (Ty->isStruct()) {
636     // Scan the fields and count the signed and unsigned fields
637     int isSigned = 0;
638     for (unsigned i = 0; i < Ty->getNumStructElements(); ++i) {
639       const TypeInfo* Tmp = Ty->getElement(i);
640       if (Tmp->isInteger())
641         if (Tmp->isSigned())
642           isSigned++;
643         else
644           isSigned--;
645     }
646     if (isSigned != 0)
647       Result = makeUniqueName(Name, isSigned > 0);
648   }
649   return Result;
650 }
651
652 static unsigned UniqueNameCounter = 0;
653
654 std::string getGlobalName(const std::string* Name, const std::string Linkage,
655                           const TypeInfo* Ty, bool isConstant) {
656   // Default to given name
657   std::string Result = *Name; 
658   // Look up the name in the Globals Map
659   GlobalsTypeMap::iterator GI = Globals.find(*Name);
660   // Did we see this global name before?
661   if (GI != Globals.end()) {
662     if (Ty->isUnresolvedDeep()) {
663       // The Gval's type is unresolved. Consequently, we can't disambiguate it
664       // by type. We'll just change its name and emit a warning.
665       warning("Cannot disambiguate global value '" + *Name + 
666               "' because type '" + Ty->getNewTy() + "'is unresolved.\n");
667       Result = *Name + ".unique";
668       UniqueNameCounter++;
669       Result += llvm::utostr(UniqueNameCounter);
670       return Result;
671     } else {
672       TypePlaneMap::iterator TPI = GI->second.find(Ty);
673       if (TPI != GI->second.end()) {
674         // We found an existing name of the same old type. This isn't allowed 
675         // in LLVM 2.0. Consequently, we must alter the name of the global so it
676         // can at least compile. References to the global will yield the first
677         // definition, which is okay. We also must warn about this.
678         Result = *Name + ".unique";
679         UniqueNameCounter++;
680         Result += llvm::utostr(UniqueNameCounter);
681         warning(std::string("Global variable '") + *Name + "' was renamed to '"+
682                 Result + "'");
683       } else { 
684         // There isn't an existing definition for this name according to the
685         // old types. Now search the TypePlanMap for types with the same new
686         // name. 
687         TypePlaneMap::iterator TPI = GI->second.begin();
688         TypePlaneMap::iterator TPE = GI->second.end();
689         for ( ; TPI != TPE; ++TPI) {
690           if (TPI->first->sameNewTyAs(Ty)) {
691             // The new types are the same but the old types are different so 
692             // this is a global name collision resulting from type planes 
693             // collapsing. 
694             if (Linkage == "external" || Linkage == "dllimport" || 
695                 Linkage == "extern_weak" || Linkage == "") {
696               // The linkage of this gval is external so we can't reliably 
697               // rename it because it could potentially create a linking 
698               // problem.  However, we can't leave the name conflict in the 
699               // output either or it won't assemble with LLVM 2.0.  So, all we 
700               // can do is rename this one to something unique and emit a 
701               // warning about the problem.
702               Result = *Name + ".unique";
703               UniqueNameCounter++;
704               Result += llvm::utostr(UniqueNameCounter);
705               warning("Renaming global value '" + *Name + "' to '" + Result + 
706                       "' may cause linkage errors.");
707               return Result;
708             } else {
709               // Its linkage is internal and its type is known so we can 
710               // disambiguate the name collision successfully based on the type.
711               Result = getUniqueName(Name, Ty);
712               TPI->second = Result;
713               return Result;
714             }
715           }
716         }
717         // We didn't find an entry in the type plane with the same new type and
718         // the old types differ so this is a new type plane for this global 
719         // variable. We just fall through to the logic below which inserts
720         // the global.
721       }
722     }
723   }
724
725   // Its a new global name, if it is external we can't change it
726   if (isConstant || Linkage == "external" || Linkage == "dllimport" || 
727       Linkage == "extern_weak" || Linkage == "") {
728     Globals[Result][Ty] = Result;
729     return Result;
730   }
731
732   // Its a new global name, and it is internal, change the name to make it
733   // unique for its type.
734   // Result = getUniqueName(Name, Ty);
735   Globals[*Name][Ty] = Result;
736   return Result;
737 }
738 %}
739
740 // %file-prefix="UpgradeParser"
741
742 %union {
743   std::string*    String;
744   const TypeInfo* Type;
745   ValueInfo       Value;
746   ConstInfo       Const;
747   ValueList*      ValList;
748   TypeList*       TypeVec;
749 }
750
751 %token <Type>   VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
752 %token <Type>   FLOAT DOUBLE LABEL 
753 %token <String> OPAQUE ESINT64VAL EUINT64VAL SINTVAL UINTVAL FPVAL
754 %token <String> NULL_TOK UNDEF ZEROINITIALIZER TRUETOK FALSETOK
755 %token <String> TYPE VAR_ID LABELSTR STRINGCONSTANT
756 %token <String> IMPLEMENTATION BEGINTOK ENDTOK
757 %token <String> DECLARE GLOBAL CONSTANT SECTION VOLATILE
758 %token <String> TO DOTDOTDOT CONST INTERNAL LINKONCE WEAK 
759 %token <String> DLLIMPORT DLLEXPORT EXTERN_WEAK APPENDING
760 %token <String> NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
761 %token <String> ALIGN UNINITIALIZED
762 %token <String> DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
763 %token <String> CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
764 %token <String> X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
765 %token <String> DATALAYOUT
766 %token <String> RET BR SWITCH INVOKE EXCEPT UNWIND UNREACHABLE
767 %token <String> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM AND OR XOR
768 %token <String> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
769 %token <String> ICMP FCMP EQ NE SLT SGT SLE SGE OEQ ONE OLT OGT OLE OGE 
770 %token <String> ORD UNO UEQ UNE ULT UGT ULE UGE
771 %token <String> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
772 %token <String> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
773 %token <String> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
774 %token <String> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI UITOFP SITOFP 
775 %token <String> PTRTOINT INTTOPTR BITCAST
776
777 %type <String> OptAssign OptLinkage OptCallingConv OptAlign OptCAlign 
778 %type <String> SectionString OptSection GlobalVarAttributes GlobalVarAttribute
779 %type <String> ConstExpr DefinitionList
780 %type <String> ConstPool TargetDefinition LibrariesDefinition LibList OptName
781 %type <String> ArgVal ArgListH ArgList FunctionHeaderH BEGIN FunctionHeader END
782 %type <String> Function FunctionProto BasicBlock 
783 %type <String> InstructionList BBTerminatorInst JumpTable Inst
784 %type <String> OptTailCall OptVolatile Unwind
785 %type <String> SymbolicValueRef OptSideEffect GlobalType
786 %type <String> FnDeclareLinkage BasicBlockList BigOrLittle AsmBlock
787 %type <String> Name ConstValueRef ConstVector External
788 %type <String> ShiftOps SetCondOps LogicalOps ArithmeticOps CastOps
789 %type <String> IPredicates FPredicates
790
791 %type <ValList> ValueRefList ValueRefListE IndexList
792 %type <TypeVec> TypeListI ArgTypeListI
793
794 %type <Type> IntType SIntType UIntType FPType TypesV Types 
795 %type <Type> PrimType UpRTypesV UpRTypes
796
797 %type <String> IntVal EInt64Val 
798 %type <Const>  ConstVal
799
800 %type <Value> ValueRef ResolvedVal InstVal PHIList MemoryInst
801
802 %start Module
803
804 %%
805
806 // Handle constant integer size restriction and conversion...
807 IntVal : SINTVAL | UINTVAL ;
808 EInt64Val : ESINT64VAL | EUINT64VAL;
809
810 // Operations that are notably excluded from this list include:
811 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
812 ArithmeticOps: ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV 
813              | REM | UREM | SREM | FREM;
814 LogicalOps   : AND | OR | XOR;
815 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
816 IPredicates  : EQ | NE | SLT | SGT | SLE | SGE | ULT | UGT | ULE | UGE;
817 FPredicates  : OEQ | ONE | OLT | OGT | OLE | OGE | ORD | UNO | UEQ | UNE
818              | ULT | UGT | ULE | UGE | TRUETOK | FALSETOK;
819 ShiftOps     : SHL | SHR | ASHR | LSHR;
820 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI | 
821                UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
822              ;
823
824 // These are some types that allow classification if we only want a particular 
825 // thing... for example, only a signed, unsigned, or integral type.
826 SIntType :  LONG |  INT |  SHORT | SBYTE;
827 UIntType : ULONG | UINT | USHORT | UBYTE;
828 IntType  : SIntType | UIntType;
829 FPType   : FLOAT | DOUBLE;
830
831 // OptAssign - Value producing statements have an optional assignment component
832 OptAssign : Name '=' {
833     $$ = $1;
834   }
835   | /*empty*/ {
836     $$ = new std::string(""); 
837   };
838
839 OptLinkage 
840   : INTERNAL | LINKONCE | WEAK | APPENDING | DLLIMPORT | DLLEXPORT 
841   | EXTERN_WEAK 
842   | /*empty*/   { $$ = new std::string(""); } ;
843
844 OptCallingConv 
845   : CCC_TOK | CSRETCC_TOK | FASTCC_TOK | COLDCC_TOK | X86_STDCALLCC_TOK 
846   | X86_FASTCALLCC_TOK 
847   | CC_TOK EUINT64VAL { 
848     *$1 += *$2; 
849     delete $2;
850     $$ = $1; 
851     }
852   | /*empty*/ { $$ = new std::string(""); } ;
853
854 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
855 // a comma before it.
856 OptAlign 
857   : /*empty*/        { $$ = new std::string(); }
858   | ALIGN EUINT64VAL { *$1 += " " + *$2; delete $2; $$ = $1; };
859
860 OptCAlign 
861   : /*empty*/            { $$ = new std::string(); } 
862   | ',' ALIGN EUINT64VAL { 
863     $2->insert(0, ", "); 
864     *$2 += " " + *$3;
865     delete $3;
866     $$ = $2;
867   };
868
869 SectionString 
870   : SECTION STRINGCONSTANT { 
871     *$1 += " " + *$2;
872     delete $2;
873     $$ = $1;
874   };
875
876 OptSection : /*empty*/     { $$ = new std::string(); } 
877            | SectionString;
878
879 GlobalVarAttributes 
880     : /* empty */ { $$ = new std::string(); } 
881     | ',' GlobalVarAttribute GlobalVarAttributes  {
882       $2->insert(0, ", ");
883       if (!$3->empty())
884         *$2 += " " + *$3;
885       delete $3;
886       $$ = $2;
887     };
888
889 GlobalVarAttribute 
890     : SectionString 
891     | ALIGN EUINT64VAL {
892       *$1 += " " + *$2;
893       delete $2;
894       $$ = $1;
895     };
896
897 //===----------------------------------------------------------------------===//
898 // Types includes all predefined types... except void, because it can only be
899 // used in specific contexts (function returning void for example).  To have
900 // access to it, a user must explicitly use TypesV.
901 //
902
903 // TypesV includes all of 'Types', but it also includes the void type.
904 TypesV    : Types    | VOID ;
905 UpRTypesV : UpRTypes | VOID ; 
906 Types     : UpRTypes ;
907
908 // Derived types are added later...
909 //
910 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
911 PrimType : LONG | ULONG | FLOAT | DOUBLE | LABEL;
912 UpRTypes 
913   : OPAQUE { 
914     $$ = TypeInfo::get(*$1, OpaqueTy);
915   } 
916   | SymbolicValueRef { 
917     $$ = TypeInfo::get(*$1, UnresolvedTy);
918   }
919   | PrimType { 
920     $$ = $1; 
921   }
922   | '\\' EUINT64VAL {                   // Type UpReference
923     $2->insert(0, "\\");
924     $$ = TypeInfo::get(*$2, UpRefTy);
925   }
926   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
927     std::string newTy( $1->getNewTy() + "(");
928     for (unsigned i = 0; i < $3->size(); ++i) {
929       if (i != 0)
930         newTy +=  ", ";
931       if ((*$3)[i]->isVoid())
932         newTy += "...";
933       else
934         newTy += (*$3)[i]->getNewTy();
935     }
936     newTy += ")";
937     $$ = TypeInfo::get(newTy, $1, $3);
938   }
939   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
940     uint64_t elems = atoi($2->c_str());
941     $2->insert(0,"[ ");
942     *$2 += " x " + $4->getNewTy() + " ]";
943     $$ = TypeInfo::get(*$2, ArrayTy, $4, elems);
944   }
945   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
946     uint64_t elems = atoi($2->c_str());
947     $2->insert(0,"< ");
948     *$2 += " x " + $4->getNewTy() + " >";
949     $$ = TypeInfo::get(*$2, PackedTy, $4, elems);
950   }
951   | '{' TypeListI '}' {                        // Structure type?
952     std::string newTy("{");
953     for (unsigned i = 0; i < $2->size(); ++i) {
954       if (i != 0)
955         newTy +=  ", ";
956       newTy += (*$2)[i]->getNewTy();
957     }
958     newTy += "}";
959     $$ = TypeInfo::get(newTy, StructTy, $2);
960   }
961   | '{' '}' {                                  // Empty structure type?
962     $$ = TypeInfo::get("{}", StructTy, new TypeList());
963   }
964   | '<' '{' TypeListI '}' '>' {                // Packed Structure type?
965     std::string newTy("<{");
966     for (unsigned i = 0; i < $3->size(); ++i) {
967       if (i != 0)
968         newTy +=  ", ";
969       newTy += (*$3)[i]->getNewTy();
970     }
971     newTy += "}>";
972     $$ = TypeInfo::get(newTy, PackedStructTy, $3);
973   }
974   | '<' '{' '}' '>' {                          // Empty packed structure type?
975     $$ = TypeInfo::get("<{}>", PackedStructTy, new TypeList());
976   }
977   | UpRTypes '*' {                             // Pointer type?
978     $$ = $1->getPointerType();
979   };
980
981 // TypeList - Used for struct declarations and as a basis for function type 
982 // declaration type lists
983 //
984 TypeListI 
985   : UpRTypes {
986     $$ = new TypeList();
987     $$->push_back($1);
988   }
989   | TypeListI ',' UpRTypes {
990     $$ = $1;
991     $$->push_back($3);
992   };
993
994 // ArgTypeList - List of types for a function type declaration...
995 ArgTypeListI 
996   : TypeListI 
997   | TypeListI ',' DOTDOTDOT {
998     $$ = $1;
999     $$->push_back(TypeInfo::get("void",VoidTy));
1000     delete $3;
1001   }
1002   | DOTDOTDOT {
1003     $$ = new TypeList();
1004     $$->push_back(TypeInfo::get("void",VoidTy));
1005     delete $1;
1006   }
1007   | /*empty*/ {
1008     $$ = new TypeList();
1009   };
1010
1011 // ConstVal - The various declarations that go into the constant pool.  This
1012 // production is used ONLY to represent constants that show up AFTER a 'const',
1013 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1014 // into other expressions (such as integers and constexprs) are handled by the
1015 // ResolvedVal, ValueRef and ConstValueRef productions.
1016 //
1017 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1018     $$.type = $1;
1019     $$.cnst = new std::string($1->getNewTy());
1020     *$$.cnst += " [ " + *$3 + " ]";
1021     delete $3;
1022   }
1023   | Types '[' ']' {
1024     $$.type = $1;
1025     $$.cnst = new std::string($1->getNewTy());
1026     *$$.cnst += "[ ]";
1027   }
1028   | Types 'c' STRINGCONSTANT {
1029     $$.type = $1;
1030     $$.cnst = new std::string($1->getNewTy());
1031     *$$.cnst += " c" + *$3;
1032     delete $3;
1033   }
1034   | Types '<' ConstVector '>' { // Nonempty unsized arr
1035     $$.type = $1;
1036     $$.cnst = new std::string($1->getNewTy());
1037     *$$.cnst += " < " + *$3 + " >";
1038     delete $3;
1039   }
1040   | Types '{' ConstVector '}' {
1041     $$.type = $1;
1042     $$.cnst = new std::string($1->getNewTy());
1043     *$$.cnst += " { " + *$3 + " }";
1044     delete $3;
1045   }
1046   | Types '{' '}' {
1047     $$.type = $1;
1048     $$.cnst = new std::string($1->getNewTy());
1049     *$$.cnst += " {}";
1050   }
1051   | Types NULL_TOK {
1052     $$.type = $1;
1053     $$.cnst = new std::string($1->getNewTy());
1054     *$$.cnst +=  " " + *$2;
1055     delete $2;
1056   }
1057   | Types UNDEF {
1058     $$.type = $1;
1059     $$.cnst = new std::string($1->getNewTy());
1060     *$$.cnst += " " + *$2;
1061     delete $2;
1062   }
1063   | Types SymbolicValueRef {
1064     std::string Name = getUniqueName($2, $1->resolve(), true);
1065     $$.type = $1;
1066     $$.cnst = new std::string($1->getNewTy());
1067     *$$.cnst += " " + Name;
1068     delete $2;
1069   }
1070   | Types ConstExpr {
1071     $$.type = $1;
1072     $$.cnst = new std::string($1->getNewTy());
1073     *$$.cnst += " " + *$2;
1074     delete $2;
1075   }
1076   | Types ZEROINITIALIZER {
1077     $$.type = $1;
1078     $$.cnst = new std::string($1->getNewTy());
1079     *$$.cnst += " " + *$2;
1080     delete $2;
1081   }
1082   | SIntType EInt64Val {      // integral constants
1083     $$.type = $1;
1084     $$.cnst = new std::string($1->getNewTy());
1085     *$$.cnst += " " + *$2;
1086     delete $2;
1087   }
1088   | UIntType EInt64Val {            // integral constants
1089     $$.type = $1;
1090     $$.cnst = new std::string($1->getNewTy());
1091     *$$.cnst += " " + *$2;
1092     delete $2;
1093   }
1094   | BOOL TRUETOK {                      // Boolean constants
1095     $$.type = $1;
1096     $$.cnst = new std::string($1->getNewTy());
1097     *$$.cnst += " " + *$2;
1098     delete $2;
1099   }
1100   | BOOL FALSETOK {                     // Boolean constants
1101     $$.type = $1;
1102     $$.cnst = new std::string($1->getNewTy());
1103     *$$.cnst += " " + *$2;
1104     delete $2;
1105   }
1106   | FPType FPVAL {                   // Float & Double constants
1107     $$.type = $1;
1108     $$.cnst = new std::string($1->getNewTy());
1109     *$$.cnst += " " + *$2;
1110     delete $2;
1111   };
1112
1113
1114 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1115     std::string source = *$3.cnst;
1116     const TypeInfo* SrcTy = $3.type->resolve();
1117     const TypeInfo* DstTy = $5->resolve(); 
1118     if (*$1 == "cast") {
1119       // Call getCastUpgrade to upgrade the old cast
1120       $$ = new std::string(getCastUpgrade(source, SrcTy, DstTy, true));
1121     } else {
1122       // Nothing to upgrade, just create the cast constant expr
1123       $$ = new std::string(*$1);
1124       *$$ += "( " + source + " to " + $5->getNewTy() + ")";
1125     }
1126     delete $1; $3.destroy(); delete $4;
1127   }
1128   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1129     *$1 += "(" + *$3.cnst;
1130     for (unsigned i = 0; i < $4->size(); ++i) {
1131       ValueInfo& VI = (*$4)[i];
1132       *$1 += ", " + *VI.val;
1133       VI.destroy();
1134     }
1135     *$1 += ")";
1136     $$ = $1;
1137     $3.destroy();
1138     delete $4;
1139   }
1140   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1141     *$1 += "(" + *$3.cnst + "," + *$5.cnst + "," + *$7.cnst + ")";
1142     $3.destroy(); $5.destroy(); $7.destroy();
1143     $$ = $1;
1144   }
1145   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1146     const char* op = getDivRemOpcode(*$1, $3.type); 
1147     $$ = new std::string(op);
1148     *$$ += "(" + *$3.cnst + "," + *$5.cnst + ")";
1149     delete $1; $3.destroy(); $5.destroy();
1150   }
1151   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1152     *$1 += "(" + *$3.cnst + "," + *$5.cnst + ")";
1153     $3.destroy(); $5.destroy();
1154     $$ = $1;
1155   }
1156   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1157     *$1 = getCompareOp(*$1, $3.type);
1158     *$1 += "(" + *$3.cnst + "," + *$5.cnst + ")";
1159     $3.destroy(); $5.destroy();
1160     $$ = $1;
1161   }
1162   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1163     *$1 += " " + *$2 + " (" +  *$4.cnst + "," + *$6.cnst + ")";
1164     delete $2; $4.destroy(); $6.destroy();
1165     $$ = $1;
1166   }
1167   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1168     *$1 += " " + *$2 + " (" + *$4.cnst + "," + *$6.cnst + ")";
1169     delete $2; $4.destroy(); $6.destroy();
1170     $$ = $1;
1171   }
1172   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1173     const char* shiftop = $1->c_str();
1174     if (*$1 == "shr")
1175       shiftop = ($3.type->isUnsigned()) ? "lshr" : "ashr";
1176     $$ = new std::string(shiftop);
1177     *$$ += "(" + *$3.cnst + "," + *$5.cnst + ")";
1178     delete $1; $3.destroy(); $5.destroy();
1179   }
1180   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1181     *$1 += "(" + *$3.cnst + "," + *$5.cnst + ")";
1182     $3.destroy(); $5.destroy();
1183     $$ = $1;
1184   }
1185   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1186     *$1 += "(" + *$3.cnst + "," + *$5.cnst + "," + *$7.cnst + ")";
1187     $3.destroy(); $5.destroy(); $7.destroy();
1188     $$ = $1;
1189   }
1190   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1191     *$1 += "(" + *$3.cnst + "," + *$5.cnst + "," + *$7.cnst + ")";
1192     $3.destroy(); $5.destroy(); $7.destroy();
1193     $$ = $1;
1194   };
1195
1196
1197 // ConstVector - A list of comma separated constants.
1198
1199 ConstVector 
1200   : ConstVector ',' ConstVal {
1201     *$1 += ", " + *$3.cnst;
1202     $3.destroy();
1203     $$ = $1;
1204   }
1205   | ConstVal { $$ = new std::string(*$1.cnst); $1.destroy(); }
1206   ;
1207
1208
1209 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1210 GlobalType : GLOBAL | CONSTANT ;
1211
1212
1213 //===----------------------------------------------------------------------===//
1214 //                             Rules to match Modules
1215 //===----------------------------------------------------------------------===//
1216
1217 // Module rule: Capture the result of parsing the whole file into a result
1218 // variable...
1219 //
1220 Module : DefinitionList {
1221 };
1222
1223 // DefinitionList - Top level definitions
1224 //
1225 DefinitionList : DefinitionList Function {
1226     $$ = 0;
1227   } 
1228   | DefinitionList FunctionProto {
1229     *O << *$2 << '\n';
1230     delete $2;
1231     $$ = 0;
1232   }
1233   | DefinitionList MODULE ASM_TOK AsmBlock {
1234     *O << "module asm " << ' ' << *$4 << '\n';
1235     $$ = 0;
1236   }  
1237   | DefinitionList IMPLEMENTATION {
1238     *O << "implementation\n";
1239     $$ = 0;
1240   }
1241   | ConstPool { $$ = 0; }
1242
1243 External : EXTERNAL | UNINITIALIZED { $$ = $1; *$$ = "external"; }
1244
1245 // ConstPool - Constants with optional names assigned to them.
1246 ConstPool : ConstPool OptAssign TYPE TypesV {
1247     EnumeratedTypes.push_back($4);
1248     if (!$2->empty()) {
1249       NamedTypes[*$2] = $4;
1250       *O << *$2 << " = ";
1251     }
1252     *O << "type " << $4->getNewTy() << '\n';
1253     delete $2; delete $3;
1254     $$ = 0;
1255   }
1256   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1257     *O << *$2 << '\n';
1258     delete $2;
1259     $$ = 0;
1260   }
1261   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
1262     *O << *$2 << ' ' << *$3 << ' ' << *$4 << '\n';
1263     delete $2; delete $3; delete $4; 
1264     $$ = 0;
1265   }
1266   | ConstPool OptAssign OptLinkage GlobalType ConstVal  GlobalVarAttributes {
1267     if (!$2->empty()) {
1268       std::string Name = getGlobalName($2,*$3, $5.type->getPointerType(),
1269                                        *$4 == "constant");
1270       *O << Name << " = ";
1271     }
1272     *O << *$3 << ' ' << *$4 << ' ' << *$5.cnst << ' ' << *$6 << '\n';
1273     delete $2; delete $3; delete $4; delete $6; 
1274     $$ = 0;
1275   }
1276   | ConstPool OptAssign External GlobalType Types  GlobalVarAttributes {
1277     if (!$2->empty()) {
1278       std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1279                                        *$4 == "constant");
1280       *O << Name << " = ";
1281     }
1282     *O <<  *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1283     delete $2; delete $3; delete $4; delete $6;
1284     $$ = 0;
1285   }
1286   | ConstPool OptAssign DLLIMPORT GlobalType Types GlobalVarAttributes {
1287     if (!$2->empty()) {
1288       std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1289                                        *$4 == "constant");
1290       *O << Name << " = ";
1291     }
1292     *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1293     delete $2; delete $3; delete $4; delete $6;
1294     $$ = 0;
1295   }
1296   | ConstPool OptAssign EXTERN_WEAK GlobalType Types  GlobalVarAttributes {
1297     if (!$2->empty()) {
1298       std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1299                                        *$4 == "constant");
1300       *O << Name << " = ";
1301     }
1302     *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1303     delete $2; delete $3; delete $4; delete $6;
1304     $$ = 0;
1305   }
1306   | ConstPool TARGET TargetDefinition { 
1307     *O << *$2 << ' ' << *$3 << '\n';
1308     delete $2; delete $3;
1309     $$ = 0;
1310   }
1311   | ConstPool DEPLIBS '=' LibrariesDefinition {
1312     *O << *$2 << " = " << *$4 << '\n';
1313     delete $2; delete $4;
1314     $$ = 0;
1315   }
1316   | /* empty: end of list */ { 
1317     $$ = 0;
1318   };
1319
1320
1321 AsmBlock : STRINGCONSTANT ;
1322
1323 BigOrLittle : BIG | LITTLE 
1324
1325 TargetDefinition 
1326   : ENDIAN '=' BigOrLittle {
1327     *$1 += " = " + *$3;
1328     delete $3;
1329     $$ = $1;
1330   }
1331   | POINTERSIZE '=' EUINT64VAL {
1332     *$1 += " = " + *$3;
1333     if (*$3 == "64")
1334       SizeOfPointer = 64;
1335     delete $3;
1336     $$ = $1;
1337   }
1338   | TRIPLE '=' STRINGCONSTANT {
1339     *$1 += " = " + *$3;
1340     delete $3;
1341     $$ = $1;
1342   }
1343   | DATALAYOUT '=' STRINGCONSTANT {
1344     *$1 += " = " + *$3;
1345     delete $3;
1346     $$ = $1;
1347   };
1348
1349 LibrariesDefinition 
1350   : '[' LibList ']' {
1351     $2->insert(0, "[ ");
1352     *$2 += " ]";
1353     $$ = $2;
1354   };
1355
1356 LibList 
1357   : LibList ',' STRINGCONSTANT {
1358     *$1 += ", " + *$3;
1359     delete $3;
1360     $$ = $1;
1361   }
1362   | STRINGCONSTANT 
1363   | /* empty: end of list */ {
1364     $$ = new std::string();
1365   };
1366
1367 //===----------------------------------------------------------------------===//
1368 //                       Rules to match Function Headers
1369 //===----------------------------------------------------------------------===//
1370
1371 Name : VAR_ID | STRINGCONSTANT;
1372 OptName : Name | /*empty*/ { $$ = new std::string(); };
1373
1374 ArgVal : Types OptName {
1375   $$ = new std::string($1->getNewTy());
1376   if (!$2->empty()) {
1377     std::string Name = getUniqueName($2, $1->resolve());
1378     *$$ += " " + Name;
1379   }
1380   delete $2;
1381 };
1382
1383 ArgListH : ArgListH ',' ArgVal {
1384     *$1 += ", " + *$3;
1385     delete $3;
1386   }
1387   | ArgVal {
1388     $$ = $1;
1389   };
1390
1391 ArgList : ArgListH {
1392     $$ = $1;
1393   }
1394   | ArgListH ',' DOTDOTDOT {
1395     *$1 += ", ...";
1396     $$ = $1;
1397     delete $3;
1398   }
1399   | DOTDOTDOT {
1400     $$ = $1;
1401   }
1402   | /* empty */ { $$ = new std::string(); };
1403
1404 FunctionHeaderH 
1405   : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
1406     if (!$1->empty()) {
1407       *$1 += " ";
1408     }
1409     *$1 += $2->getNewTy() + " " + *$3 + "(" + *$5 + ")";
1410     if (!$7->empty()) {
1411       *$1 += " " + *$7;
1412     }
1413     if (!$8->empty()) {
1414       *$1 += " " + *$8;
1415     }
1416     delete $3;
1417     delete $5;
1418     delete $7;
1419     delete $8;
1420     $$ = $1;
1421   };
1422
1423 BEGIN : BEGINTOK { $$ = new std::string("{"); delete $1; }
1424   | '{' { $$ = new std::string ("{"); }
1425
1426 FunctionHeader 
1427   : OptLinkage FunctionHeaderH BEGIN {
1428     *O << "define ";
1429     if (!$1->empty()) {
1430       *O << *$1 << ' ';
1431     }
1432     *O << *$2 << ' ' << *$3 << '\n';
1433     delete $1; delete $2; delete $3;
1434     $$ = 0;
1435   }
1436   ;
1437
1438 END : ENDTOK { $$ = new std::string("}"); delete $1; }
1439     | '}' { $$ = new std::string("}"); };
1440
1441 Function : FunctionHeader BasicBlockList END {
1442   if ($2)
1443     *O << *$2;
1444   *O << *$3 << "\n\n";
1445   delete $1; delete $2; delete $3;
1446   $$ = 0;
1447 };
1448
1449 FnDeclareLinkage
1450   : /*default*/ { $$ = new std::string(); }
1451   | DLLIMPORT    
1452   | EXTERN_WEAK 
1453   ;
1454   
1455 FunctionProto 
1456   : DECLARE FnDeclareLinkage FunctionHeaderH { 
1457     if (!$2->empty())
1458       *$1 += " " + *$2;
1459     *$1 += " " + *$3;
1460     delete $2;
1461     delete $3;
1462     $$ = $1;
1463   };
1464
1465 //===----------------------------------------------------------------------===//
1466 //                        Rules to match Basic Blocks
1467 //===----------------------------------------------------------------------===//
1468
1469 OptSideEffect : /* empty */ { $$ = new std::string(); }
1470   | SIDEEFFECT;
1471
1472 ConstValueRef 
1473   : ESINT64VAL | EUINT64VAL | FPVAL | TRUETOK | FALSETOK | NULL_TOK | UNDEF
1474   | ZEROINITIALIZER 
1475   | '<' ConstVector '>' { 
1476     $2->insert(0, "<");
1477     *$2 += ">";
1478     $$ = $2;
1479   }
1480   | ConstExpr 
1481   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
1482     if (!$2->empty()) {
1483       *$1 += " " + *$2;
1484     }
1485     *$1 += " " + *$3 + ", " + *$5;
1486     delete $2; delete $3; delete $5;
1487     $$ = $1;
1488   };
1489
1490 SymbolicValueRef : IntVal | Name ;
1491
1492 // ValueRef - A reference to a definition... either constant or symbolic
1493 ValueRef 
1494   : SymbolicValueRef {
1495     $$.val = $1;
1496     $$.constant = false;
1497     $$.type = 0;
1498   }
1499   | ConstValueRef {
1500     $$.val = $1;
1501     $$.constant = true;
1502     $$.type = 0;
1503   }
1504   ;
1505
1506 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1507 // type immediately preceeds the value reference, and allows complex constant
1508 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1509 ResolvedVal : Types ValueRef {
1510     $1 = $1->resolve();
1511     std::string Name = getUniqueName($2.val, $1);
1512     $$ = $2;
1513     delete $$.val;
1514     $$.val = new std::string($1->getNewTy() + " " + Name);
1515     $$.type = $1;
1516   };
1517
1518 BasicBlockList : BasicBlockList BasicBlock {
1519     $$ = 0;
1520   }
1521   | BasicBlock { // Do not allow functions with 0 basic blocks   
1522     $$ = 0;
1523   };
1524
1525
1526 // Basic blocks are terminated by branching instructions: 
1527 // br, br/cc, switch, ret
1528 //
1529 BasicBlock : InstructionList BBTerminatorInst  {
1530     $$ = 0;
1531   };
1532
1533 InstructionList : InstructionList Inst {
1534     *O << "    " << *$2 << '\n';
1535     delete $2;
1536     $$ = 0;
1537   }
1538   | /* empty */ {
1539     $$ = 0;
1540   }
1541   | LABELSTR {
1542     *O << *$1 << '\n';
1543     delete $1;
1544     $$ = 0;
1545   };
1546
1547 Unwind : UNWIND | EXCEPT { $$ = $1; *$$ = "unwind"; }
1548
1549 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1550     *O << "    " << *$1 << ' ' << *$2.val << '\n';
1551     delete $1; $2.destroy();
1552     $$ = 0;
1553   }
1554   | RET VOID {                                       // Return with no result...
1555     *O << "    " << *$1 << ' ' << $2->getNewTy() << '\n';
1556     delete $1;
1557     $$ = 0;
1558   }
1559   | BR LABEL ValueRef {                         // Unconditional Branch...
1560     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << *$3.val << '\n';
1561     delete $1; $3.destroy();
1562     $$ = 0;
1563   }                                                  // Conditional Branch...
1564   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1565     std::string Name = getUniqueName($3.val, $2);
1566     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1567        << $5->getNewTy() << ' ' << *$6.val << ", " << $8->getNewTy() << ' ' 
1568        << *$9.val << '\n';
1569     delete $1; $3.destroy(); $6.destroy(); $9.destroy();
1570     $$ = 0;
1571   }
1572   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1573     std::string Name = getUniqueName($3.val, $2);
1574     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1575        << $5->getNewTy() << ' ' << *$6.val << " [" << *$8 << " ]\n";
1576     delete $1; $3.destroy(); $6.destroy(); 
1577     delete $8;
1578     $$ = 0;
1579   }
1580   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1581     std::string Name = getUniqueName($3.val, $2);
1582     *O << "    " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", " 
1583        << $5->getNewTy() << ' ' << *$6.val << "[]\n";
1584     delete $1; $3.destroy(); $6.destroy();
1585     $$ = 0;
1586   }
1587   | OptAssign INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1588     TO LABEL ValueRef Unwind LABEL ValueRef {
1589     const TypeInfo* ResTy = getFunctionReturnType($4);
1590     *O << "    ";
1591     if (!$1->empty()) {
1592       std::string Name = getUniqueName($1, ResTy);
1593       *O << Name << " = ";
1594     }
1595     *O << *$2 << ' ' << *$3 << ' ' << $4->getNewTy() << ' ' << *$5.val << " (";
1596     for (unsigned i = 0; i < $7->size(); ++i) {
1597       ValueInfo& VI = (*$7)[i];
1598       *O << *VI.val;
1599       if (i+1 < $7->size())
1600         *O << ", ";
1601       VI.destroy();
1602     }
1603     *O << ") " << *$9 << ' ' << $10->getNewTy() << ' ' << *$11.val << ' ' 
1604        << *$12 << ' ' << $13->getNewTy() << ' ' << *$14.val << '\n';
1605     delete $1; delete $2; delete $3; $5.destroy(); delete $7; 
1606     delete $9; $11.destroy(); delete $12; $14.destroy(); 
1607     $$ = 0;
1608   }
1609   | Unwind {
1610     *O << "    " << *$1 << '\n';
1611     delete $1;
1612     $$ = 0;
1613   }
1614   | UNREACHABLE {
1615     *O << "    " << *$1 << '\n';
1616     delete $1;
1617     $$ = 0;
1618   };
1619
1620 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1621     *$1 += " " + $2->getNewTy() + " " + *$3 + ", " + $5->getNewTy() + " " + 
1622            *$6.val;
1623     delete $3; $6.destroy();
1624     $$ = $1;
1625   }
1626   | IntType ConstValueRef ',' LABEL ValueRef {
1627     $2->insert(0, $1->getNewTy() + " " );
1628     *$2 += ", " + $4->getNewTy() + " " + *$5.val;
1629     $5.destroy();
1630     $$ = $2;
1631   };
1632
1633 Inst 
1634   : OptAssign InstVal {
1635     if (!$1->empty()) {
1636       // Get a unique name for this value, based on its type.
1637       std::string Name = getUniqueName($1, $2.type);
1638       *$1 = Name + " = ";
1639       if (deleteUselessCastFlag && *deleteUselessCastName == Name) {
1640         // don't actually delete it, just comment it out
1641         $1->insert(0, "; USELSS BITCAST: "); 
1642         delete deleteUselessCastName;
1643       }
1644     }
1645     *$1 += *$2.val;
1646     $2.destroy();
1647     deleteUselessCastFlag = false;
1648     $$ = $1; 
1649   };
1650
1651 PHIList 
1652   : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1653     std::string Name = getUniqueName($3.val, $1);
1654     Name.insert(0, $1->getNewTy() + "[");
1655     Name += "," + *$5.val + "]";
1656     $$.val = new std::string(Name);
1657     $$.type = $1;
1658     $3.destroy(); $5.destroy();
1659   }
1660   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1661     std::string Name = getUniqueName($4.val, $1.type);
1662     *$1.val += ", [" + Name + "," + *$6.val + "]";
1663     $4.destroy(); $6.destroy();
1664     $$ = $1;
1665   };
1666
1667
1668 ValueRefList 
1669   : ResolvedVal {
1670     $$ = new ValueList();
1671     $$->push_back($1);
1672   }
1673   | ValueRefList ',' ResolvedVal {
1674     $$ = $1;
1675     $$->push_back($3);
1676   };
1677
1678 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1679 ValueRefListE 
1680   : ValueRefList  { $$ = $1; }
1681   | /*empty*/ { $$ = new ValueList(); }
1682   ;
1683
1684 OptTailCall 
1685   : TAIL CALL {
1686     *$1 += " " + *$2;
1687     delete $2;
1688     $$ = $1;
1689   }
1690   | CALL 
1691   ;
1692
1693 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1694     const char* op = getDivRemOpcode(*$1, $2); 
1695     std::string Name1 = getUniqueName($3.val, $2);
1696     std::string Name2 = getUniqueName($5.val, $2);
1697     $$.val = new std::string(op);
1698     *$$.val += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1699     $$.type = $2;
1700     delete $1; $3.destroy(); $5.destroy();
1701   }
1702   | LogicalOps Types ValueRef ',' ValueRef {
1703     std::string Name1 = getUniqueName($3.val, $2);
1704     std::string Name2 = getUniqueName($5.val, $2);
1705     *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1706     $$.val = $1;
1707     $$.type = $2;
1708     $3.destroy(); $5.destroy();
1709   }
1710   | SetCondOps Types ValueRef ',' ValueRef {
1711     std::string Name1 = getUniqueName($3.val, $2);
1712     std::string Name2 = getUniqueName($5.val, $2);
1713     *$1 = getCompareOp(*$1, $2);
1714     *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1715     $$.val = $1;
1716     $$.type = TypeInfo::get("bool",BoolTy);
1717     $3.destroy(); $5.destroy();
1718   }
1719   | ICMP IPredicates Types ValueRef ',' ValueRef {
1720     std::string Name1 = getUniqueName($4.val, $3);
1721     std::string Name2 = getUniqueName($6.val, $3);
1722     *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
1723     $$.val = $1;
1724     $$.type = TypeInfo::get("bool",BoolTy);
1725     delete $2; $4.destroy(); $6.destroy();
1726   }
1727   | FCMP FPredicates Types ValueRef ',' ValueRef {
1728     std::string Name1 = getUniqueName($4.val, $3);
1729     std::string Name2 = getUniqueName($6.val, $3);
1730     *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
1731     $$.val = $1;
1732     $$.type = TypeInfo::get("bool",BoolTy);
1733     delete $2; $4.destroy(); $6.destroy();
1734   }
1735   | NOT ResolvedVal {
1736     $$ = $2;
1737     $$.val->insert(0, *$1 + " ");
1738     delete $1;
1739   }
1740   | ShiftOps ResolvedVal ',' ResolvedVal {
1741     const char* shiftop = $1->c_str();
1742     if (*$1 == "shr")
1743       shiftop = ($2.type->isUnsigned()) ? "lshr" : "ashr";
1744     $$.val = new std::string(shiftop);
1745     *$$.val += " " + *$2.val + ", " + *$4.val;
1746     $$.type = $2.type;
1747     delete $1; delete $2.val; $4.destroy();
1748   }
1749   | CastOps ResolvedVal TO Types {
1750     std::string source = *$2.val;
1751     const TypeInfo* SrcTy = $2.type->resolve();
1752     const TypeInfo* DstTy = $4->resolve();
1753     $$.val = new std::string();
1754     $$.type = DstTy;
1755     if (*$1 == "cast") {
1756       *$$.val += getCastUpgrade(source, SrcTy, DstTy, false);
1757     } else {
1758       *$$.val += *$1 + " " + source + " to " + DstTy->getNewTy();
1759     }
1760     // Check to see if this is a useless cast of a value to the same name
1761     // and the same type. Such casts will probably cause redefinition errors
1762     // when assembled and perform no code gen action so just remove them.
1763     if (*$1 == "cast" || *$1 == "bitcast")
1764       if (SrcTy->isInteger() && DstTy->isInteger() &&
1765           SrcTy->getBitWidth() == DstTy->getBitWidth()) {
1766         deleteUselessCastFlag = true; // Flag the "Inst" rule
1767         deleteUselessCastName = new std::string(*$2.val); // save the name
1768         size_t pos = deleteUselessCastName->find_first_of("%\"",0);
1769         if (pos != std::string::npos) {
1770           // remove the type portion before val
1771           deleteUselessCastName->erase(0, pos);
1772         }
1773       }
1774     delete $1; $2.destroy();
1775     delete $3;
1776   }
1777   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1778     *$1 += " " + *$2.val + ", " + *$4.val + ", " + *$6.val;
1779     $$.val = $1;
1780     $$.type = $4.type;
1781     $2.destroy(); delete $4.val; $6.destroy();
1782   }
1783   | VAARG ResolvedVal ',' Types {
1784     *$1 += " " + *$2.val + ", " + $4->getNewTy();
1785     $$.val = $1;
1786     $$.type = $4;
1787     $2.destroy();
1788   }
1789   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
1790     *$1 += " " + *$2.val + ", " + *$4.val;
1791     $$.val = $1;
1792     $2.type = $2.type->resolve();;
1793     $$.type = $2.type->getElementType();
1794     delete $2.val; $4.destroy();
1795   }
1796   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1797     *$1 += " " + *$2.val + ", " + *$4.val + ", " + *$6.val;
1798     $$.val = $1;
1799     $$.type = $2.type;
1800     delete $2.val; $4.destroy(); $6.destroy();
1801   }
1802   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1803     *$1 += " " + *$2.val + ", " + *$4.val + ", " + *$6.val;
1804     $$.val = $1;
1805     $$.type = $2.type;
1806     delete $2.val; $4.destroy(); $6.destroy();
1807   }
1808   | PHI_TOK PHIList {
1809     *$1 += " " + *$2.val;
1810     $$.val = $1;
1811     $$.type = $2.type;
1812     delete $2.val;
1813   }
1814   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
1815     if (!$2->empty())
1816       *$1 += " " + *$2;
1817     if (!$1->empty())
1818       *$1 += " ";
1819     *$1 += $3->getNewTy() + " " + *$4.val + "(";
1820     for (unsigned i = 0; i < $6->size(); ++i) {
1821       ValueInfo& VI = (*$6)[i];
1822       *$1 += *VI.val;
1823       if (i+1 < $6->size())
1824         *$1 += ", ";
1825       VI.destroy();
1826     }
1827     *$1 += ")";
1828     $$.val = $1;
1829     $$.type = getFunctionReturnType($3);
1830     delete $2; $4.destroy(); delete $6;
1831   }
1832   | MemoryInst ;
1833
1834
1835 // IndexList - List of indices for GEP based instructions...
1836 IndexList 
1837   : ',' ValueRefList { $$ = $2; }
1838   | /* empty */ {  $$ = new ValueList(); }
1839   ;
1840
1841 OptVolatile 
1842   : VOLATILE 
1843   | /* empty */ { $$ = new std::string(); }
1844   ;
1845
1846 MemoryInst : MALLOC Types OptCAlign {
1847     *$1 += " " + $2->getNewTy();
1848     if (!$3->empty())
1849       *$1 += " " + *$3;
1850     $$.val = $1;
1851     $$.type = $2->getPointerType();
1852     delete $3;
1853   }
1854   | MALLOC Types ',' UINT ValueRef OptCAlign {
1855     std::string Name = getUniqueName($5.val, $4);
1856     *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
1857     if (!$6->empty())
1858       *$1 += " " + *$6;
1859     $$.val = $1;
1860     $$.type = $2->getPointerType();
1861     $5.destroy(); delete $6;
1862   }
1863   | ALLOCA Types OptCAlign {
1864     *$1 += " " + $2->getNewTy();
1865     if (!$3->empty())
1866       *$1 += " " + *$3;
1867     $$.val = $1;
1868     $$.type = $2->getPointerType();
1869     delete $3;
1870   }
1871   | ALLOCA Types ',' UINT ValueRef OptCAlign {
1872     std::string Name = getUniqueName($5.val, $4);
1873     *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
1874     if (!$6->empty())
1875       *$1 += " " + *$6;
1876     $$.val = $1;
1877     $$.type = $2->getPointerType();
1878     $5.destroy(); delete $6;
1879   }
1880   | FREE ResolvedVal {
1881     *$1 += " " + *$2.val;
1882     $$.val = $1;
1883     $$.type = TypeInfo::get("void", VoidTy); 
1884     $2.destroy();
1885   }
1886   | OptVolatile LOAD Types ValueRef {
1887     std::string Name = getUniqueName($4.val, $3);
1888     if (!$1->empty())
1889       *$1 += " ";
1890     *$1 += *$2 + " " + $3->getNewTy() + " " + Name;
1891     $$.val = $1;
1892     $$.type = $3->getElementType();
1893     delete $2; $4.destroy();
1894   }
1895   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1896     std::string Name = getUniqueName($6.val, $5);
1897     if (!$1->empty())
1898       *$1 += " ";
1899     *$1 += *$2 + " " + *$3.val + ", " + $5->getNewTy() + " " + Name;
1900     $$.val = $1;
1901     $$.type = TypeInfo::get("void", VoidTy);
1902     delete $2; $3.destroy(); $6.destroy();
1903   }
1904   | GETELEMENTPTR Types ValueRef IndexList {
1905     std::string Name = getUniqueName($3.val, $2);
1906     // Upgrade the indices
1907     for (unsigned i = 0; i < $4->size(); ++i) {
1908       ValueInfo& VI = (*$4)[i];
1909       if (VI.type->isUnsigned() && !VI.isConstant() && 
1910           VI.type->getBitWidth() < 64) {
1911         std::string* old = VI.val;
1912         *O << "    %gep_upgrade" << unique << " = zext " << *old 
1913            << " to i64\n";
1914         VI.val = new std::string("i64 %gep_upgrade" + llvm::utostr(unique++));
1915         VI.type = TypeInfo::get("i64",ULongTy);
1916       }
1917     }
1918     *$1 += " " + $2->getNewTy() + " " + Name;
1919     for (unsigned i = 0; i < $4->size(); ++i) {
1920       ValueInfo& VI = (*$4)[i];
1921       *$1 += ", " + *VI.val;
1922     }
1923     $$.val = $1;
1924     $$.type = getGEPIndexedType($2,$4); 
1925     $3.destroy(); delete $4;
1926   };
1927
1928 %%
1929
1930 int yyerror(const char *ErrorMsg) {
1931   std::string where 
1932     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1933                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
1934   std::string errMsg = where + "error: " + std::string(ErrorMsg) + 
1935                        " while reading ";
1936   if (yychar == YYEMPTY || yychar == 0)
1937     errMsg += "end-of-file.";
1938   else
1939     errMsg += "token: '" + std::string(Upgradetext, Upgradeleng) + "'";
1940   std::cerr << "llvm-upgrade: " << errMsg << '\n';
1941   *O << "llvm-upgrade parse failed.\n";
1942   exit(1);
1943 }
1944
1945 static void warning(const std::string& ErrorMsg) {
1946   std::string where 
1947     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1948                   + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
1949   std::string errMsg = where + "warning: " + std::string(ErrorMsg) + 
1950                        " while reading ";
1951   if (yychar == YYEMPTY || yychar == 0)
1952     errMsg += "end-of-file.";
1953   else
1954     errMsg += "token: '" + std::string(Upgradetext, Upgradeleng) + "'";
1955   std::cerr << "llvm-upgrade: " << errMsg << '\n';
1956 }