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