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