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