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