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