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