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