e42ebc758be7b5e7b0a175d452d7be42824c33cb
[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               "gep_upgrade", CurBB);
1179     }
1180     // Add to the CIndices list, if requested.
1181     if (CIndices)
1182       CIndices->push_back(cast<Constant>(Index));
1183   }
1184
1185   const Type *IdxTy =
1186     GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1187     if (!IdxTy)
1188       error("Index list invalid for constant getelementptr");
1189   return IdxTy;
1190 }
1191
1192 Module* UpgradeAssembly(const std::string &infile, std::istream& in, 
1193                               bool debug, bool addAttrs)
1194 {
1195   Upgradelineno = 1; 
1196   CurFilename = infile;
1197   LexInput = &in;
1198   yydebug = debug;
1199   AddAttributes = addAttrs;
1200   ObsoleteVarArgs = false;
1201   NewVarArgs = false;
1202
1203   CurModule.CurrentModule = new Module(CurFilename);
1204
1205   // Check to make sure the parser succeeded
1206   if (yyparse()) {
1207     if (ParserResult)
1208       delete ParserResult;
1209     std::cerr << "llvm-upgrade: parse failed.\n";
1210     return 0;
1211   }
1212
1213   // Check to make sure that parsing produced a result
1214   if (!ParserResult) {
1215     std::cerr << "llvm-upgrade: no parse result.\n";
1216     return 0;
1217   }
1218
1219   // Reset ParserResult variable while saving its value for the result.
1220   Module *Result = ParserResult;
1221   ParserResult = 0;
1222
1223   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1224   {
1225     Function* F;
1226     if ((F = Result->getNamedFunction("llvm.va_start"))
1227         && F->getFunctionType()->getNumParams() == 0)
1228       ObsoleteVarArgs = true;
1229     if((F = Result->getNamedFunction("llvm.va_copy"))
1230        && F->getFunctionType()->getNumParams() == 1)
1231       ObsoleteVarArgs = true;
1232   }
1233
1234   if (ObsoleteVarArgs && NewVarArgs) {
1235     error("This file is corrupt: it uses both new and old style varargs");
1236     return 0;
1237   }
1238
1239   if(ObsoleteVarArgs) {
1240     if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1241       if (F->arg_size() != 0) {
1242         error("Obsolete va_start takes 0 argument");
1243         return 0;
1244       }
1245       
1246       //foo = va_start()
1247       // ->
1248       //bar = alloca typeof(foo)
1249       //va_start(bar)
1250       //foo = load bar
1251
1252       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1253       const Type* ArgTy = F->getFunctionType()->getReturnType();
1254       const Type* ArgTyPtr = PointerType::get(ArgTy);
1255       Function* NF = cast<Function>(Result->getOrInsertFunction(
1256         "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1257
1258       while (!F->use_empty()) {
1259         CallInst* CI = cast<CallInst>(F->use_back());
1260         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1261         new CallInst(NF, bar, "", CI);
1262         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1263         CI->replaceAllUsesWith(foo);
1264         CI->getParent()->getInstList().erase(CI);
1265       }
1266       Result->getFunctionList().erase(F);
1267     }
1268     
1269     if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1270       if(F->arg_size() != 1) {
1271         error("Obsolete va_end takes 1 argument");
1272         return 0;
1273       }
1274
1275       //vaend foo
1276       // ->
1277       //bar = alloca 1 of typeof(foo)
1278       //vaend bar
1279       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1280       const Type* ArgTy = F->getFunctionType()->getParamType(0);
1281       const Type* ArgTyPtr = PointerType::get(ArgTy);
1282       Function* NF = cast<Function>(Result->getOrInsertFunction(
1283         "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1284
1285       while (!F->use_empty()) {
1286         CallInst* CI = cast<CallInst>(F->use_back());
1287         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1288         new StoreInst(CI->getOperand(1), bar, CI);
1289         new CallInst(NF, bar, "", CI);
1290         CI->getParent()->getInstList().erase(CI);
1291       }
1292       Result->getFunctionList().erase(F);
1293     }
1294
1295     if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1296       if(F->arg_size() != 1) {
1297         error("Obsolete va_copy takes 1 argument");
1298         return 0;
1299       }
1300       //foo = vacopy(bar)
1301       // ->
1302       //a = alloca 1 of typeof(foo)
1303       //b = alloca 1 of typeof(foo)
1304       //store bar -> b
1305       //vacopy(a, b)
1306       //foo = load a
1307       
1308       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1309       const Type* ArgTy = F->getFunctionType()->getReturnType();
1310       const Type* ArgTyPtr = PointerType::get(ArgTy);
1311       Function* NF = cast<Function>(Result->getOrInsertFunction(
1312         "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1313
1314       while (!F->use_empty()) {
1315         CallInst* CI = cast<CallInst>(F->use_back());
1316         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1317         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1318         new StoreInst(CI->getOperand(1), b, CI);
1319         new CallInst(NF, a, b, "", CI);
1320         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1321         CI->replaceAllUsesWith(foo);
1322         CI->getParent()->getInstList().erase(CI);
1323       }
1324       Result->getFunctionList().erase(F);
1325     }
1326   }
1327
1328   return Result;
1329 }
1330
1331 } // end llvm namespace
1332
1333 using namespace llvm;
1334
1335 %}
1336
1337 %union {
1338   llvm::Module                           *ModuleVal;
1339   llvm::Function                         *FunctionVal;
1340   std::pair<llvm::PATypeInfo, char*>     *ArgVal;
1341   llvm::BasicBlock                       *BasicBlockVal;
1342   llvm::TerminatorInst                   *TermInstVal;
1343   llvm::InstrInfo                        InstVal;
1344   llvm::ConstInfo                        ConstVal;
1345   llvm::ValueInfo                        ValueVal;
1346   llvm::PATypeInfo                       TypeVal;
1347   llvm::TypeInfo                         PrimType;
1348   llvm::PHIListInfo                      PHIList;
1349   std::list<llvm::PATypeInfo>            *TypeList;
1350   std::vector<llvm::ValueInfo>           *ValueList;
1351   std::vector<llvm::ConstInfo>           *ConstVector;
1352
1353
1354   std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1355   // Represent the RHS of PHI node
1356   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1357
1358   llvm::GlobalValue::LinkageTypes         Linkage;
1359   int64_t                           SInt64Val;
1360   uint64_t                          UInt64Val;
1361   int                               SIntVal;
1362   unsigned                          UIntVal;
1363   double                            FPVal;
1364   bool                              BoolVal;
1365
1366   char                             *StrVal;   // This memory is strdup'd!
1367   llvm::ValID                       ValIDVal; // strdup'd memory maybe!
1368
1369   llvm::BinaryOps                   BinaryOpVal;
1370   llvm::TermOps                     TermOpVal;
1371   llvm::MemoryOps                   MemOpVal;
1372   llvm::OtherOps                    OtherOpVal;
1373   llvm::CastOps                     CastOpVal;
1374   llvm::ICmpInst::Predicate         IPred;
1375   llvm::FCmpInst::Predicate         FPred;
1376   llvm::Module::Endianness          Endianness;
1377 }
1378
1379 %type <ModuleVal>     Module FunctionList
1380 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
1381 %type <BasicBlockVal> BasicBlock InstructionList
1382 %type <TermInstVal>   BBTerminatorInst
1383 %type <InstVal>       Inst InstVal MemoryInst
1384 %type <ConstVal>      ConstVal ConstExpr
1385 %type <ConstVector>   ConstVector
1386 %type <ArgList>       ArgList ArgListH
1387 %type <ArgVal>        ArgVal
1388 %type <PHIList>       PHIList
1389 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
1390 %type <ValueList>     IndexList                   // For GEP derived indices
1391 %type <TypeList>      TypeListI ArgTypeListI
1392 %type <JumpTable>     JumpTable
1393 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
1394 %type <BoolVal>       OptVolatile                 // 'volatile' or not
1395 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
1396 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
1397 %type <Linkage>       OptLinkage
1398 %type <Endianness>    BigOrLittle
1399
1400 // ValueRef - Unresolved reference to a definition or BB
1401 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
1402 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
1403
1404 // Tokens and types for handling constant integer values
1405 //
1406 // ESINT64VAL - A negative number within long long range
1407 %token <SInt64Val> ESINT64VAL
1408
1409 // EUINT64VAL - A positive number within uns. long long range
1410 %token <UInt64Val> EUINT64VAL
1411 %type  <SInt64Val> EINT64VAL
1412
1413 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
1414 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
1415 %type   <SIntVal>   INTVAL
1416 %token  <FPVal>     FPVAL     // Float or Double constant
1417
1418 // Built in types...
1419 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
1420 %type  <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1421 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1422 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1423
1424 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1425 %type  <StrVal> Name OptName OptAssign
1426 %type  <UIntVal> OptAlign OptCAlign
1427 %type <StrVal> OptSection SectionString
1428
1429 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1430 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1431 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1432 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1433 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1434 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1435 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1436 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1437 %token DATALAYOUT
1438 %type <UIntVal> OptCallingConv
1439
1440 // Basic Block Terminating Operators
1441 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1442 %token UNWIND EXCEPT
1443
1444 // Binary Operators
1445 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1446 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM 
1447 %token <BinaryOpVal> AND OR XOR
1448 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comparators
1449 %token <OtherOpVal> ICMP FCMP
1450
1451 // Memory Instructions
1452 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1453
1454 // Other Operators
1455 %type  <OtherOpVal> ShiftOps
1456 %token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1457 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1458 %token VAARG_old VANEXT_old //OBSOLETE
1459
1460 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1461 %type  <IPred> IPredicates
1462 %type  <FPred> FPredicates
1463 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
1464 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1465
1466 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI 
1467 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST 
1468 %type  <CastOpVal> CastOps
1469
1470 %start Module
1471
1472 %%
1473
1474 // Handle constant integer size restriction and conversion...
1475 //
1476 INTVAL 
1477   : SINTVAL;
1478   | UINTVAL {
1479     if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
1480       error("Value too large for type");
1481     $$ = (int32_t)$1;
1482   }
1483   ;
1484
1485 EINT64VAL 
1486   : ESINT64VAL;      // These have same type and can't cause problems...
1487   | EUINT64VAL {
1488     if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1489       error("Value too large for type");
1490     $$ = (int64_t)$1;
1491   };
1492
1493 // Operations that are notably excluded from this list include:
1494 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1495 //
1496 ArithmeticOps
1497   : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1498   ;
1499
1500 LogicalOps   
1501   : AND | OR | XOR
1502   ;
1503
1504 SetCondOps   
1505   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1506   ;
1507
1508 IPredicates  
1509   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1510   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1511   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1512   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1513   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1514   ;
1515
1516 FPredicates  
1517   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1518   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1519   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1520   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1521   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1522   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1523   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1524   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1525   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1526   ;
1527 ShiftOps  
1528   : SHL | SHR | ASHR | LSHR
1529   ;
1530
1531 CastOps      
1532   : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI 
1533   | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1534   ;
1535
1536 // These are some types that allow classification if we only want a particular 
1537 // thing... for example, only a signed, unsigned, or integral type.
1538 SIntType 
1539   :  LONG |  INT |  SHORT | SBYTE
1540   ;
1541
1542 UIntType 
1543   : ULONG | UINT | USHORT | UBYTE
1544   ;
1545
1546 IntType  
1547   : SIntType | UIntType
1548   ;
1549
1550 FPType   
1551   : FLOAT | DOUBLE
1552   ;
1553
1554 // OptAssign - Value producing statements have an optional assignment component
1555 OptAssign 
1556   : Name '=' {
1557     $$ = $1;
1558   }
1559   | /*empty*/ {
1560     $$ = 0;
1561   };
1562
1563 OptLinkage 
1564   : INTERNAL    { $$ = GlobalValue::InternalLinkage; } 
1565   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; } 
1566   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1567   | APPENDING   { $$ = GlobalValue::AppendingLinkage; } 
1568   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1569   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1570   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } 
1571   | /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1572   ;
1573
1574 OptCallingConv 
1575   : /*empty*/          { $$ = CallingConv::C; } 
1576   | CCC_TOK            { $$ = CallingConv::C; } 
1577   | CSRETCC_TOK        { $$ = CallingConv::CSRet; } 
1578   | FASTCC_TOK         { $$ = CallingConv::Fast; } 
1579   | COLDCC_TOK         { $$ = CallingConv::Cold; } 
1580   | X86_STDCALLCC_TOK  { $$ = CallingConv::X86_StdCall; } 
1581   | X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } 
1582   | CC_TOK EUINT64VAL  {
1583     if ((unsigned)$2 != $2)
1584       error("Calling conv too large");
1585     $$ = $2;
1586   }
1587   ;
1588
1589 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1590 // a comma before it.
1591 OptAlign 
1592   : /*empty*/        { $$ = 0; } 
1593   | ALIGN EUINT64VAL {
1594     $$ = $2;
1595     if ($$ != 0 && !isPowerOf2_32($$))
1596       error("Alignment must be a power of two");
1597   }
1598   ;
1599
1600 OptCAlign 
1601   : /*empty*/ { $$ = 0; } 
1602   | ',' ALIGN EUINT64VAL {
1603     $$ = $3;
1604     if ($$ != 0 && !isPowerOf2_32($$))
1605       error("Alignment must be a power of two");
1606   }
1607   ;
1608
1609 SectionString 
1610   : SECTION STRINGCONSTANT {
1611     for (unsigned i = 0, e = strlen($2); i != e; ++i)
1612       if ($2[i] == '"' || $2[i] == '\\')
1613         error("Invalid character in section name");
1614     $$ = $2;
1615   }
1616   ;
1617
1618 OptSection 
1619   : /*empty*/ { $$ = 0; } 
1620   | SectionString { $$ = $1; }
1621   ;
1622
1623 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1624 // is set to be the global we are processing.
1625 //
1626 GlobalVarAttributes 
1627   : /* empty */ {} 
1628   | ',' GlobalVarAttribute GlobalVarAttributes {}
1629   ;
1630
1631 GlobalVarAttribute
1632   : SectionString {
1633     CurGV->setSection($1);
1634     free($1);
1635   } 
1636   | ALIGN EUINT64VAL {
1637     if ($2 != 0 && !isPowerOf2_32($2))
1638       error("Alignment must be a power of two");
1639     CurGV->setAlignment($2);
1640     
1641   }
1642   ;
1643
1644 //===----------------------------------------------------------------------===//
1645 // Types includes all predefined types... except void, because it can only be
1646 // used in specific contexts (function returning void for example).  To have
1647 // access to it, a user must explicitly use TypesV.
1648 //
1649
1650 // TypesV includes all of 'Types', but it also includes the void type.
1651 TypesV    
1652   : Types
1653   | VOID { 
1654     $$.T = new PATypeHolder($1.T); 
1655     $$.S = Signless;
1656   }
1657   ;
1658
1659 UpRTypesV 
1660   : UpRTypes 
1661   | VOID { 
1662     $$.T = new PATypeHolder($1.T); 
1663     $$.S = Signless;
1664   }
1665   ;
1666
1667 Types
1668   : UpRTypes {
1669     if (!UpRefs.empty())
1670       error("Invalid upreference in type: " + (*$1.T)->getDescription());
1671     $$ = $1;
1672   }
1673   ;
1674
1675 PrimType
1676   : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT 
1677   | LONG | ULONG | FLOAT | DOUBLE | LABEL
1678   ;
1679
1680 // Derived types are added later...
1681 UpRTypes 
1682   : PrimType { 
1683     $$.T = new PATypeHolder($1.T);
1684     $$.S = $1.S;
1685   }
1686   | OPAQUE {
1687     $$.T = new PATypeHolder(OpaqueType::get());
1688     $$.S = Signless;
1689   }
1690   | SymbolicValueRef {            // Named types are also simple types...
1691     const Type* tmp = getType($1);
1692     $$.T = new PATypeHolder(tmp);
1693     $$.S = Signless; // FIXME: what if its signed?
1694   }
1695   | '\\' EUINT64VAL {                   // Type UpReference
1696     if ($2 > (uint64_t)~0U) 
1697       error("Value out of range");
1698     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1699     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1700     $$.T = new PATypeHolder(OT);
1701     $$.S = Signless;
1702     UR_OUT("New Upreference!\n");
1703   }
1704   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1705     std::vector<const Type*> Params;
1706     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1707            E = $3->end(); I != E; ++I) {
1708       Params.push_back(I->T->get());
1709       delete I->T;
1710     }
1711     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1712     if (isVarArg) Params.pop_back();
1713
1714     $$.T = new PATypeHolder(HandleUpRefs(
1715                            FunctionType::get($1.T->get(),Params,isVarArg)));
1716     $$.S = $1.S;
1717     delete $1.T;    // Delete the return type handle
1718     delete $3;      // Delete the argument list
1719   }
1720   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1721     $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(), 
1722                                                         (unsigned)$2)));
1723     $$.S = $4.S;
1724     delete $4.T;
1725   }
1726   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1727      const llvm::Type* ElemTy = $4.T->get();
1728      if ((unsigned)$2 != $2)
1729         error("Unsigned result not equal to signed result");
1730      if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1731         error("Elements of a PackedType must be integer or floating point");
1732      if (!isPowerOf2_32($2))
1733        error("PackedType length should be a power of 2");
1734      $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy, 
1735                                           (unsigned)$2)));
1736      $$.S = $4.S;
1737      delete $4.T;
1738   }
1739   | '{' TypeListI '}' {                        // Structure type?
1740     std::vector<const Type*> Elements;
1741     for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1742            E = $2->end(); I != E; ++I)
1743       Elements.push_back(I->T->get());
1744     $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1745     $$.S = Signless;
1746     delete $2;
1747   }
1748   | '{' '}' {                                  // Empty structure type?
1749     $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1750     $$.S = Signless;
1751   }
1752   | '<' '{' TypeListI '}' '>' {                // Packed Structure type?
1753     std::vector<const Type*> Elements;
1754     for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1755            E = $3->end(); I != E; ++I) {
1756       Elements.push_back(I->T->get());
1757       delete I->T;
1758     }
1759     $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1760     $$.S = Signless;
1761     delete $3;
1762   }
1763   | '<' '{' '}' '>' {                          // Empty packed structure type?
1764     $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1765     $$.S = Signless;
1766   }
1767   | UpRTypes '*' {                             // Pointer type?
1768     if ($1.T->get() == Type::LabelTy)
1769       error("Cannot form a pointer to a basic block");
1770     $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1771     $$.S = $1.S;
1772     delete $1.T;
1773   }
1774   ;
1775
1776 // TypeList - Used for struct declarations and as a basis for function type 
1777 // declaration type lists
1778 //
1779 TypeListI 
1780   : UpRTypes {
1781     $$ = new std::list<PATypeInfo>();
1782     $$->push_back($1); 
1783   }
1784   | TypeListI ',' UpRTypes {
1785     ($$=$1)->push_back($3);
1786   }
1787   ;
1788
1789 // ArgTypeList - List of types for a function type declaration...
1790 ArgTypeListI 
1791   : TypeListI
1792   | TypeListI ',' DOTDOTDOT {
1793     PATypeInfo VoidTI;
1794     VoidTI.T = new PATypeHolder(Type::VoidTy);
1795     VoidTI.S = Signless;
1796     ($$=$1)->push_back(VoidTI);
1797   }
1798   | DOTDOTDOT {
1799     $$ = new std::list<PATypeInfo>();
1800     PATypeInfo VoidTI;
1801     VoidTI.T = new PATypeHolder(Type::VoidTy);
1802     VoidTI.S = Signless;
1803     $$->push_back(VoidTI);
1804   }
1805   | /*empty*/ {
1806     $$ = new std::list<PATypeInfo>();
1807   }
1808   ;
1809
1810 // ConstVal - The various declarations that go into the constant pool.  This
1811 // production is used ONLY to represent constants that show up AFTER a 'const',
1812 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1813 // into other expressions (such as integers and constexprs) are handled by the
1814 // ResolvedVal, ValueRef and ConstValueRef productions.
1815 //
1816 ConstVal
1817   : Types '[' ConstVector ']' { // Nonempty unsized arr
1818     const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1819     if (ATy == 0)
1820       error("Cannot make array constant with type: '" + 
1821             $1.T->get()->getDescription() + "'");
1822     const Type *ETy = ATy->getElementType();
1823     int NumElements = ATy->getNumElements();
1824
1825     // Verify that we have the correct size...
1826     if (NumElements != -1 && NumElements != (int)$3->size())
1827       error("Type mismatch: constant sized array initialized with " +
1828             utostr($3->size()) +  " arguments, but has size of " + 
1829             itostr(NumElements) + "");
1830
1831     // Verify all elements are correct type!
1832     std::vector<Constant*> Elems;
1833     for (unsigned i = 0; i < $3->size(); i++) {
1834       Constant *C = (*$3)[i].C;
1835       const Type* ValTy = C->getType();
1836       if (ETy != ValTy)
1837         error("Element #" + utostr(i) + " is not of type '" + 
1838               ETy->getDescription() +"' as required!\nIt is of type '"+
1839               ValTy->getDescription() + "'");
1840       Elems.push_back(C);
1841     }
1842     $$.C = ConstantArray::get(ATy, Elems);
1843     $$.S = $1.S;
1844     delete $1.T; 
1845     delete $3;
1846   }
1847   | Types '[' ']' {
1848     const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1849     if (ATy == 0)
1850       error("Cannot make array constant with type: '" + 
1851             $1.T->get()->getDescription() + "'");
1852     int NumElements = ATy->getNumElements();
1853     if (NumElements != -1 && NumElements != 0) 
1854       error("Type mismatch: constant sized array initialized with 0"
1855             " arguments, but has size of " + itostr(NumElements) +"");
1856     $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1857     $$.S = $1.S;
1858     delete $1.T;
1859   }
1860   | Types 'c' STRINGCONSTANT {
1861     const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1862     if (ATy == 0)
1863       error("Cannot make array constant with type: '" + 
1864             $1.T->get()->getDescription() + "'");
1865     int NumElements = ATy->getNumElements();
1866     const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1867     if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1868       error("String arrays require type i8, not '" + ETy->getDescription() + 
1869             "'");
1870     char *EndStr = UnEscapeLexed($3, true);
1871     if (NumElements != -1 && NumElements != (EndStr-$3))
1872       error("Can't build string constant of size " + 
1873             itostr((int)(EndStr-$3)) + " when array has size " + 
1874             itostr(NumElements) + "");
1875     std::vector<Constant*> Vals;
1876     for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1877       Vals.push_back(ConstantInt::get(ETy, *C));
1878     free($3);
1879     $$.C = ConstantArray::get(ATy, Vals);
1880     $$.S = $1.S;
1881     delete $1.T;
1882   }
1883   | Types '<' ConstVector '>' { // Nonempty unsized arr
1884     const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1885     if (PTy == 0)
1886       error("Cannot make packed constant with type: '" + 
1887             $1.T->get()->getDescription() + "'");
1888     const Type *ETy = PTy->getElementType();
1889     int NumElements = PTy->getNumElements();
1890     // Verify that we have the correct size...
1891     if (NumElements != -1 && NumElements != (int)$3->size())
1892       error("Type mismatch: constant sized packed initialized with " +
1893             utostr($3->size()) +  " arguments, but has size of " + 
1894             itostr(NumElements) + "");
1895     // Verify all elements are correct type!
1896     std::vector<Constant*> Elems;
1897     for (unsigned i = 0; i < $3->size(); i++) {
1898       Constant *C = (*$3)[i].C;
1899       const Type* ValTy = C->getType();
1900       if (ETy != ValTy)
1901         error("Element #" + utostr(i) + " is not of type '" + 
1902               ETy->getDescription() +"' as required!\nIt is of type '"+
1903               ValTy->getDescription() + "'");
1904       Elems.push_back(C);
1905     }
1906     $$.C = ConstantPacked::get(PTy, Elems);
1907     $$.S = $1.S;
1908     delete $1.T;
1909     delete $3;
1910   }
1911   | Types '{' ConstVector '}' {
1912     const StructType *STy = dyn_cast<StructType>($1.T->get());
1913     if (STy == 0)
1914       error("Cannot make struct constant with type: '" + 
1915             $1.T->get()->getDescription() + "'");
1916     if ($3->size() != STy->getNumContainedTypes())
1917       error("Illegal number of initializers for structure type");
1918
1919     // Check to ensure that constants are compatible with the type initializer!
1920     std::vector<Constant*> Fields;
1921     for (unsigned i = 0, e = $3->size(); i != e; ++i) {
1922       Constant *C = (*$3)[i].C;
1923       if (C->getType() != STy->getElementType(i))
1924         error("Expected type '" + STy->getElementType(i)->getDescription() +
1925               "' for element #" + utostr(i) + " of structure initializer");
1926       Fields.push_back(C);
1927     }
1928     $$.C = ConstantStruct::get(STy, Fields);
1929     $$.S = $1.S;
1930     delete $1.T;
1931     delete $3;
1932   }
1933   | Types '{' '}' {
1934     const StructType *STy = dyn_cast<StructType>($1.T->get());
1935     if (STy == 0)
1936       error("Cannot make struct constant with type: '" + 
1937               $1.T->get()->getDescription() + "'");
1938     if (STy->getNumContainedTypes() != 0)
1939       error("Illegal number of initializers for structure type");
1940     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1941     $$.S = $1.S;
1942     delete $1.T;
1943   }
1944   | Types '<' '{' ConstVector '}' '>' {
1945     const StructType *STy = dyn_cast<StructType>($1.T->get());
1946     if (STy == 0)
1947       error("Cannot make packed struct constant with type: '" + 
1948             $1.T->get()->getDescription() + "'");
1949     if ($4->size() != STy->getNumContainedTypes())
1950       error("Illegal number of initializers for packed structure type");
1951
1952     // Check to ensure that constants are compatible with the type initializer!
1953     std::vector<Constant*> Fields;
1954     for (unsigned i = 0, e = $4->size(); i != e; ++i) {
1955       Constant *C = (*$4)[i].C;
1956       if (C->getType() != STy->getElementType(i))
1957         error("Expected type '" + STy->getElementType(i)->getDescription() +
1958               "' for element #" + utostr(i) + " of packed struct initializer");
1959       Fields.push_back(C);
1960     }
1961     $$.C = ConstantStruct::get(STy, Fields);
1962     $$.S = $1.S;
1963     delete $1.T; 
1964     delete $4;
1965   }
1966   | Types '<' '{' '}' '>' {
1967     const StructType *STy = dyn_cast<StructType>($1.T->get());
1968     if (STy == 0)
1969       error("Cannot make packed struct constant with type: '" + 
1970               $1.T->get()->getDescription() + "'");
1971     if (STy->getNumContainedTypes() != 0)
1972       error("Illegal number of initializers for packed structure type");
1973     $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1974     $$.S = $1.S;
1975     delete $1.T;
1976   }
1977   | Types NULL_TOK {
1978     const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
1979     if (PTy == 0)
1980       error("Cannot make null pointer constant with type: '" + 
1981             $1.T->get()->getDescription() + "'");
1982     $$.C = ConstantPointerNull::get(PTy);
1983     $$.S = $1.S;
1984     delete $1.T;
1985   }
1986   | Types UNDEF {
1987     $$.C = UndefValue::get($1.T->get());
1988     $$.S = $1.S;
1989     delete $1.T;
1990   }
1991   | Types SymbolicValueRef {
1992     const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
1993     if (Ty == 0)
1994       error("Global const reference must be a pointer type, not" +
1995             $1.T->get()->getDescription());
1996
1997     // ConstExprs can exist in the body of a function, thus creating
1998     // GlobalValues whenever they refer to a variable.  Because we are in
1999     // the context of a function, getExistingValue will search the functions
2000     // symbol table instead of the module symbol table for the global symbol,
2001     // which throws things all off.  To get around this, we just tell
2002     // getExistingValue that we are at global scope here.
2003     //
2004     Function *SavedCurFn = CurFun.CurrentFunction;
2005     CurFun.CurrentFunction = 0;
2006     Value *V = getExistingValue(Ty, $2);
2007     CurFun.CurrentFunction = SavedCurFn;
2008
2009     // If this is an initializer for a constant pointer, which is referencing a
2010     // (currently) undefined variable, create a stub now that shall be replaced
2011     // in the future with the right type of variable.
2012     //
2013     if (V == 0) {
2014       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2015       const PointerType *PT = cast<PointerType>(Ty);
2016
2017       // First check to see if the forward references value is already created!
2018       PerModuleInfo::GlobalRefsType::iterator I =
2019         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2020     
2021       if (I != CurModule.GlobalRefs.end()) {
2022         V = I->second;             // Placeholder already exists, use it...
2023         $2.destroy();
2024       } else {
2025         std::string Name;
2026         if ($2.Type == ValID::NameVal) Name = $2.Name;
2027
2028         // Create the forward referenced global.
2029         GlobalValue *GV;
2030         if (const FunctionType *FTy = 
2031                  dyn_cast<FunctionType>(PT->getElementType())) {
2032           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2033                             CurModule.CurrentModule);
2034         } else {
2035           GV = new GlobalVariable(PT->getElementType(), false,
2036                                   GlobalValue::ExternalLinkage, 0,
2037                                   Name, CurModule.CurrentModule);
2038         }
2039
2040         // Keep track of the fact that we have a forward ref to recycle it
2041         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2042         V = GV;
2043       }
2044     }
2045     $$.C = cast<GlobalValue>(V);
2046     $$.S = $1.S;
2047     delete $1.T;            // Free the type handle
2048   }
2049   | Types ConstExpr {
2050     if ($1.T->get() != $2.C->getType())
2051       error("Mismatched types for constant expression");
2052     $$ = $2;
2053     $$.S = $1.S;
2054     delete $1.T;
2055   }
2056   | Types ZEROINITIALIZER {
2057     const Type *Ty = $1.T->get();
2058     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2059       error("Cannot create a null initialized value of this type");
2060     $$.C = Constant::getNullValue(Ty);
2061     $$.S = $1.S;
2062     delete $1.T;
2063   }
2064   | SIntType EINT64VAL {      // integral constants
2065     const Type *Ty = $1.T;
2066     if (!ConstantInt::isValueValidForType(Ty, $2))
2067       error("Constant value doesn't fit in type");
2068     $$.C = ConstantInt::get(Ty, $2);
2069     $$.S = Signed;
2070   }
2071   | UIntType EUINT64VAL {            // integral constants
2072     const Type *Ty = $1.T;
2073     if (!ConstantInt::isValueValidForType(Ty, $2))
2074       error("Constant value doesn't fit in type");
2075     $$.C = ConstantInt::get(Ty, $2);
2076     $$.S = Unsigned;
2077   }
2078   | BOOL TRUETOK {                      // Boolean constants
2079     $$.C = ConstantInt::get(Type::Int1Ty, true);
2080     $$.S = Unsigned;
2081   }
2082   | BOOL FALSETOK {                     // Boolean constants
2083     $$.C = ConstantInt::get(Type::Int1Ty, false);
2084     $$.S = Unsigned;
2085   }
2086   | FPType FPVAL {                   // Float & Double constants
2087     if (!ConstantFP::isValueValidForType($1.T, $2))
2088       error("Floating point constant invalid for type");
2089     $$.C = ConstantFP::get($1.T, $2);
2090     $$.S = Signless;
2091   }
2092   ;
2093
2094 ConstExpr
2095   : CastOps '(' ConstVal TO Types ')' {
2096     const Type* SrcTy = $3.C->getType();
2097     const Type* DstTy = $5.T->get();
2098     Signedness SrcSign = $3.S;
2099     Signedness DstSign = $5.S;
2100     if (!SrcTy->isFirstClassType())
2101       error("cast constant expression from a non-primitive type: '" +
2102             SrcTy->getDescription() + "'");
2103     if (!DstTy->isFirstClassType())
2104       error("cast constant expression to a non-primitive type: '" +
2105             DstTy->getDescription() + "'");
2106     $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2107     $$.S = DstSign;
2108     delete $5.T;
2109   }
2110   | GETELEMENTPTR '(' ConstVal IndexList ')' {
2111     const Type *Ty = $3.C->getType();
2112     if (!isa<PointerType>(Ty))
2113       error("GetElementPtr requires a pointer operand");
2114
2115     std::vector<Value*> VIndices;
2116     std::vector<Constant*> CIndices;
2117     upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2118
2119     delete $4;
2120     $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2121     $$.S = Signless;
2122   }
2123   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2124     if (!$3.C->getType()->isInteger() ||
2125         cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2126       error("Select condition must be bool type");
2127     if ($5.C->getType() != $7.C->getType())
2128       error("Select operand types must match");
2129     $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2130     $$.S = Unsigned;
2131   }
2132   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2133     const Type *Ty = $3.C->getType();
2134     if (Ty != $5.C->getType())
2135       error("Binary operator types must match");
2136     // First, make sure we're dealing with the right opcode by upgrading from
2137     // obsolete versions.
2138     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2139
2140     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2141     // To retain backward compatibility with these early compilers, we emit a
2142     // cast to the appropriate integer type automatically if we are in the
2143     // broken case.  See PR424 for more information.
2144     if (!isa<PointerType>(Ty)) {
2145       $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2146     } else {
2147       const Type *IntPtrTy = 0;
2148       switch (CurModule.CurrentModule->getPointerSize()) {
2149       case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2150       case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2151       default: error("invalid pointer binary constant expr");
2152       }
2153       $$.C = ConstantExpr::get(Opcode, 
2154              ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2155              ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2156       $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2157     }
2158     $$.S = $3.S; 
2159   }
2160   | LogicalOps '(' ConstVal ',' ConstVal ')' {
2161     const Type* Ty = $3.C->getType();
2162     if (Ty != $5.C->getType())
2163       error("Logical operator types must match");
2164     if (!Ty->isInteger()) {
2165       if (!isa<PackedType>(Ty) || 
2166           !cast<PackedType>(Ty)->getElementType()->isInteger())
2167         error("Logical operator requires integer operands");
2168     }
2169     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2170     $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2171     $$.S = $3.S;
2172   }
2173   | SetCondOps '(' ConstVal ',' ConstVal ')' {
2174     const Type* Ty = $3.C->getType();
2175     if (Ty != $5.C->getType())
2176       error("setcc operand types must match");
2177     unsigned short pred;
2178     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2179     $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2180     $$.S = Unsigned;
2181   }
2182   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2183     if ($4.C->getType() != $6.C->getType()) 
2184       error("icmp operand types must match");
2185     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2186     $$.S = Unsigned;
2187   }
2188   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2189     if ($4.C->getType() != $6.C->getType()) 
2190       error("fcmp operand types must match");
2191     $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2192     $$.S = Unsigned;
2193   }
2194   | ShiftOps '(' ConstVal ',' ConstVal ')' {
2195     if (!$5.C->getType()->isInteger() ||
2196         cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2197       error("Shift count for shift constant must be unsigned byte");
2198     if (!$3.C->getType()->isInteger())
2199       error("Shift constant expression requires integer operand");
2200     $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2201     $$.S = $3.S;
2202   }
2203   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2204     if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2205       error("Invalid extractelement operands");
2206     $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2207     $$.S = $3.S;
2208   }
2209   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2210     if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2211       error("Invalid insertelement operands");
2212     $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2213     $$.S = $3.S;
2214   }
2215   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2216     if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2217       error("Invalid shufflevector operands");
2218     $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2219     $$.S = $3.S;
2220   }
2221   ;
2222
2223
2224 // ConstVector - A list of comma separated constants.
2225 ConstVector 
2226   : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2227   | ConstVal {
2228     $$ = new std::vector<ConstInfo>();
2229     $$->push_back($1);
2230   }
2231   ;
2232
2233
2234 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2235 GlobalType 
2236   : GLOBAL { $$ = false; } 
2237   | CONSTANT { $$ = true; }
2238   ;
2239
2240
2241 //===----------------------------------------------------------------------===//
2242 //                             Rules to match Modules
2243 //===----------------------------------------------------------------------===//
2244
2245 // Module rule: Capture the result of parsing the whole file into a result
2246 // variable...
2247 //
2248 Module 
2249   : FunctionList {
2250     $$ = ParserResult = $1;
2251     CurModule.ModuleDone();
2252   }
2253   ;
2254
2255 // FunctionList - A list of functions, preceeded by a constant pool.
2256 //
2257 FunctionList 
2258   : FunctionList Function { $$ = $1; CurFun.FunctionDone(); } 
2259   | FunctionList FunctionProto { $$ = $1; }
2260   | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }  
2261   | FunctionList IMPLEMENTATION { $$ = $1; }
2262   | ConstPool {
2263     $$ = CurModule.CurrentModule;
2264     // Emit an error if there are any unresolved types left.
2265     if (!CurModule.LateResolveTypes.empty()) {
2266       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2267       if (DID.Type == ValID::NameVal) {
2268         error("Reference to an undefined type: '"+DID.getName() + "'");
2269       } else {
2270         error("Reference to an undefined type: #" + itostr(DID.Num));
2271       }
2272     }
2273   }
2274   ;
2275
2276 // ConstPool - Constants with optional names assigned to them.
2277 ConstPool 
2278   : ConstPool OptAssign TYPE TypesV {
2279     // Eagerly resolve types.  This is not an optimization, this is a
2280     // requirement that is due to the fact that we could have this:
2281     //
2282     // %list = type { %list * }
2283     // %list = type { %list * }    ; repeated type decl
2284     //
2285     // If types are not resolved eagerly, then the two types will not be
2286     // determined to be the same type!
2287     //
2288     const Type* Ty = $4.T->get();
2289     ResolveTypeTo($2, Ty);
2290
2291     if (!setTypeName(Ty, $2) && !$2) {
2292       // If this is a named type that is not a redefinition, add it to the slot
2293       // table.
2294       CurModule.Types.push_back(Ty);
2295     }
2296     delete $4.T;
2297   }
2298   | ConstPool FunctionProto {       // Function prototypes can be in const pool
2299   }
2300   | ConstPool MODULE ASM_TOK AsmBlock {  // Asm blocks can be in the const pool
2301   }
2302   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2303     if ($5.C == 0) 
2304       error("Global value initializer is not a constant");
2305     CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2306   } GlobalVarAttributes {
2307     CurGV = 0;
2308   }
2309   | ConstPool OptAssign EXTERNAL GlobalType Types {
2310     const Type *Ty = $5.T->get();
2311     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2312     delete $5.T;
2313   } GlobalVarAttributes {
2314     CurGV = 0;
2315   }
2316   | ConstPool OptAssign DLLIMPORT GlobalType Types {
2317     const Type *Ty = $5.T->get();
2318     CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2319     delete $5.T;
2320   } GlobalVarAttributes {
2321     CurGV = 0;
2322   }
2323   | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2324     const Type *Ty = $5.T->get();
2325     CurGV = 
2326       ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2327     delete $5.T;
2328   } GlobalVarAttributes {
2329     CurGV = 0;
2330   }
2331   | ConstPool TARGET TargetDefinition { 
2332   }
2333   | ConstPool DEPLIBS '=' LibrariesDefinition {
2334   }
2335   | /* empty: end of list */ { 
2336   }
2337   ;
2338
2339 AsmBlock 
2340   : STRINGCONSTANT {
2341     const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2342     char *EndStr = UnEscapeLexed($1, true);
2343     std::string NewAsm($1, EndStr);
2344     free($1);
2345
2346     if (AsmSoFar.empty())
2347       CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2348     else
2349       CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2350   }
2351   ;
2352
2353 BigOrLittle 
2354   : BIG    { $$ = Module::BigEndian; };
2355   | LITTLE { $$ = Module::LittleEndian; }
2356   ;
2357
2358 TargetDefinition 
2359   : ENDIAN '=' BigOrLittle {
2360     CurModule.setEndianness($3);
2361   }
2362   | POINTERSIZE '=' EUINT64VAL {
2363     if ($3 == 32)
2364       CurModule.setPointerSize(Module::Pointer32);
2365     else if ($3 == 64)
2366       CurModule.setPointerSize(Module::Pointer64);
2367     else
2368       error("Invalid pointer size: '" + utostr($3) + "'");
2369   }
2370   | TRIPLE '=' STRINGCONSTANT {
2371     CurModule.CurrentModule->setTargetTriple($3);
2372     free($3);
2373   }
2374   | DATALAYOUT '=' STRINGCONSTANT {
2375     CurModule.CurrentModule->setDataLayout($3);
2376     free($3);
2377   }
2378   ;
2379
2380 LibrariesDefinition 
2381   : '[' LibList ']'
2382   ;
2383
2384 LibList 
2385   : LibList ',' STRINGCONSTANT {
2386       CurModule.CurrentModule->addLibrary($3);
2387       free($3);
2388   }
2389   | STRINGCONSTANT {
2390     CurModule.CurrentModule->addLibrary($1);
2391     free($1);
2392   }
2393   | /* empty: end of list */ { }
2394   ;
2395
2396 //===----------------------------------------------------------------------===//
2397 //                       Rules to match Function Headers
2398 //===----------------------------------------------------------------------===//
2399
2400 Name 
2401   : VAR_ID | STRINGCONSTANT
2402   ;
2403
2404 OptName 
2405   : Name 
2406   | /*empty*/ { $$ = 0; }
2407   ;
2408
2409 ArgVal 
2410   : Types OptName {
2411     if ($1.T->get() == Type::VoidTy)
2412       error("void typed arguments are invalid");
2413     $$ = new std::pair<PATypeInfo, char*>($1, $2);
2414   }
2415   ;
2416
2417 ArgListH 
2418   : ArgListH ',' ArgVal {
2419     $$ = $1;
2420     $$->push_back(*$3);
2421     delete $3;
2422   }
2423   | ArgVal {
2424     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2425     $$->push_back(*$1);
2426     delete $1;
2427   }
2428   ;
2429
2430 ArgList 
2431   : ArgListH { $$ = $1; }
2432   | ArgListH ',' DOTDOTDOT {
2433     $$ = $1;
2434     PATypeInfo VoidTI;
2435     VoidTI.T = new PATypeHolder(Type::VoidTy);
2436     VoidTI.S = Signless;
2437     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2438   }
2439   | DOTDOTDOT {
2440     $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2441     PATypeInfo VoidTI;
2442     VoidTI.T = new PATypeHolder(Type::VoidTy);
2443     VoidTI.S = Signless;
2444     $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2445   }
2446   | /* empty */ { $$ = 0; }
2447   ;
2448
2449 FunctionHeaderH 
2450   : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2451     UnEscapeLexed($3);
2452     std::string FunctionName($3);
2453     free($3);  // Free strdup'd memory!
2454
2455     const Type* RetTy = $2.T->get();
2456     
2457     if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2458       error("LLVM functions cannot return aggregate types");
2459
2460     std::vector<const Type*> ParamTypeList;
2461
2462     // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2463     // i8*. We check here for those names and override the parameter list
2464     // types to ensure the prototype is correct.
2465     if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2466       ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2467     } else if (FunctionName == "llvm.va_copy") {
2468       ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2469       ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2470     } else if ($5) {   // If there are arguments...
2471       for (std::vector<std::pair<PATypeInfo,char*> >::iterator 
2472            I = $5->begin(), E = $5->end(); I != E; ++I) {
2473         const Type *Ty = I->first.T->get();
2474         ParamTypeList.push_back(Ty);
2475       }
2476     }
2477
2478     bool isVarArg = 
2479       ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2480     if (isVarArg) ParamTypeList.pop_back();
2481
2482     const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg);
2483     const PointerType *PFT = PointerType::get(FT);
2484     delete $2.T;
2485
2486     ValID ID;
2487     if (!FunctionName.empty()) {
2488       ID = ValID::create((char*)FunctionName.c_str());
2489     } else {
2490       ID = ValID::create((int)CurModule.Values[PFT].size());
2491     }
2492
2493     Function *Fn = 0;
2494     // See if this function was forward referenced.  If so, recycle the object.
2495     if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2496       // Move the function to the end of the list, from whereever it was 
2497       // previously inserted.
2498       Fn = cast<Function>(FWRef);
2499       CurModule.CurrentModule->getFunctionList().remove(Fn);
2500       CurModule.CurrentModule->getFunctionList().push_back(Fn);
2501     } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2502                (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2503       // If this is the case, either we need to be a forward decl, or it needs 
2504       // to be.
2505       if (!CurFun.isDeclare && !Fn->isExternal())
2506         error("Redefinition of function '" + FunctionName + "'");
2507       
2508       // Make sure to strip off any argument names so we can't get conflicts.
2509       if (Fn->isExternal())
2510         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2511              AI != AE; ++AI)
2512           AI->setName("");
2513     } else  {  // Not already defined?
2514       Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2515                         CurModule.CurrentModule);
2516
2517       InsertValue(Fn, CurModule.Values);
2518     }
2519
2520     CurFun.FunctionStart(Fn);
2521
2522     if (CurFun.isDeclare) {
2523       // If we have declaration, always overwrite linkage.  This will allow us 
2524       // to correctly handle cases, when pointer to function is passed as 
2525       // argument to another function.
2526       Fn->setLinkage(CurFun.Linkage);
2527     }
2528     Fn->setCallingConv($1);
2529     Fn->setAlignment($8);
2530     if ($7) {
2531       Fn->setSection($7);
2532       free($7);
2533     }
2534
2535     // Add all of the arguments we parsed to the function...
2536     if ($5) {                     // Is null if empty...
2537       if (isVarArg) {  // Nuke the last entry
2538         assert($5->back().first.T->get() == Type::VoidTy && 
2539                $5->back().second == 0 && "Not a varargs marker");
2540         delete $5->back().first.T;
2541         $5->pop_back();  // Delete the last entry
2542       }
2543       Function::arg_iterator ArgIt = Fn->arg_begin();
2544       for (std::vector<std::pair<PATypeInfo,char*> >::iterator 
2545            I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2546         delete I->first.T;                        // Delete the typeholder...
2547         setValueName(ArgIt, I->second);           // Insert arg into symtab...
2548         InsertValue(ArgIt);
2549       }
2550       delete $5;                     // We're now done with the argument list
2551     }
2552   }
2553   ;
2554
2555 BEGIN 
2556   : BEGINTOK | '{'                // Allow BEGIN or '{' to start a function
2557   ;
2558
2559 FunctionHeader 
2560   : OptLinkage FunctionHeaderH BEGIN {
2561     $$ = CurFun.CurrentFunction;
2562
2563     // Make sure that we keep track of the linkage type even if there was a
2564     // previous "declare".
2565     $$->setLinkage($1);
2566   }
2567   ;
2568
2569 END 
2570   : ENDTOK | '}'                    // Allow end of '}' to end a function
2571   ;
2572
2573 Function 
2574   : BasicBlockList END {
2575     $$ = $1;
2576   };
2577
2578 FnDeclareLinkage
2579   : /*default*/ 
2580   | DLLIMPORT   { CurFun.Linkage = GlobalValue::DLLImportLinkage; } 
2581   | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
2582   ;
2583   
2584 FunctionProto 
2585   : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2586     $$ = CurFun.CurrentFunction;
2587     CurFun.FunctionDone();
2588     
2589   }
2590   ;
2591
2592 //===----------------------------------------------------------------------===//
2593 //                        Rules to match Basic Blocks
2594 //===----------------------------------------------------------------------===//
2595
2596 OptSideEffect 
2597   : /* empty */ { $$ = false; }
2598   | SIDEEFFECT { $$ = true; }
2599   ;
2600
2601 ConstValueRef 
2602     // A reference to a direct constant
2603   : ESINT64VAL {    $$ = ValID::create($1); }
2604   | EUINT64VAL { $$ = ValID::create($1); }
2605   | FPVAL { $$ = ValID::create($1); } 
2606   | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); } 
2607   | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2608   | NULL_TOK { $$ = ValID::createNull(); }
2609   | UNDEF { $$ = ValID::createUndef(); }
2610   | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2611   | '<' ConstVector '>' { // Nonempty unsized packed vector
2612     const Type *ETy = (*$2)[0].C->getType();
2613     int NumElements = $2->size(); 
2614     PackedType* pt = PackedType::get(ETy, NumElements);
2615     PATypeHolder* PTy = new PATypeHolder(
2616       HandleUpRefs(PackedType::get(ETy, NumElements)));
2617     
2618     // Verify all elements are correct type!
2619     std::vector<Constant*> Elems;
2620     for (unsigned i = 0; i < $2->size(); i++) {
2621       Constant *C = (*$2)[i].C;
2622       const Type *CTy = C->getType();
2623       if (ETy != CTy)
2624         error("Element #" + utostr(i) + " is not of type '" + 
2625               ETy->getDescription() +"' as required!\nIt is of type '" +
2626               CTy->getDescription() + "'");
2627       Elems.push_back(C);
2628     }
2629     $$ = ValID::create(ConstantPacked::get(pt, Elems));
2630     delete PTy; delete $2;
2631   }
2632   | ConstExpr {
2633     $$ = ValID::create($1.C);
2634   }
2635   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2636     char *End = UnEscapeLexed($3, true);
2637     std::string AsmStr = std::string($3, End);
2638     End = UnEscapeLexed($5, true);
2639     std::string Constraints = std::string($5, End);
2640     $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2641     free($3);
2642     free($5);
2643   }
2644   ;
2645
2646 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2647 // another value.
2648 //
2649 SymbolicValueRef 
2650   : INTVAL {  $$ = ValID::create($1); }
2651   | Name   {  $$ = ValID::create($1); }
2652   ;
2653
2654 // ValueRef - A reference to a definition... either constant or symbolic
2655 ValueRef 
2656   : SymbolicValueRef | ConstValueRef
2657   ;
2658
2659
2660 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2661 // type immediately preceeds the value reference, and allows complex constant
2662 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2663 ResolvedVal 
2664   : Types ValueRef { 
2665     const Type *Ty = $1.T->get();
2666     $$.S = $1.S;
2667     $$.V = getVal(Ty, $2); 
2668     delete $1.T;
2669   }
2670   ;
2671
2672 BasicBlockList 
2673   : BasicBlockList BasicBlock {
2674     $$ = $1;
2675   }
2676   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2677     $$ = $1;
2678   };
2679
2680
2681 // Basic blocks are terminated by branching instructions: 
2682 // br, br/cc, switch, ret
2683 //
2684 BasicBlock 
2685   : InstructionList OptAssign BBTerminatorInst  {
2686     setValueName($3, $2);
2687     InsertValue($3);
2688     $1->getInstList().push_back($3);
2689     InsertValue($1);
2690     $$ = $1;
2691   }
2692   ;
2693
2694 InstructionList
2695   : InstructionList Inst {
2696     if ($2.I)
2697       $1->getInstList().push_back($2.I);
2698     $$ = $1;
2699   }
2700   | /* empty */ {
2701     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2702     // Make sure to move the basic block to the correct location in the
2703     // function, instead of leaving it inserted wherever it was first
2704     // referenced.
2705     Function::BasicBlockListType &BBL = 
2706       CurFun.CurrentFunction->getBasicBlockList();
2707     BBL.splice(BBL.end(), BBL, $$);
2708   }
2709   | LABELSTR {
2710     $$ = CurBB = getBBVal(ValID::create($1), true);
2711     // Make sure to move the basic block to the correct location in the
2712     // function, instead of leaving it inserted wherever it was first
2713     // referenced.
2714     Function::BasicBlockListType &BBL = 
2715       CurFun.CurrentFunction->getBasicBlockList();
2716     BBL.splice(BBL.end(), BBL, $$);
2717   }
2718   ;
2719
2720 Unwind : UNWIND | EXCEPT;
2721
2722 BBTerminatorInst 
2723   : RET ResolvedVal {              // Return with a result...
2724     $$ = new ReturnInst($2.V);
2725   }
2726   | RET VOID {                                       // Return with no result...
2727     $$ = new ReturnInst();
2728   }
2729   | BR LABEL ValueRef {                         // Unconditional Branch...
2730     BasicBlock* tmpBB = getBBVal($3);
2731     $$ = new BranchInst(tmpBB);
2732   }                                                  // Conditional Branch...
2733   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2734     BasicBlock* tmpBBA = getBBVal($6);
2735     BasicBlock* tmpBBB = getBBVal($9);
2736     Value* tmpVal = getVal(Type::Int1Ty, $3);
2737     $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2738   }
2739   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2740     Value* tmpVal = getVal($2.T, $3);
2741     BasicBlock* tmpBB = getBBVal($6);
2742     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2743     $$ = S;
2744     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2745       E = $8->end();
2746     for (; I != E; ++I) {
2747       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2748           S->addCase(CI, I->second);
2749       else
2750         error("Switch case is constant, but not a simple integer");
2751     }
2752     delete $8;
2753   }
2754   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2755     Value* tmpVal = getVal($2.T, $3);
2756     BasicBlock* tmpBB = getBBVal($6);
2757     SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2758     $$ = S;
2759   }
2760   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2761     TO LABEL ValueRef Unwind LABEL ValueRef {
2762     const PointerType *PFTy;
2763     const FunctionType *Ty;
2764
2765     if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2766         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2767       // Pull out the types of all of the arguments...
2768       std::vector<const Type*> ParamTypes;
2769       if ($6) {
2770         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2771              I != E; ++I)
2772           ParamTypes.push_back((*I).V->getType());
2773       }
2774       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2775       if (isVarArg) ParamTypes.pop_back();
2776       Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg);
2777       PFTy = PointerType::get(Ty);
2778     }
2779     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2780     BasicBlock *Normal = getBBVal($10);
2781     BasicBlock *Except = getBBVal($13);
2782
2783     // Create the call node...
2784     if (!$6) {                                   // Has no arguments?
2785       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2786     } else {                                     // Has arguments?
2787       // Loop through FunctionType's arguments and ensure they are specified
2788       // correctly!
2789       //
2790       FunctionType::param_iterator I = Ty->param_begin();
2791       FunctionType::param_iterator E = Ty->param_end();
2792       std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2793
2794       std::vector<Value*> Args;
2795       for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2796         if ((*ArgI).V->getType() != *I)
2797           error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2798                 (*I)->getDescription() + "'");
2799         Args.push_back((*ArgI).V);
2800       }
2801
2802       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2803         error("Invalid number of parameters detected");
2804
2805       $$ = new InvokeInst(V, Normal, Except, Args);
2806     }
2807     cast<InvokeInst>($$)->setCallingConv($2);
2808     delete $3.T;
2809     delete $6;
2810   }
2811   | Unwind {
2812     $$ = new UnwindInst();
2813   }
2814   | UNREACHABLE {
2815     $$ = new UnreachableInst();
2816   }
2817   ;
2818
2819 JumpTable 
2820   : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2821     $$ = $1;
2822     Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2823     
2824     if (V == 0)
2825       error("May only switch on a constant pool value");
2826
2827     BasicBlock* tmpBB = getBBVal($6);
2828     $$->push_back(std::make_pair(V, tmpBB));
2829   }
2830   | IntType ConstValueRef ',' LABEL ValueRef {
2831     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2832     Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2833
2834     if (V == 0)
2835       error("May only switch on a constant pool value");
2836
2837     BasicBlock* tmpBB = getBBVal($5);
2838     $$->push_back(std::make_pair(V, tmpBB)); 
2839   }
2840   ;
2841
2842 Inst 
2843   : OptAssign InstVal {
2844     bool omit = false;
2845     if ($1)
2846       if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2847         if (BCI->getSrcTy() == BCI->getDestTy() && 
2848             BCI->getOperand(0)->getName() == $1)
2849           // This is a useless bit cast causing a name redefinition. It is
2850           // a bit cast from a type to the same type of an operand with the
2851           // same name as the name we would give this instruction. Since this
2852           // instruction results in no code generation, it is safe to omit
2853           // the instruction. This situation can occur because of collapsed
2854           // type planes. For example:
2855           //   %X = add int %Y, %Z
2856           //   %X = cast int %Y to uint
2857           // After upgrade, this looks like:
2858           //   %X = add i32 %Y, %Z
2859           //   %X = bitcast i32 to i32
2860           // The bitcast is clearly useless so we omit it.
2861           omit = true;
2862     if (omit) {
2863       $$.I = 0;
2864       $$.S = Signless;
2865     } else {
2866       setValueName($2.I, $1);
2867       InsertValue($2.I);
2868       $$ = $2;
2869     }
2870   };
2871
2872 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2873     $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2874     $$.S = $1.S;
2875     Value* tmpVal = getVal($1.T->get(), $3);
2876     BasicBlock* tmpBB = getBBVal($5);
2877     $$.P->push_back(std::make_pair(tmpVal, tmpBB));
2878     delete $1.T;
2879   }
2880   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2881     $$ = $1;
2882     Value* tmpVal = getVal($1.P->front().first->getType(), $4);
2883     BasicBlock* tmpBB = getBBVal($6);
2884     $1.P->push_back(std::make_pair(tmpVal, tmpBB));
2885   }
2886   ;
2887
2888 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
2889     $$ = new std::vector<ValueInfo>();
2890     $$->push_back($1);
2891   }
2892   | ValueRefList ',' ResolvedVal {
2893     $$ = $1;
2894     $1->push_back($3);
2895   };
2896
2897 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2898 ValueRefListE 
2899   : ValueRefList 
2900   | /*empty*/ { $$ = 0; }
2901   ;
2902
2903 OptTailCall 
2904   : TAIL CALL {
2905     $$ = true;
2906   }
2907   | CALL {
2908     $$ = false;
2909   }
2910   ;
2911
2912 InstVal 
2913   : ArithmeticOps Types ValueRef ',' ValueRef {
2914     const Type* Ty = $2.T->get();
2915     if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
2916       error("Arithmetic operator requires integer, FP, or packed operands");
2917     if (isa<PackedType>(Ty) && 
2918         ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
2919       error("Remainder not supported on packed types");
2920     // Upgrade the opcode from obsolete versions before we do anything with it.
2921     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2922     Value* val1 = getVal(Ty, $3); 
2923     Value* val2 = getVal(Ty, $5);
2924     $$.I = BinaryOperator::create(Opcode, val1, val2);
2925     if ($$.I == 0)
2926       error("binary operator returned null");
2927     $$.S = $2.S;
2928     delete $2.T;
2929   }
2930   | LogicalOps Types ValueRef ',' ValueRef {
2931     const Type *Ty = $2.T->get();
2932     if (!Ty->isInteger()) {
2933       if (!isa<PackedType>(Ty) ||
2934           !cast<PackedType>(Ty)->getElementType()->isInteger())
2935         error("Logical operator requires integral operands");
2936     }
2937     Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2938     Value* tmpVal1 = getVal(Ty, $3);
2939     Value* tmpVal2 = getVal(Ty, $5);
2940     $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
2941     if ($$.I == 0)
2942       error("binary operator returned null");
2943     $$.S = $2.S;
2944     delete $2.T;
2945   }
2946   | SetCondOps Types ValueRef ',' ValueRef {
2947     const Type* Ty = $2.T->get();
2948     if(isa<PackedType>(Ty))
2949       error("PackedTypes currently not supported in setcc instructions");
2950     unsigned short pred;
2951     Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
2952     Value* tmpVal1 = getVal(Ty, $3);
2953     Value* tmpVal2 = getVal(Ty, $5);
2954     $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
2955     if ($$.I == 0)
2956       error("binary operator returned null");
2957     $$.S = Unsigned;
2958     delete $2.T;
2959   }
2960   | ICMP IPredicates Types ValueRef ',' ValueRef {
2961     const Type *Ty = $3.T->get();
2962     if (isa<PackedType>(Ty)) 
2963       error("PackedTypes currently not supported in icmp instructions");
2964     else if (!Ty->isInteger() && !isa<PointerType>(Ty))
2965       error("icmp requires integer or pointer typed operands");
2966     Value* tmpVal1 = getVal(Ty, $4);
2967     Value* tmpVal2 = getVal(Ty, $6);
2968     $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
2969     $$.S = Unsigned;
2970     delete $3.T;
2971   }
2972   | FCMP FPredicates Types ValueRef ',' ValueRef {
2973     const Type *Ty = $3.T->get();
2974     if (isa<PackedType>(Ty))
2975       error("PackedTypes currently not supported in fcmp instructions");
2976     else if (!Ty->isFloatingPoint())
2977       error("fcmp instruction requires floating point operands");
2978     Value* tmpVal1 = getVal(Ty, $4);
2979     Value* tmpVal2 = getVal(Ty, $6);
2980     $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
2981     $$.S = Unsigned;
2982     delete $3.T;
2983   }
2984   | NOT ResolvedVal {
2985     warning("Use of obsolete 'not' instruction: Replacing with 'xor");
2986     const Type *Ty = $2.V->getType();
2987     Value *Ones = ConstantInt::getAllOnesValue(Ty);
2988     if (Ones == 0)
2989       error("Expected integral type for not instruction");
2990     $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
2991     if ($$.I == 0)
2992       error("Could not create a xor instruction");
2993     $$.S = $2.S
2994   }
2995   | ShiftOps ResolvedVal ',' ResolvedVal {
2996     if (!$4.V->getType()->isInteger() ||
2997         cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
2998       error("Shift amount must be int8");
2999     if (!$2.V->getType()->isInteger())
3000       error("Shift constant expression requires integer operand");
3001     $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3002     $$.S = $2.S;
3003   }
3004   | CastOps ResolvedVal TO Types {
3005     const Type *DstTy = $4.T->get();
3006     if (!DstTy->isFirstClassType())
3007       error("cast instruction to a non-primitive type: '" +
3008             DstTy->getDescription() + "'");
3009     $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3010     $$.S = $4.S;
3011     delete $4.T;
3012   }
3013   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3014     if (!$2.V->getType()->isInteger() ||
3015         cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3016       error("select condition must be bool");
3017     if ($4.V->getType() != $6.V->getType())
3018       error("select value types should match");
3019     $$.I = new SelectInst($2.V, $4.V, $6.V);
3020     $$.S = $2.S;
3021   }
3022   | VAARG ResolvedVal ',' Types {
3023     const Type *Ty = $4.T->get();
3024     NewVarArgs = true;
3025     $$.I = new VAArgInst($2.V, Ty);
3026     $$.S = $4.S;
3027     delete $4.T;
3028   }
3029   | VAARG_old ResolvedVal ',' Types {
3030     const Type* ArgTy = $2.V->getType();
3031     const Type* DstTy = $4.T->get();
3032     ObsoleteVarArgs = true;
3033     Function* NF = cast<Function>(CurModule.CurrentModule->
3034       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3035
3036     //b = vaarg a, t -> 
3037     //foo = alloca 1 of t
3038     //bar = vacopy a 
3039     //store bar -> foo
3040     //b = vaarg foo, t
3041     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3042     CurBB->getInstList().push_back(foo);
3043     CallInst* bar = new CallInst(NF, $2.V);
3044     CurBB->getInstList().push_back(bar);
3045     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3046     $$.I = new VAArgInst(foo, DstTy);
3047     $$.S = $4.S;
3048     delete $4.T;
3049   }
3050   | VANEXT_old ResolvedVal ',' Types {
3051     const Type* ArgTy = $2.V->getType();
3052     const Type* DstTy = $4.T->get();
3053     ObsoleteVarArgs = true;
3054     Function* NF = cast<Function>(CurModule.CurrentModule->
3055       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3056
3057     //b = vanext a, t ->
3058     //foo = alloca 1 of t
3059     //bar = vacopy a
3060     //store bar -> foo
3061     //tmp = vaarg foo, t
3062     //b = load foo
3063     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3064     CurBB->getInstList().push_back(foo);
3065     CallInst* bar = new CallInst(NF, $2.V);
3066     CurBB->getInstList().push_back(bar);
3067     CurBB->getInstList().push_back(new StoreInst(bar, foo));
3068     Instruction* tmp = new VAArgInst(foo, DstTy);
3069     CurBB->getInstList().push_back(tmp);
3070     $$.I = new LoadInst(foo);
3071     $$.S = $4.S;
3072     delete $4.T;
3073   }
3074   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3075     if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3076       error("Invalid extractelement operands");
3077     $$.I = new ExtractElementInst($2.V, $4.V);
3078     $$.S = $2.S;
3079   }
3080   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3081     if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3082       error("Invalid insertelement operands");
3083     $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3084     $$.S = $2.S;
3085   }
3086   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3087     if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3088       error("Invalid shufflevector operands");
3089     $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3090     $$.S = $2.S;
3091   }
3092   | PHI_TOK PHIList {
3093     const Type *Ty = $2.P->front().first->getType();
3094     if (!Ty->isFirstClassType())
3095       error("PHI node operands must be of first class type");
3096     PHINode *PHI = new PHINode(Ty);
3097     PHI->reserveOperandSpace($2.P->size());
3098     while ($2.P->begin() != $2.P->end()) {
3099       if ($2.P->front().first->getType() != Ty) 
3100         error("All elements of a PHI node must be of the same type");
3101       PHI->addIncoming($2.P->front().first, $2.P->front().second);
3102       $2.P->pop_front();
3103     }
3104     $$.I = PHI;
3105     $$.S = $2.S;
3106     delete $2.P;  // Free the list...
3107   }
3108   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
3109
3110     // Handle the short call syntax
3111     const PointerType *PFTy;
3112     const FunctionType *FTy;
3113     if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3114         !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3115       // Pull out the types of all of the arguments...
3116       std::vector<const Type*> ParamTypes;
3117       if ($6) {
3118         for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3119              I != E; ++I)
3120           ParamTypes.push_back((*I).V->getType());
3121       }
3122
3123       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3124       if (isVarArg) ParamTypes.pop_back();
3125
3126       const Type *RetTy = $3.T->get();
3127       if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3128         error("Functions cannot return aggregate types");
3129
3130       FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3131       PFTy = PointerType::get(FTy);
3132     }
3133
3134     // First upgrade any intrinsic calls.
3135     std::vector<Value*> Args;
3136     if ($6)
3137       for (unsigned i = 0, e = $6->size(); i < e; ++i) 
3138         Args.push_back((*$6)[i].V);
3139     Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3140
3141     // If we got an upgraded intrinsic
3142     if (Inst) {
3143       $$.I = Inst;
3144       $$.S = Signless;
3145     } else {
3146       // Get the function we're calling
3147       Value *V = getVal(PFTy, $4);
3148
3149       // Check the argument values match
3150       if (!$6) {                                   // Has no arguments?
3151         // Make sure no arguments is a good thing!
3152         if (FTy->getNumParams() != 0)
3153           error("No arguments passed to a function that expects arguments");
3154       } else {                                     // Has arguments?
3155         // Loop through FunctionType's arguments and ensure they are specified
3156         // correctly!
3157         //
3158         FunctionType::param_iterator I = FTy->param_begin();
3159         FunctionType::param_iterator E = FTy->param_end();
3160         std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3161
3162         for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3163           if ((*ArgI).V->getType() != *I)
3164             error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3165                   (*I)->getDescription() + "'");
3166
3167         if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3168           error("Invalid number of parameters detected");
3169       }
3170
3171       // Create the call instruction
3172       CallInst *CI = new CallInst(V, Args);
3173       CI->setTailCall($1);
3174       CI->setCallingConv($2);
3175       $$.I = CI;
3176       $$.S = $3.S;
3177     }
3178     delete $3.T;
3179     delete $6;
3180   }
3181   | MemoryInst {
3182     $$ = $1;
3183   }
3184   ;
3185
3186
3187 // IndexList - List of indices for GEP based instructions...
3188 IndexList 
3189   : ',' ValueRefList { $$ = $2; } 
3190   | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3191   ;
3192
3193 OptVolatile 
3194   : VOLATILE { $$ = true; }
3195   | /* empty */ { $$ = false; }
3196   ;
3197
3198 MemoryInst 
3199   : MALLOC Types OptCAlign {
3200     const Type *Ty = $2.T->get();
3201     $$.S = $2.S;
3202     $$.I = new MallocInst(Ty, 0, $3);
3203     delete $2.T;
3204   }
3205   | MALLOC Types ',' UINT ValueRef OptCAlign {
3206     const Type *Ty = $2.T->get();
3207     $$.S = $2.S;
3208     $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3209     delete $2.T;
3210   }
3211   | ALLOCA Types OptCAlign {
3212     const Type *Ty = $2.T->get();
3213     $$.S = $2.S;
3214     $$.I = new AllocaInst(Ty, 0, $3);
3215     delete $2.T;
3216   }
3217   | ALLOCA Types ',' UINT ValueRef OptCAlign {
3218     const Type *Ty = $2.T->get();
3219     $$.S = $2.S;
3220     $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3221     delete $2.T;
3222   }
3223   | FREE ResolvedVal {
3224     const Type *PTy = $2.V->getType();
3225     if (!isa<PointerType>(PTy))
3226       error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3227     $$.I = new FreeInst($2.V);
3228     $$.S = Signless;
3229   }
3230   | OptVolatile LOAD Types ValueRef {
3231     const Type* Ty = $3.T->get();
3232     $$.S = $3.S;
3233     if (!isa<PointerType>(Ty))
3234       error("Can't load from nonpointer type: " + Ty->getDescription());
3235     if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3236       error("Can't load from pointer of non-first-class type: " +
3237                      Ty->getDescription());
3238     Value* tmpVal = getVal(Ty, $4);
3239     $$.I = new LoadInst(tmpVal, "", $1);
3240     delete $3.T;
3241   }
3242   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3243     const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3244     if (!PTy)
3245       error("Can't store to a nonpointer type: " + 
3246              $5.T->get()->getDescription());
3247     const Type *ElTy = PTy->getElementType();
3248     if (ElTy != $3.V->getType())
3249       error("Can't store '" + $3.V->getType()->getDescription() +
3250             "' into space of type '" + ElTy->getDescription() + "'");
3251     Value* tmpVal = getVal(PTy, $6);
3252     $$.I = new StoreInst($3.V, tmpVal, $1);
3253     $$.S = Signless;
3254     delete $5.T;
3255   }
3256   | GETELEMENTPTR Types ValueRef IndexList {
3257     const Type* Ty = $2.T->get();
3258     if (!isa<PointerType>(Ty))
3259       error("getelementptr insn requires pointer operand");
3260
3261     std::vector<Value*> VIndices;
3262     upgradeGEPIndices(Ty, $4, VIndices);
3263
3264     Value* tmpVal = getVal(Ty, $3);
3265     $$.I = new GetElementPtrInst(tmpVal, VIndices);
3266     $$.S = Signless;
3267     delete $2.T;
3268     delete $4;
3269   };
3270
3271
3272 %%
3273
3274 int yyerror(const char *ErrorMsg) {
3275   std::string where 
3276     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3277                   + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3278   std::string errMsg = where + "error: " + std::string(ErrorMsg);
3279   if (yychar != YYEMPTY && yychar != 0)
3280     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3281               "'.";
3282   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3283   std::cout << "llvm-upgrade: parse failed.\n";
3284   exit(1);
3285 }
3286
3287 void warning(const std::string& ErrorMsg) {
3288   std::string where 
3289     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3290                   + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3291   std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3292   if (yychar != YYEMPTY && yychar != 0)
3293     errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3294               "'.";
3295   std::cerr << "llvm-upgrade: " << errMsg << '\n';
3296 }
3297
3298 void error(const std::string& ErrorMsg, int LineNo) {
3299   if (LineNo == -1) LineNo = Upgradelineno;
3300   Upgradelineno = LineNo;
3301   yyerror(ErrorMsg.c_str());
3302 }
3303