b5a3dcd46cda5b997131f967283bb3674e5224a3
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the bison parser for LLVM assembly languages files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 %{
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <algorithm>
24 #include <iostream>
25 #include <list>
26 #include <utility>
27
28 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
29 int yylex();                       // declaration" of xxx warnings.
30 int yyparse();
31
32 namespace llvm {
33   std::string CurFilename;
34 }
35 using namespace llvm;
36
37 static Module *ParserResult;
38
39 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
40 // relating to upreferences in the input stream.
41 //
42 //#define DEBUG_UPREFS 1
43 #ifdef DEBUG_UPREFS
44 #define UR_OUT(X) std::cerr << X
45 #else
46 #define UR_OUT(X)
47 #endif
48
49 #define YYERROR_VERBOSE 1
50
51 static bool ObsoleteVarArgs;
52 static bool NewVarArgs;
53 static BasicBlock *CurBB;
54 static GlobalVariable *CurGV;
55
56
57 // This contains info used when building the body of a function.  It is
58 // destroyed when the function is completed.
59 //
60 typedef std::vector<Value *> ValueList;           // Numbered defs
61 static void 
62 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
63                    std::map<const Type *,ValueList> *FutureLateResolvers = 0);
64
65 static struct PerModuleInfo {
66   Module *CurrentModule;
67   std::map<const Type *, ValueList> Values; // Module level numbered definitions
68   std::map<const Type *,ValueList> LateResolveValues;
69   std::vector<PATypeHolder>    Types;
70   std::map<ValID, PATypeHolder> LateResolveTypes;
71
72   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
73   /// how they were referenced and one which line of the input they came from so
74   /// that we can resolve them later and print error messages as appropriate.
75   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
76
77   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
78   // references to global values.  Global values may be referenced before they
79   // are defined, and if so, the temporary object that they represent is held
80   // here.  This is used for forward references of GlobalValues.
81   //
82   typedef std::map<std::pair<const PointerType *,
83                              ValID>, GlobalValue*> GlobalRefsType;
84   GlobalRefsType GlobalRefs;
85
86   void ModuleDone() {
87     // If we could not resolve some functions at function compilation time
88     // (calls to functions before they are defined), resolve them now...  Types
89     // are resolved when the constant pool has been completely parsed.
90     //
91     ResolveDefinitions(LateResolveValues);
92
93     // Check to make sure that all global value forward references have been
94     // resolved!
95     //
96     if (!GlobalRefs.empty()) {
97       std::string UndefinedReferences = "Unresolved global references exist:\n";
98
99       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
100            I != E; ++I) {
101         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
102                                I->first.second.getName() + "\n";
103       }
104       ThrowException(UndefinedReferences);
105     }
106
107     Values.clear();         // Clear out function local definitions
108     Types.clear();
109     CurrentModule = 0;
110   }
111
112
113   // GetForwardRefForGlobal - Check to see if there is a forward reference
114   // for this global.  If so, remove it from the GlobalRefs map and return it.
115   // If not, just return null.
116   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
117     // Check to see if there is a forward reference to this global variable...
118     // if there is, eliminate it and patch the reference to use the new def'n.
119     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
120     GlobalValue *Ret = 0;
121     if (I != GlobalRefs.end()) {
122       Ret = I->second;
123       GlobalRefs.erase(I);
124     }
125     return Ret;
126   }
127 } CurModule;
128
129 static struct PerFunctionInfo {
130   Function *CurrentFunction;     // Pointer to current function being created
131
132   std::map<const Type*, ValueList> Values;   // Keep track of #'d definitions
133   std::map<const Type*, ValueList> LateResolveValues;
134   bool isDeclare;                // Is this function a forward declararation?
135
136   /// BBForwardRefs - When we see forward references to basic blocks, keep
137   /// track of them here.
138   std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
139   std::vector<BasicBlock*> NumberedBlocks;
140   unsigned NextBBNum;
141
142   inline PerFunctionInfo() {
143     CurrentFunction = 0;
144     isDeclare = false;
145   }
146
147   inline void FunctionStart(Function *M) {
148     CurrentFunction = M;
149     NextBBNum = 0;
150   }
151
152   void FunctionDone() {
153     NumberedBlocks.clear();
154
155     // Any forward referenced blocks left?
156     if (!BBForwardRefs.empty())
157       ThrowException("Undefined reference to label " +
158                      BBForwardRefs.begin()->first->getName());
159
160     // Resolve all forward references now.
161     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
162
163     Values.clear();         // Clear out function local definitions
164     CurrentFunction = 0;
165     isDeclare = false;
166   }
167 } CurFun;  // Info for the current function...
168
169 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
170
171
172 //===----------------------------------------------------------------------===//
173 //               Code to handle definitions of all the types
174 //===----------------------------------------------------------------------===//
175
176 static int InsertValue(Value *V,
177                   std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
178   if (V->hasName()) return -1;           // Is this a numbered definition?
179
180   // Yes, insert the value into the value table...
181   ValueList &List = ValueTab[V->getType()];
182   List.push_back(V);
183   return List.size()-1;
184 }
185
186 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
187   switch (D.Type) {
188   case ValID::NumberVal:               // Is it a numbered definition?
189     // Module constants occupy the lowest numbered slots...
190     if ((unsigned)D.Num < CurModule.Types.size())
191       return CurModule.Types[(unsigned)D.Num];
192     break;
193   case ValID::NameVal:                 // Is it a named definition?
194     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
195       D.destroy();  // Free old strdup'd memory...
196       return N;
197     }
198     break;
199   default:
200     ThrowException("Internal parser error: Invalid symbol type reference!");
201   }
202
203   // If we reached here, we referenced either a symbol that we don't know about
204   // or an id number that hasn't been read yet.  We may be referencing something
205   // forward, so just create an entry to be resolved later and get to it...
206   //
207   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
208
209
210   if (inFunctionScope()) {
211     if (D.Type == ValID::NameVal)
212       ThrowException("Reference to an undefined type: '" + D.getName() + "'");
213     else
214       ThrowException("Reference to an undefined type: #" + itostr(D.Num));
215   }
216
217   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
218   if (I != CurModule.LateResolveTypes.end())
219     return I->second;
220
221   Type *Typ = OpaqueType::get();
222   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
223   return Typ;
224  }
225
226 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
227   SymbolTable &SymTab =
228     inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
229                         CurModule.CurrentModule->getSymbolTable();
230   return SymTab.lookup(Ty, Name);
231 }
232
233 // getValNonImprovising - Look up the value specified by the provided type and
234 // the provided ValID.  If the value exists and has already been defined, return
235 // it.  Otherwise return null.
236 //
237 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
238   if (isa<FunctionType>(Ty))
239     ThrowException("Functions are not values and "
240                    "must be referenced as pointers");
241
242   switch (D.Type) {
243   case ValID::NumberVal: {                 // Is it a numbered definition?
244     unsigned Num = (unsigned)D.Num;
245
246     // Module constants occupy the lowest numbered slots...
247     std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
248     if (VI != CurModule.Values.end()) {
249       if (Num < VI->second.size())
250         return VI->second[Num];
251       Num -= VI->second.size();
252     }
253
254     // Make sure that our type is within bounds
255     VI = CurFun.Values.find(Ty);
256     if (VI == CurFun.Values.end()) return 0;
257
258     // Check that the number is within bounds...
259     if (VI->second.size() <= Num) return 0;
260
261     return VI->second[Num];
262   }
263
264   case ValID::NameVal: {                // Is it a named definition?
265     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
266     if (N == 0) return 0;
267
268     D.destroy();  // Free old strdup'd memory...
269     return N;
270   }
271
272   // Check to make sure that "Ty" is an integral type, and that our
273   // value will fit into the specified type...
274   case ValID::ConstSIntVal:    // Is it a constant pool reference??
275     if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
276       ThrowException("Signed integral constant '" +
277                      itostr(D.ConstPool64) + "' is invalid for type '" +
278                      Ty->getDescription() + "'!");
279     return ConstantSInt::get(Ty, D.ConstPool64);
280
281   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
282     if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
283       if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
284         ThrowException("Integral constant '" + utostr(D.UConstPool64) +
285                        "' is invalid or out of range!");
286       } else {     // This is really a signed reference.  Transmogrify.
287         return ConstantSInt::get(Ty, D.ConstPool64);
288       }
289     } else {
290       return ConstantUInt::get(Ty, D.UConstPool64);
291     }
292
293   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
294     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
295       ThrowException("FP constant invalid for type!!");
296     return ConstantFP::get(Ty, D.ConstPoolFP);
297
298   case ValID::ConstNullVal:      // Is it a null value?
299     if (!isa<PointerType>(Ty))
300       ThrowException("Cannot create a a non pointer null!");
301     return ConstantPointerNull::get(cast<PointerType>(Ty));
302
303   case ValID::ConstUndefVal:      // Is it an undef value?
304     return UndefValue::get(Ty);
305
306   case ValID::ConstZeroVal:      // Is it a zero value?
307     return Constant::getNullValue(Ty);
308     
309   case ValID::ConstantVal:       // Fully resolved constant?
310     if (D.ConstantValue->getType() != Ty)
311       ThrowException("Constant expression type different from required type!");
312     return D.ConstantValue;
313
314   default:
315     assert(0 && "Unhandled case!");
316     return 0;
317   }   // End of switch
318
319   assert(0 && "Unhandled case!");
320   return 0;
321 }
322
323 // getVal - This function is identical to getValNonImprovising, except that if a
324 // value is not already defined, it "improvises" by creating a placeholder var
325 // that looks and acts just like the requested variable.  When the value is
326 // defined later, all uses of the placeholder variable are replaced with the
327 // real thing.
328 //
329 static Value *getVal(const Type *Ty, const ValID &ID) {
330   if (Ty == Type::LabelTy)
331     ThrowException("Cannot use a basic block here");
332
333   // See if the value has already been defined.
334   Value *V = getValNonImprovising(Ty, ID);
335   if (V) return V;
336
337   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
338     ThrowException("Invalid use of a composite type!");
339
340   // If we reached here, we referenced either a symbol that we don't know about
341   // or an id number that hasn't been read yet.  We may be referencing something
342   // forward, so just create an entry to be resolved later and get to it...
343   //
344   V = new Argument(Ty);
345
346   // Remember where this forward reference came from.  FIXME, shouldn't we try
347   // to recycle these things??
348   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
349                                                                llvmAsmlineno)));
350
351   if (inFunctionScope())
352     InsertValue(V, CurFun.LateResolveValues);
353   else
354     InsertValue(V, CurModule.LateResolveValues);
355   return V;
356 }
357
358 /// getBBVal - This is used for two purposes:
359 ///  * If isDefinition is true, a new basic block with the specified ID is being
360 ///    defined.
361 ///  * If isDefinition is true, this is a reference to a basic block, which may
362 ///    or may not be a forward reference.
363 ///
364 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
365   assert(inFunctionScope() && "Can't get basic block at global scope!");
366
367   std::string Name;
368   BasicBlock *BB = 0;
369   switch (ID.Type) {
370   default: ThrowException("Illegal label reference " + ID.getName());
371   case ValID::NumberVal:                // Is it a numbered definition?
372     if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
373       CurFun.NumberedBlocks.resize(ID.Num+1);
374     BB = CurFun.NumberedBlocks[ID.Num];
375     break;
376   case ValID::NameVal:                  // Is it a named definition?
377     Name = ID.Name;
378     if (Value *N = CurFun.CurrentFunction->
379                    getSymbolTable().lookup(Type::LabelTy, Name))
380       BB = cast<BasicBlock>(N);
381     break;
382   }
383
384   // See if the block has already been defined.
385   if (BB) {
386     // If this is the definition of the block, make sure the existing value was
387     // just a forward reference.  If it was a forward reference, there will be
388     // an entry for it in the PlaceHolderInfo map.
389     if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
390       // The existing value was a definition, not a forward reference.
391       ThrowException("Redefinition of label " + ID.getName());
392
393     ID.destroy();                       // Free strdup'd memory.
394     return BB;
395   }
396
397   // Otherwise this block has not been seen before.
398   BB = new BasicBlock("", CurFun.CurrentFunction);
399   if (ID.Type == ValID::NameVal) {
400     BB->setName(ID.Name);
401   } else {
402     CurFun.NumberedBlocks[ID.Num] = BB;
403   }
404
405   // If this is not a definition, keep track of it so we can use it as a forward
406   // reference.
407   if (!isDefinition) {
408     // Remember where this forward reference came from.
409     CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
410   } else {
411     // The forward declaration could have been inserted anywhere in the
412     // function: insert it into the correct place now.
413     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
414     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
415   }
416   ID.destroy();
417   return BB;
418 }
419
420
421 //===----------------------------------------------------------------------===//
422 //              Code to handle forward references in instructions
423 //===----------------------------------------------------------------------===//
424 //
425 // This code handles the late binding needed with statements that reference
426 // values not defined yet... for example, a forward branch, or the PHI node for
427 // a loop body.
428 //
429 // This keeps a table (CurFun.LateResolveValues) of all such forward references
430 // and back patchs after we are done.
431 //
432
433 // ResolveDefinitions - If we could not resolve some defs at parsing
434 // time (forward branches, phi functions for loops, etc...) resolve the
435 // defs now...
436 //
437 static void 
438 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
439                    std::map<const Type*,ValueList> *FutureLateResolvers) {
440   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
441   for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
442          E = LateResolvers.end(); LRI != E; ++LRI) {
443     ValueList &List = LRI->second;
444     while (!List.empty()) {
445       Value *V = List.back();
446       List.pop_back();
447
448       std::map<Value*, std::pair<ValID, int> >::iterator PHI =
449         CurModule.PlaceHolderInfo.find(V);
450       assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
451
452       ValID &DID = PHI->second.first;
453
454       Value *TheRealValue = getValNonImprovising(LRI->first, DID);
455       if (TheRealValue) {
456         V->replaceAllUsesWith(TheRealValue);
457         delete V;
458         CurModule.PlaceHolderInfo.erase(PHI);
459       } else if (FutureLateResolvers) {
460         // Functions have their unresolved items forwarded to the module late
461         // resolver table
462         InsertValue(V, *FutureLateResolvers);
463       } else {
464         if (DID.Type == ValID::NameVal)
465           ThrowException("Reference to an invalid definition: '" +DID.getName()+
466                          "' of type '" + V->getType()->getDescription() + "'",
467                          PHI->second.second);
468         else
469           ThrowException("Reference to an invalid definition: #" +
470                          itostr(DID.Num) + " of type '" +
471                          V->getType()->getDescription() + "'",
472                          PHI->second.second);
473       }
474     }
475   }
476
477   LateResolvers.clear();
478 }
479
480 // ResolveTypeTo - A brand new type was just declared.  This means that (if
481 // name is not null) things referencing Name can be resolved.  Otherwise, things
482 // refering to the number can be resolved.  Do this now.
483 //
484 static void ResolveTypeTo(char *Name, const Type *ToTy) {
485   ValID D;
486   if (Name) D = ValID::create(Name);
487   else      D = ValID::create((int)CurModule.Types.size());
488
489   std::map<ValID, PATypeHolder>::iterator I =
490     CurModule.LateResolveTypes.find(D);
491   if (I != CurModule.LateResolveTypes.end()) {
492     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
493     CurModule.LateResolveTypes.erase(I);
494   }
495 }
496
497 // setValueName - Set the specified value to the name given.  The name may be
498 // null potentially, in which case this is a noop.  The string passed in is
499 // assumed to be a malloc'd string buffer, and is free'd by this function.
500 //
501 static void setValueName(Value *V, char *NameStr) {
502   if (NameStr) {
503     std::string Name(NameStr);      // Copy string
504     free(NameStr);                  // Free old string
505
506     if (V->getType() == Type::VoidTy)
507       ThrowException("Can't assign name '" + Name+"' to value with void type!");
508
509     assert(inFunctionScope() && "Must be in function scope!");
510     SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
511     if (ST.lookup(V->getType(), Name))
512       ThrowException("Redefinition of value named '" + Name + "' in the '" +
513                      V->getType()->getDescription() + "' type plane!");
514
515     // Set the name.
516     V->setName(Name);
517   }
518 }
519
520 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
521 /// this is a declaration, otherwise it is a definition.
522 static GlobalVariable *
523 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
524                     bool isConstantGlobal, const Type *Ty,
525                     Constant *Initializer) {
526   if (isa<FunctionType>(Ty))
527     ThrowException("Cannot declare global vars of function type!");
528
529   const PointerType *PTy = PointerType::get(Ty);
530
531   std::string Name;
532   if (NameStr) {
533     Name = NameStr;      // Copy string
534     free(NameStr);       // Free old string
535   }
536
537   // See if this global value was forward referenced.  If so, recycle the
538   // object.
539   ValID ID;
540   if (!Name.empty()) {
541     ID = ValID::create((char*)Name.c_str());
542   } else {
543     ID = ValID::create((int)CurModule.Values[PTy].size());
544   }
545
546   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
547     // Move the global to the end of the list, from whereever it was
548     // previously inserted.
549     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
550     CurModule.CurrentModule->getGlobalList().remove(GV);
551     CurModule.CurrentModule->getGlobalList().push_back(GV);
552     GV->setInitializer(Initializer);
553     GV->setLinkage(Linkage);
554     GV->setConstant(isConstantGlobal);
555     InsertValue(GV, CurModule.Values);
556     return GV;
557   }
558
559   // If this global has a name, check to see if there is already a definition
560   // of this global in the module.  If so, merge as appropriate.  Note that
561   // this is really just a hack around problems in the CFE.  :(
562   if (!Name.empty()) {
563     // We are a simple redefinition of a value, check to see if it is defined
564     // the same as the old one.
565     if (GlobalVariable *EGV =
566                 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
567       // We are allowed to redefine a global variable in two circumstances:
568       // 1. If at least one of the globals is uninitialized or
569       // 2. If both initializers have the same value.
570       //
571       if (!EGV->hasInitializer() || !Initializer ||
572           EGV->getInitializer() == Initializer) {
573
574         // Make sure the existing global version gets the initializer!  Make
575         // sure that it also gets marked const if the new version is.
576         if (Initializer && !EGV->hasInitializer())
577           EGV->setInitializer(Initializer);
578         if (isConstantGlobal)
579           EGV->setConstant(true);
580         EGV->setLinkage(Linkage);
581         return EGV;
582       }
583
584       ThrowException("Redefinition of global variable named '" + Name +
585                      "' in the '" + Ty->getDescription() + "' type plane!");
586     }
587   }
588
589   // Otherwise there is no existing GV to use, create one now.
590   GlobalVariable *GV =
591     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
592                        CurModule.CurrentModule);
593   InsertValue(GV, CurModule.Values);
594   return GV;
595 }
596
597 // setTypeName - Set the specified type to the name given.  The name may be
598 // null potentially, in which case this is a noop.  The string passed in is
599 // assumed to be a malloc'd string buffer, and is freed by this function.
600 //
601 // This function returns true if the type has already been defined, but is
602 // allowed to be redefined in the specified context.  If the name is a new name
603 // for the type plane, it is inserted and false is returned.
604 static bool setTypeName(const Type *T, char *NameStr) {
605   assert(!inFunctionScope() && "Can't give types function-local names!");
606   if (NameStr == 0) return false;
607  
608   std::string Name(NameStr);      // Copy string
609   free(NameStr);                  // Free old string
610
611   // We don't allow assigning names to void type
612   if (T == Type::VoidTy)
613     ThrowException("Can't assign name '" + Name + "' to the void type!");
614
615   // Set the type name, checking for conflicts as we do so.
616   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
617
618   if (AlreadyExists) {   // Inserting a name that is already defined???
619     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
620     assert(Existing && "Conflict but no matching type?");
621
622     // There is only one case where this is allowed: when we are refining an
623     // opaque type.  In this case, Existing will be an opaque type.
624     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
625       // We ARE replacing an opaque type!
626       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
627       return true;
628     }
629
630     // Otherwise, this is an attempt to redefine a type. That's okay if
631     // the redefinition is identical to the original. This will be so if
632     // Existing and T point to the same Type object. In this one case we
633     // allow the equivalent redefinition.
634     if (Existing == T) return true;  // Yes, it's equal.
635
636     // Any other kind of (non-equivalent) redefinition is an error.
637     ThrowException("Redefinition of type named '" + Name + "' in the '" +
638                    T->getDescription() + "' type plane!");
639   }
640
641   return false;
642 }
643
644 //===----------------------------------------------------------------------===//
645 // Code for handling upreferences in type names...
646 //
647
648 // TypeContains - Returns true if Ty directly contains E in it.
649 //
650 static bool TypeContains(const Type *Ty, const Type *E) {
651   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
652                    E) != Ty->subtype_end();
653 }
654
655 namespace {
656   struct UpRefRecord {
657     // NestingLevel - The number of nesting levels that need to be popped before
658     // this type is resolved.
659     unsigned NestingLevel;
660
661     // LastContainedTy - This is the type at the current binding level for the
662     // type.  Every time we reduce the nesting level, this gets updated.
663     const Type *LastContainedTy;
664
665     // UpRefTy - This is the actual opaque type that the upreference is
666     // represented with.
667     OpaqueType *UpRefTy;
668
669     UpRefRecord(unsigned NL, OpaqueType *URTy)
670       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
671   };
672 }
673
674 // UpRefs - A list of the outstanding upreferences that need to be resolved.
675 static std::vector<UpRefRecord> UpRefs;
676
677 /// HandleUpRefs - Every time we finish a new layer of types, this function is
678 /// called.  It loops through the UpRefs vector, which is a list of the
679 /// currently active types.  For each type, if the up reference is contained in
680 /// the newly completed type, we decrement the level count.  When the level
681 /// count reaches zero, the upreferenced type is the type that is passed in:
682 /// thus we can complete the cycle.
683 ///
684 static PATypeHolder HandleUpRefs(const Type *ty) {
685   if (!ty->isAbstract()) return ty;
686   PATypeHolder Ty(ty);
687   UR_OUT("Type '" << Ty->getDescription() <<
688          "' newly formed.  Resolving upreferences.\n" <<
689          UpRefs.size() << " upreferences active!\n");
690
691   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
692   // to zero), we resolve them all together before we resolve them to Ty.  At
693   // the end of the loop, if there is anything to resolve to Ty, it will be in
694   // this variable.
695   OpaqueType *TypeToResolve = 0;
696
697   for (unsigned i = 0; i != UpRefs.size(); ++i) {
698     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
699            << UpRefs[i].second->getDescription() << ") = "
700            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
701     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
702       // Decrement level of upreference
703       unsigned Level = --UpRefs[i].NestingLevel;
704       UpRefs[i].LastContainedTy = Ty;
705       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
706       if (Level == 0) {                     // Upreference should be resolved!
707         if (!TypeToResolve) {
708           TypeToResolve = UpRefs[i].UpRefTy;
709         } else {
710           UR_OUT("  * Resolving upreference for "
711                  << UpRefs[i].second->getDescription() << "\n";
712                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
713           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
714           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
715                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
716         }
717         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
718         --i;                                // Do not skip the next element...
719       }
720     }
721   }
722
723   if (TypeToResolve) {
724     UR_OUT("  * Resolving upreference for "
725            << UpRefs[i].second->getDescription() << "\n";
726            std::string OldName = TypeToResolve->getDescription());
727     TypeToResolve->refineAbstractTypeTo(Ty);
728   }
729
730   return Ty;
731 }
732
733
734 // common code from the two 'RunVMAsmParser' functions
735  static Module * RunParser(Module * M) {
736
737   llvmAsmlineno = 1;      // Reset the current line number...
738   ObsoleteVarArgs = false;
739   NewVarArgs = false;
740
741   CurModule.CurrentModule = M;
742   yyparse();       // Parse the file, potentially throwing exception
743
744   Module *Result = ParserResult;
745   ParserResult = 0;
746
747   //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
748   {
749     Function* F;
750     if ((F = Result->getNamedFunction("llvm.va_start"))
751         && F->getFunctionType()->getNumParams() == 0)
752       ObsoleteVarArgs = true;
753     if((F = Result->getNamedFunction("llvm.va_copy"))
754        && F->getFunctionType()->getNumParams() == 1)
755       ObsoleteVarArgs = true;
756   }
757
758   if (ObsoleteVarArgs && NewVarArgs)
759     ThrowException("This file is corrupt: it uses both new and old style varargs");
760
761   if(ObsoleteVarArgs) {
762     if(Function* F = Result->getNamedFunction("llvm.va_start")) {
763       if (F->arg_size() != 0)
764         ThrowException("Obsolete va_start takes 0 argument!");
765       
766       //foo = va_start()
767       // ->
768       //bar = alloca typeof(foo)
769       //va_start(bar)
770       //foo = load bar
771
772       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
773       const Type* ArgTy = F->getFunctionType()->getReturnType();
774       const Type* ArgTyPtr = PointerType::get(ArgTy);
775       Function* NF = Result->getOrInsertFunction("llvm.va_start", 
776                                                  RetTy, ArgTyPtr, (Type *)0);
777
778       while (!F->use_empty()) {
779         CallInst* CI = cast<CallInst>(F->use_back());
780         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
781         new CallInst(NF, bar, "", CI);
782         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
783         CI->replaceAllUsesWith(foo);
784         CI->getParent()->getInstList().erase(CI);
785       }
786       Result->getFunctionList().erase(F);
787     }
788     
789     if(Function* F = Result->getNamedFunction("llvm.va_end")) {
790       if(F->arg_size() != 1)
791         ThrowException("Obsolete va_end takes 1 argument!");
792
793       //vaend foo
794       // ->
795       //bar = alloca 1 of typeof(foo)
796       //vaend bar
797       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
798       const Type* ArgTy = F->getFunctionType()->getParamType(0);
799       const Type* ArgTyPtr = PointerType::get(ArgTy);
800       Function* NF = Result->getOrInsertFunction("llvm.va_end", 
801                                                  RetTy, ArgTyPtr, (Type *)0);
802
803       while (!F->use_empty()) {
804         CallInst* CI = cast<CallInst>(F->use_back());
805         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
806         new StoreInst(CI->getOperand(1), bar, CI);
807         new CallInst(NF, bar, "", CI);
808         CI->getParent()->getInstList().erase(CI);
809       }
810       Result->getFunctionList().erase(F);
811     }
812
813     if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
814       if(F->arg_size() != 1)
815         ThrowException("Obsolete va_copy takes 1 argument!");
816       //foo = vacopy(bar)
817       // ->
818       //a = alloca 1 of typeof(foo)
819       //b = alloca 1 of typeof(foo)
820       //store bar -> b
821       //vacopy(a, b)
822       //foo = load a
823       
824       const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
825       const Type* ArgTy = F->getFunctionType()->getReturnType();
826       const Type* ArgTyPtr = PointerType::get(ArgTy);
827       Function* NF = Result->getOrInsertFunction("llvm.va_copy", 
828                                                  RetTy, ArgTyPtr, ArgTyPtr,
829                                                  (Type *)0);
830
831       while (!F->use_empty()) {
832         CallInst* CI = cast<CallInst>(F->use_back());
833         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
834         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
835         new StoreInst(CI->getOperand(1), b, CI);
836         new CallInst(NF, a, b, "", CI);
837         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
838         CI->replaceAllUsesWith(foo);
839         CI->getParent()->getInstList().erase(CI);
840       }
841       Result->getFunctionList().erase(F);
842     }
843   }
844
845   return Result;
846
847  }
848
849 //===----------------------------------------------------------------------===//
850 //            RunVMAsmParser - Define an interface to this parser
851 //===----------------------------------------------------------------------===//
852 //
853 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
854   set_scan_file(F);
855
856   CurFilename = Filename;
857   return RunParser(new Module(CurFilename));
858 }
859
860 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
861   set_scan_string(AsmString);
862
863   CurFilename = "from_memory";
864   if (M == NULL) {
865     return RunParser(new Module (CurFilename));
866   } else {
867     return RunParser(M);
868   }
869 }
870
871 %}
872
873 %union {
874   llvm::Module                           *ModuleVal;
875   llvm::Function                         *FunctionVal;
876   std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
877   llvm::BasicBlock                       *BasicBlockVal;
878   llvm::TerminatorInst                   *TermInstVal;
879   llvm::Instruction                      *InstVal;
880   llvm::Constant                         *ConstVal;
881
882   const llvm::Type                       *PrimType;
883   llvm::PATypeHolder                     *TypeVal;
884   llvm::Value                            *ValueVal;
885
886   std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
887   std::vector<llvm::Value*>              *ValueList;
888   std::list<llvm::PATypeHolder>          *TypeList;
889   // Represent the RHS of PHI node
890   std::list<std::pair<llvm::Value*,
891                       llvm::BasicBlock*> > *PHIList;
892   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
893   std::vector<llvm::Constant*>           *ConstVector;
894
895   llvm::GlobalValue::LinkageTypes         Linkage;
896   int64_t                           SInt64Val;
897   uint64_t                          UInt64Val;
898   int                               SIntVal;
899   unsigned                          UIntVal;
900   double                            FPVal;
901   bool                              BoolVal;
902
903   char                             *StrVal;   // This memory is strdup'd!
904   llvm::ValID                             ValIDVal; // strdup'd memory maybe!
905
906   llvm::Instruction::BinaryOps            BinaryOpVal;
907   llvm::Instruction::TermOps              TermOpVal;
908   llvm::Instruction::MemoryOps            MemOpVal;
909   llvm::Instruction::OtherOps             OtherOpVal;
910   llvm::Module::Endianness                Endianness;
911 }
912
913 %type <ModuleVal>     Module FunctionList
914 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
915 %type <BasicBlockVal> BasicBlock InstructionList
916 %type <TermInstVal>   BBTerminatorInst
917 %type <InstVal>       Inst InstVal MemoryInst
918 %type <ConstVal>      ConstVal ConstExpr
919 %type <ConstVector>   ConstVector
920 %type <ArgList>       ArgList ArgListH
921 %type <ArgVal>        ArgVal
922 %type <PHIList>       PHIList
923 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
924 %type <ValueList>     IndexList                   // For GEP derived indices
925 %type <TypeList>      TypeListI ArgTypeListI
926 %type <JumpTable>     JumpTable
927 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
928 %type <BoolVal>       OptVolatile                 // 'volatile' or not
929 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
930 %type <Linkage>       OptLinkage
931 %type <Endianness>    BigOrLittle
932
933 // ValueRef - Unresolved reference to a definition or BB
934 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
935 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
936 // Tokens and types for handling constant integer values
937 //
938 // ESINT64VAL - A negative number within long long range
939 %token <SInt64Val> ESINT64VAL
940
941 // EUINT64VAL - A positive number within uns. long long range
942 %token <UInt64Val> EUINT64VAL
943 %type  <SInt64Val> EINT64VAL
944
945 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
946 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
947 %type   <SIntVal>   INTVAL
948 %token  <FPVal>     FPVAL     // Float or Double constant
949
950 // Built in types...
951 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
952 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
953 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
954 %token <PrimType> FLOAT DOUBLE TYPE LABEL
955
956 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
957 %type  <StrVal> Name OptName OptAssign
958 %type  <UIntVal> OptAlign OptCAlign
959 %type <StrVal> OptSection SectionString
960
961 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
962 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
963 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK  APPENDING
964 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
965 %token DEPLIBS CALL TAIL
966 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
967 %type <UIntVal> OptCallingConv
968
969 // Basic Block Terminating Operators
970 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
971
972 // Binary Operators
973 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
974 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
975 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
976
977 // Memory Instructions
978 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
979
980 // Other Operators
981 %type  <OtherOpVal> ShiftOps
982 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
983 %token VAARG_old VANEXT_old //OBSOLETE
984
985
986 %start Module
987 %%
988
989 // Handle constant integer size restriction and conversion...
990 //
991 INTVAL : SINTVAL;
992 INTVAL : UINTVAL {
993   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
994     ThrowException("Value too large for type!");
995   $$ = (int32_t)$1;
996 };
997
998
999 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
1000 EINT64VAL : EUINT64VAL {
1001   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
1002     ThrowException("Value too large for type!");
1003   $$ = (int64_t)$1;
1004 };
1005
1006 // Operations that are notably excluded from this list include:
1007 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1008 //
1009 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1010 LogicalOps   : AND | OR | XOR;
1011 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1012
1013 ShiftOps  : SHL | SHR;
1014
1015 // These are some types that allow classification if we only want a particular 
1016 // thing... for example, only a signed, unsigned, or integral type.
1017 SIntType :  LONG |  INT |  SHORT | SBYTE;
1018 UIntType : ULONG | UINT | USHORT | UBYTE;
1019 IntType  : SIntType | UIntType;
1020 FPType   : FLOAT | DOUBLE;
1021
1022 // OptAssign - Value producing statements have an optional assignment component
1023 OptAssign : Name '=' {
1024     $$ = $1;
1025   }
1026   | /*empty*/ {
1027     $$ = 0;
1028   };
1029
1030 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
1031              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
1032              WEAK      { $$ = GlobalValue::WeakLinkage; } |
1033              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1034              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1035
1036 OptCallingConv : /*empty*/      { $$ = CallingConv::C; } |
1037                  CCC_TOK        { $$ = CallingConv::C; } |
1038                  FASTCC_TOK     { $$ = CallingConv::Fast; } |
1039                  COLDCC_TOK     { $$ = CallingConv::Cold; } |
1040                  CC_TOK EUINT64VAL {
1041                    if ((unsigned)$2 != $2)
1042                      ThrowException("Calling conv too large!");
1043                    $$ = $2;
1044                  };
1045
1046 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1047 // a comma before it.
1048 OptAlign : /*empty*/        { $$ = 0; } |
1049            ALIGN EUINT64VAL {
1050   $$ = $2;
1051   if ($$ != 0 && !isPowerOf2_32($$))
1052     ThrowException("Alignment must be a power of two!");
1053 };
1054 OptCAlign : /*empty*/            { $$ = 0; } |
1055             ',' ALIGN EUINT64VAL {
1056   $$ = $3;
1057   if ($$ != 0 && !isPowerOf2_32($$))
1058     ThrowException("Alignment must be a power of two!");
1059 };
1060
1061
1062 SectionString : SECTION STRINGCONSTANT {
1063   for (unsigned i = 0, e = strlen($2); i != e; ++i)
1064     if ($2[i] == '"' || $2[i] == '\\')
1065       ThrowException("Invalid character in section name!");
1066   $$ = $2;
1067 };
1068
1069 OptSection : /*empty*/ { $$ = 0; } |
1070              SectionString { $$ = $1; };
1071
1072 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1073 // is set to be the global we are processing.
1074 //
1075 GlobalVarAttributes : /* empty */ {} |
1076                      ',' GlobalVarAttribute GlobalVarAttributes {};
1077 GlobalVarAttribute : SectionString {
1078     CurGV->setSection($1);
1079     free($1);
1080   } 
1081   | ALIGN EUINT64VAL {
1082     if ($2 != 0 && !isPowerOf2_32($2))
1083       ThrowException("Alignment must be a power of two!");
1084     CurGV->setAlignment($2);
1085   };
1086
1087 //===----------------------------------------------------------------------===//
1088 // Types includes all predefined types... except void, because it can only be
1089 // used in specific contexts (function returning void for example).  To have
1090 // access to it, a user must explicitly use TypesV.
1091 //
1092
1093 // TypesV includes all of 'Types', but it also includes the void type.
1094 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
1095 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1096
1097 Types     : UpRTypes {
1098     if (!UpRefs.empty())
1099       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1100     $$ = $1;
1101   };
1102
1103
1104 // Derived types are added later...
1105 //
1106 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
1107 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
1108 UpRTypes : OPAQUE {
1109     $$ = new PATypeHolder(OpaqueType::get());
1110   }
1111   | PrimType {
1112     $$ = new PATypeHolder($1);
1113   };
1114 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
1115   $$ = new PATypeHolder(getTypeVal($1));
1116 };
1117
1118 // Include derived types in the Types production.
1119 //
1120 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
1121     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1122     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1123     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1124     $$ = new PATypeHolder(OT);
1125     UR_OUT("New Upreference!\n");
1126   }
1127   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
1128     std::vector<const Type*> Params;
1129     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1130            E = $3->end(); I != E; ++I)
1131       Params.push_back(*I);
1132     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1133     if (isVarArg) Params.pop_back();
1134
1135     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1136     delete $3;      // Delete the argument list
1137     delete $1;      // Delete the return type handle
1138   }
1139   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
1140     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1141     delete $4;
1142   }
1143   | '<' EUINT64VAL 'x' UpRTypes '>' {          // Packed array type?
1144      const llvm::Type* ElemTy = $4->get();
1145      if ((unsigned)$2 != $2)
1146         ThrowException("Unsigned result not equal to signed result");
1147      if (!ElemTy->isPrimitiveType())
1148         ThrowException("Elemental type of a PackedType must be primitive");
1149      if (!isPowerOf2_32($2))
1150        ThrowException("Vector length should be a power of 2!");
1151      $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1152      delete $4;
1153   }
1154   | '{' TypeListI '}' {                        // Structure type?
1155     std::vector<const Type*> Elements;
1156     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1157            E = $2->end(); I != E; ++I)
1158       Elements.push_back(*I);
1159
1160     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1161     delete $2;
1162   }
1163   | '{' '}' {                                  // Empty structure type?
1164     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1165   }
1166   | UpRTypes '*' {                             // Pointer type?
1167     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1168     delete $1;
1169   };
1170
1171 // TypeList - Used for struct declarations and as a basis for function type 
1172 // declaration type lists
1173 //
1174 TypeListI : UpRTypes {
1175     $$ = new std::list<PATypeHolder>();
1176     $$->push_back(*$1); delete $1;
1177   }
1178   | TypeListI ',' UpRTypes {
1179     ($$=$1)->push_back(*$3); delete $3;
1180   };
1181
1182 // ArgTypeList - List of types for a function type declaration...
1183 ArgTypeListI : TypeListI
1184   | TypeListI ',' DOTDOTDOT {
1185     ($$=$1)->push_back(Type::VoidTy);
1186   }
1187   | DOTDOTDOT {
1188     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1189   }
1190   | /*empty*/ {
1191     $$ = new std::list<PATypeHolder>();
1192   };
1193
1194 // ConstVal - The various declarations that go into the constant pool.  This
1195 // production is used ONLY to represent constants that show up AFTER a 'const',
1196 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1197 // into other expressions (such as integers and constexprs) are handled by the
1198 // ResolvedVal, ValueRef and ConstValueRef productions.
1199 //
1200 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1201     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1202     if (ATy == 0)
1203       ThrowException("Cannot make array constant with type: '" + 
1204                      (*$1)->getDescription() + "'!");
1205     const Type *ETy = ATy->getElementType();
1206     int NumElements = ATy->getNumElements();
1207
1208     // Verify that we have the correct size...
1209     if (NumElements != -1 && NumElements != (int)$3->size())
1210       ThrowException("Type mismatch: constant sized array initialized with " +
1211                      utostr($3->size()) +  " arguments, but has size of " + 
1212                      itostr(NumElements) + "!");
1213
1214     // Verify all elements are correct type!
1215     for (unsigned i = 0; i < $3->size(); i++) {
1216       if (ETy != (*$3)[i]->getType())
1217         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1218                        ETy->getDescription() +"' as required!\nIt is of type '"+
1219                        (*$3)[i]->getType()->getDescription() + "'.");
1220     }
1221
1222     $$ = ConstantArray::get(ATy, *$3);
1223     delete $1; delete $3;
1224   }
1225   | Types '[' ']' {
1226     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1227     if (ATy == 0)
1228       ThrowException("Cannot make array constant with type: '" + 
1229                      (*$1)->getDescription() + "'!");
1230
1231     int NumElements = ATy->getNumElements();
1232     if (NumElements != -1 && NumElements != 0) 
1233       ThrowException("Type mismatch: constant sized array initialized with 0"
1234                      " arguments, but has size of " + itostr(NumElements) +"!");
1235     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1236     delete $1;
1237   }
1238   | Types 'c' STRINGCONSTANT {
1239     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1240     if (ATy == 0)
1241       ThrowException("Cannot make array constant with type: '" + 
1242                      (*$1)->getDescription() + "'!");
1243
1244     int NumElements = ATy->getNumElements();
1245     const Type *ETy = ATy->getElementType();
1246     char *EndStr = UnEscapeLexed($3, true);
1247     if (NumElements != -1 && NumElements != (EndStr-$3))
1248       ThrowException("Can't build string constant of size " + 
1249                      itostr((int)(EndStr-$3)) +
1250                      " when array has size " + itostr(NumElements) + "!");
1251     std::vector<Constant*> Vals;
1252     if (ETy == Type::SByteTy) {
1253       for (char *C = $3; C != EndStr; ++C)
1254         Vals.push_back(ConstantSInt::get(ETy, *C));
1255     } else if (ETy == Type::UByteTy) {
1256       for (char *C = $3; C != EndStr; ++C)
1257         Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1258     } else {
1259       free($3);
1260       ThrowException("Cannot build string arrays of non byte sized elements!");
1261     }
1262     free($3);
1263     $$ = ConstantArray::get(ATy, Vals);
1264     delete $1;
1265   }
1266   | Types '<' ConstVector '>' { // Nonempty unsized arr
1267     const PackedType *PTy = dyn_cast<PackedType>($1->get());
1268     if (PTy == 0)
1269       ThrowException("Cannot make packed constant with type: '" + 
1270                      (*$1)->getDescription() + "'!");
1271     const Type *ETy = PTy->getElementType();
1272     int NumElements = PTy->getNumElements();
1273
1274     // Verify that we have the correct size...
1275     if (NumElements != -1 && NumElements != (int)$3->size())
1276       ThrowException("Type mismatch: constant sized packed initialized with " +
1277                      utostr($3->size()) +  " arguments, but has size of " + 
1278                      itostr(NumElements) + "!");
1279
1280     // Verify all elements are correct type!
1281     for (unsigned i = 0; i < $3->size(); i++) {
1282       if (ETy != (*$3)[i]->getType())
1283         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1284            ETy->getDescription() +"' as required!\nIt is of type '"+
1285            (*$3)[i]->getType()->getDescription() + "'.");
1286     }
1287
1288     $$ = ConstantPacked::get(PTy, *$3);
1289     delete $1; delete $3;
1290   }
1291   | Types '{' ConstVector '}' {
1292     const StructType *STy = dyn_cast<StructType>($1->get());
1293     if (STy == 0)
1294       ThrowException("Cannot make struct constant with type: '" + 
1295                      (*$1)->getDescription() + "'!");
1296
1297     if ($3->size() != STy->getNumContainedTypes())
1298       ThrowException("Illegal number of initializers for structure type!");
1299
1300     // Check to ensure that constants are compatible with the type initializer!
1301     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1302       if ((*$3)[i]->getType() != STy->getElementType(i))
1303         ThrowException("Expected type '" +
1304                        STy->getElementType(i)->getDescription() +
1305                        "' for element #" + utostr(i) +
1306                        " of structure initializer!");
1307
1308     $$ = ConstantStruct::get(STy, *$3);
1309     delete $1; delete $3;
1310   }
1311   | Types '{' '}' {
1312     const StructType *STy = dyn_cast<StructType>($1->get());
1313     if (STy == 0)
1314       ThrowException("Cannot make struct constant with type: '" + 
1315                      (*$1)->getDescription() + "'!");
1316
1317     if (STy->getNumContainedTypes() != 0)
1318       ThrowException("Illegal number of initializers for structure type!");
1319
1320     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1321     delete $1;
1322   }
1323   | Types NULL_TOK {
1324     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1325     if (PTy == 0)
1326       ThrowException("Cannot make null pointer constant with type: '" + 
1327                      (*$1)->getDescription() + "'!");
1328
1329     $$ = ConstantPointerNull::get(PTy);
1330     delete $1;
1331   }
1332   | Types UNDEF {
1333     $$ = UndefValue::get($1->get());
1334     delete $1;
1335   }
1336   | Types SymbolicValueRef {
1337     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1338     if (Ty == 0)
1339       ThrowException("Global const reference must be a pointer type!");
1340
1341     // ConstExprs can exist in the body of a function, thus creating
1342     // GlobalValues whenever they refer to a variable.  Because we are in
1343     // the context of a function, getValNonImprovising will search the functions
1344     // symbol table instead of the module symbol table for the global symbol,
1345     // which throws things all off.  To get around this, we just tell
1346     // getValNonImprovising that we are at global scope here.
1347     //
1348     Function *SavedCurFn = CurFun.CurrentFunction;
1349     CurFun.CurrentFunction = 0;
1350
1351     Value *V = getValNonImprovising(Ty, $2);
1352
1353     CurFun.CurrentFunction = SavedCurFn;
1354
1355     // If this is an initializer for a constant pointer, which is referencing a
1356     // (currently) undefined variable, create a stub now that shall be replaced
1357     // in the future with the right type of variable.
1358     //
1359     if (V == 0) {
1360       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1361       const PointerType *PT = cast<PointerType>(Ty);
1362
1363       // First check to see if the forward references value is already created!
1364       PerModuleInfo::GlobalRefsType::iterator I =
1365         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1366     
1367       if (I != CurModule.GlobalRefs.end()) {
1368         V = I->second;             // Placeholder already exists, use it...
1369         $2.destroy();
1370       } else {
1371         std::string Name;
1372         if ($2.Type == ValID::NameVal) Name = $2.Name;
1373
1374         // Create the forward referenced global.
1375         GlobalValue *GV;
1376         if (const FunctionType *FTy = 
1377                  dyn_cast<FunctionType>(PT->getElementType())) {
1378           GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1379                             CurModule.CurrentModule);
1380         } else {
1381           GV = new GlobalVariable(PT->getElementType(), false,
1382                                   GlobalValue::ExternalLinkage, 0,
1383                                   Name, CurModule.CurrentModule);
1384         }
1385
1386         // Keep track of the fact that we have a forward ref to recycle it
1387         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1388         V = GV;
1389       }
1390     }
1391
1392     $$ = cast<GlobalValue>(V);
1393     delete $1;            // Free the type handle
1394   }
1395   | Types ConstExpr {
1396     if ($1->get() != $2->getType())
1397       ThrowException("Mismatched types for constant expression!");
1398     $$ = $2;
1399     delete $1;
1400   }
1401   | Types ZEROINITIALIZER {
1402     const Type *Ty = $1->get();
1403     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1404       ThrowException("Cannot create a null initialized value of this type!");
1405     $$ = Constant::getNullValue(Ty);
1406     delete $1;
1407   };
1408
1409 ConstVal : SIntType EINT64VAL {      // integral constants
1410     if (!ConstantSInt::isValueValidForType($1, $2))
1411       ThrowException("Constant value doesn't fit in type!");
1412     $$ = ConstantSInt::get($1, $2);
1413   }
1414   | UIntType EUINT64VAL {            // integral constants
1415     if (!ConstantUInt::isValueValidForType($1, $2))
1416       ThrowException("Constant value doesn't fit in type!");
1417     $$ = ConstantUInt::get($1, $2);
1418   }
1419   | BOOL TRUETOK {                      // Boolean constants
1420     $$ = ConstantBool::True;
1421   }
1422   | BOOL FALSETOK {                     // Boolean constants
1423     $$ = ConstantBool::False;
1424   }
1425   | FPType FPVAL {                   // Float & Double constants
1426     if (!ConstantFP::isValueValidForType($1, $2))
1427       ThrowException("Floating point constant invalid for type!!");
1428     $$ = ConstantFP::get($1, $2);
1429   };
1430
1431
1432 ConstExpr: CAST '(' ConstVal TO Types ')' {
1433     if (!$3->getType()->isFirstClassType())
1434       ThrowException("cast constant expression from a non-primitive type: '" +
1435                      $3->getType()->getDescription() + "'!");
1436     if (!$5->get()->isFirstClassType())
1437       ThrowException("cast constant expression to a non-primitive type: '" +
1438                      $5->get()->getDescription() + "'!");
1439     $$ = ConstantExpr::getCast($3, $5->get());
1440     delete $5;
1441   }
1442   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1443     if (!isa<PointerType>($3->getType()))
1444       ThrowException("GetElementPtr requires a pointer operand!");
1445
1446     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
1447     // indices to uint struct indices for compatibility.
1448     generic_gep_type_iterator<std::vector<Value*>::iterator>
1449       GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1450       GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1451     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1452       if (isa<StructType>(*GTI))        // Only change struct indices
1453         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1454           if (CUI->getType() == Type::UByteTy)
1455             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1456
1457     const Type *IdxTy =
1458       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1459     if (!IdxTy)
1460       ThrowException("Index list invalid for constant getelementptr!");
1461
1462     std::vector<Constant*> IdxVec;
1463     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1464       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1465         IdxVec.push_back(C);
1466       else
1467         ThrowException("Indices to constant getelementptr must be constants!");
1468
1469     delete $4;
1470
1471     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1472   }
1473   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1474     if ($3->getType() != Type::BoolTy)
1475       ThrowException("Select condition must be of boolean type!");
1476     if ($5->getType() != $7->getType())
1477       ThrowException("Select operand types must match!");
1478     $$ = ConstantExpr::getSelect($3, $5, $7);
1479   }
1480   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1481     if ($3->getType() != $5->getType())
1482       ThrowException("Binary operator types must match!");
1483     // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1484     // To retain backward compatibility with these early compilers, we emit a
1485     // cast to the appropriate integer type automatically if we are in the
1486     // broken case.  See PR424 for more information.
1487     if (!isa<PointerType>($3->getType())) {
1488       $$ = ConstantExpr::get($1, $3, $5);
1489     } else {
1490       const Type *IntPtrTy = 0;
1491       switch (CurModule.CurrentModule->getPointerSize()) {
1492       case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1493       case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1494       default: ThrowException("invalid pointer binary constant expr!");
1495       }
1496       $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1497                              ConstantExpr::getCast($5, IntPtrTy));
1498       $$ = ConstantExpr::getCast($$, $3->getType());
1499     }
1500   }
1501   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1502     if ($3->getType() != $5->getType())
1503       ThrowException("Logical operator types must match!");
1504     if (!$3->getType()->isIntegral()) {
1505       if (!isa<PackedType>($3->getType()) || 
1506           !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1507         ThrowException("Logical operator requires integral operands!");
1508     }
1509     $$ = ConstantExpr::get($1, $3, $5);
1510   }
1511   | SetCondOps '(' ConstVal ',' ConstVal ')' {
1512     if ($3->getType() != $5->getType())
1513       ThrowException("setcc operand types must match!");
1514     $$ = ConstantExpr::get($1, $3, $5);
1515   }
1516   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1517     if ($5->getType() != Type::UByteTy)
1518       ThrowException("Shift count for shift constant must be unsigned byte!");
1519     if (!$3->getType()->isInteger())
1520       ThrowException("Shift constant expression requires integer operand!");
1521     $$ = ConstantExpr::get($1, $3, $5);
1522   };
1523
1524
1525 // ConstVector - A list of comma separated constants.
1526 ConstVector : ConstVector ',' ConstVal {
1527     ($$ = $1)->push_back($3);
1528   }
1529   | ConstVal {
1530     $$ = new std::vector<Constant*>();
1531     $$->push_back($1);
1532   };
1533
1534
1535 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1536 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1537
1538
1539 //===----------------------------------------------------------------------===//
1540 //                             Rules to match Modules
1541 //===----------------------------------------------------------------------===//
1542
1543 // Module rule: Capture the result of parsing the whole file into a result
1544 // variable...
1545 //
1546 Module : FunctionList {
1547   $$ = ParserResult = $1;
1548   CurModule.ModuleDone();
1549 };
1550
1551 // FunctionList - A list of functions, preceeded by a constant pool.
1552 //
1553 FunctionList : FunctionList Function {
1554     $$ = $1;
1555     CurFun.FunctionDone();
1556   } 
1557   | FunctionList FunctionProto {
1558     $$ = $1;
1559   }
1560   | FunctionList IMPLEMENTATION {
1561     $$ = $1;
1562   }
1563   | ConstPool {
1564     $$ = CurModule.CurrentModule;
1565     // Emit an error if there are any unresolved types left.
1566     if (!CurModule.LateResolveTypes.empty()) {
1567       const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1568       if (DID.Type == ValID::NameVal)
1569         ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1570       else
1571         ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1572     }
1573   };
1574
1575 // ConstPool - Constants with optional names assigned to them.
1576 ConstPool : ConstPool OptAssign TYPE TypesV {
1577     // Eagerly resolve types.  This is not an optimization, this is a
1578     // requirement that is due to the fact that we could have this:
1579     //
1580     // %list = type { %list * }
1581     // %list = type { %list * }    ; repeated type decl
1582     //
1583     // If types are not resolved eagerly, then the two types will not be
1584     // determined to be the same type!
1585     //
1586     ResolveTypeTo($2, *$4);
1587
1588     if (!setTypeName(*$4, $2) && !$2) {
1589       // If this is a named type that is not a redefinition, add it to the slot
1590       // table.
1591       CurModule.Types.push_back(*$4);
1592     }
1593
1594     delete $4;
1595   }
1596   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1597   }
1598   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1599     if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1600     CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1601                                                        } GlobalVarAttributes {
1602     CurGV = 0;
1603   }
1604   | ConstPool OptAssign EXTERNAL GlobalType Types {
1605     CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1606                                              $4, *$5, 0);
1607     delete $5;
1608                                                    } GlobalVarAttributes {
1609     CurGV = 0;
1610   }
1611   | ConstPool TARGET TargetDefinition { 
1612   }
1613   | ConstPool DEPLIBS '=' LibrariesDefinition {
1614   }
1615   | /* empty: end of list */ { 
1616   };
1617
1618
1619
1620 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1621 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1622
1623 TargetDefinition : ENDIAN '=' BigOrLittle {
1624     CurModule.CurrentModule->setEndianness($3);
1625   }
1626   | POINTERSIZE '=' EUINT64VAL {
1627     if ($3 == 32)
1628       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1629     else if ($3 == 64)
1630       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1631     else
1632       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1633   }
1634   | TRIPLE '=' STRINGCONSTANT {
1635     CurModule.CurrentModule->setTargetTriple($3);
1636     free($3);
1637   };
1638
1639 LibrariesDefinition : '[' LibList ']';
1640
1641 LibList : LibList ',' STRINGCONSTANT {
1642           CurModule.CurrentModule->addLibrary($3);
1643           free($3);
1644         }
1645         | STRINGCONSTANT {
1646           CurModule.CurrentModule->addLibrary($1);
1647           free($1);
1648         }
1649         | /* empty: end of list */ {
1650         }
1651         ;
1652
1653 //===----------------------------------------------------------------------===//
1654 //                       Rules to match Function Headers
1655 //===----------------------------------------------------------------------===//
1656
1657 Name : VAR_ID | STRINGCONSTANT;
1658 OptName : Name | /*empty*/ { $$ = 0; };
1659
1660 ArgVal : Types OptName {
1661   if (*$1 == Type::VoidTy)
1662     ThrowException("void typed arguments are invalid!");
1663   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1664 };
1665
1666 ArgListH : ArgListH ',' ArgVal {
1667     $$ = $1;
1668     $1->push_back(*$3);
1669     delete $3;
1670   }
1671   | ArgVal {
1672     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1673     $$->push_back(*$1);
1674     delete $1;
1675   };
1676
1677 ArgList : ArgListH {
1678     $$ = $1;
1679   }
1680   | ArgListH ',' DOTDOTDOT {
1681     $$ = $1;
1682     $$->push_back(std::pair<PATypeHolder*,
1683                             char*>(new PATypeHolder(Type::VoidTy), 0));
1684   }
1685   | DOTDOTDOT {
1686     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1687     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1688   }
1689   | /* empty */ {
1690     $$ = 0;
1691   };
1692
1693 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' 
1694                   OptSection OptAlign {
1695   UnEscapeLexed($3);
1696   std::string FunctionName($3);
1697   free($3);  // Free strdup'd memory!
1698   
1699   if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1700     ThrowException("LLVM functions cannot return aggregate types!");
1701
1702   std::vector<const Type*> ParamTypeList;
1703   if ($5) {   // If there are arguments...
1704     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1705          I != $5->end(); ++I)
1706       ParamTypeList.push_back(I->first->get());
1707   }
1708
1709   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1710   if (isVarArg) ParamTypeList.pop_back();
1711
1712   const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1713   const PointerType *PFT = PointerType::get(FT);
1714   delete $2;
1715
1716   ValID ID;
1717   if (!FunctionName.empty()) {
1718     ID = ValID::create((char*)FunctionName.c_str());
1719   } else {
1720     ID = ValID::create((int)CurModule.Values[PFT].size());
1721   }
1722
1723   Function *Fn = 0;
1724   // See if this function was forward referenced.  If so, recycle the object.
1725   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1726     // Move the function to the end of the list, from whereever it was 
1727     // previously inserted.
1728     Fn = cast<Function>(FWRef);
1729     CurModule.CurrentModule->getFunctionList().remove(Fn);
1730     CurModule.CurrentModule->getFunctionList().push_back(Fn);
1731   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
1732              (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1733     // If this is the case, either we need to be a forward decl, or it needs 
1734     // to be.
1735     if (!CurFun.isDeclare && !Fn->isExternal())
1736       ThrowException("Redefinition of function '" + FunctionName + "'!");
1737     
1738     // Make sure to strip off any argument names so we can't get conflicts.
1739     if (Fn->isExternal())
1740       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1741            AI != AE; ++AI)
1742         AI->setName("");
1743
1744   } else  {  // Not already defined?
1745     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1746                       CurModule.CurrentModule);
1747     InsertValue(Fn, CurModule.Values);
1748   }
1749
1750   CurFun.FunctionStart(Fn);
1751   Fn->setCallingConv($1);
1752   Fn->setAlignment($8);
1753   if ($7) {
1754     Fn->setSection($7);
1755     free($7);
1756   }
1757
1758   // Add all of the arguments we parsed to the function...
1759   if ($5) {                     // Is null if empty...
1760     if (isVarArg) {  // Nuke the last entry
1761       assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1762              "Not a varargs marker!");
1763       delete $5->back().first;
1764       $5->pop_back();  // Delete the last entry
1765     }
1766     Function::arg_iterator ArgIt = Fn->arg_begin();
1767     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1768          I != $5->end(); ++I, ++ArgIt) {
1769       delete I->first;                          // Delete the typeholder...
1770
1771       setValueName(ArgIt, I->second);           // Insert arg into symtab...
1772       InsertValue(ArgIt);
1773     }
1774
1775     delete $5;                     // We're now done with the argument list
1776   }
1777 };
1778
1779 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1780
1781 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1782   $$ = CurFun.CurrentFunction;
1783
1784   // Make sure that we keep track of the linkage type even if there was a
1785   // previous "declare".
1786   $$->setLinkage($1);
1787 };
1788
1789 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1790
1791 Function : BasicBlockList END {
1792   $$ = $1;
1793 };
1794
1795 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1796   $$ = CurFun.CurrentFunction;
1797   CurFun.FunctionDone();
1798 };
1799
1800 //===----------------------------------------------------------------------===//
1801 //                        Rules to match Basic Blocks
1802 //===----------------------------------------------------------------------===//
1803
1804 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1805     $$ = ValID::create($1);
1806   }
1807   | EUINT64VAL {
1808     $$ = ValID::create($1);
1809   }
1810   | FPVAL {                     // Perhaps it's an FP constant?
1811     $$ = ValID::create($1);
1812   }
1813   | TRUETOK {
1814     $$ = ValID::create(ConstantBool::True);
1815   } 
1816   | FALSETOK {
1817     $$ = ValID::create(ConstantBool::False);
1818   }
1819   | NULL_TOK {
1820     $$ = ValID::createNull();
1821   }
1822   | UNDEF {
1823     $$ = ValID::createUndef();
1824   }
1825   | ZEROINITIALIZER {     // A vector zero constant.
1826     $$ = ValID::createZeroInit();
1827   }
1828   | '<' ConstVector '>' { // Nonempty unsized packed vector
1829     const Type *ETy = (*$2)[0]->getType();
1830     int NumElements = $2->size(); 
1831     
1832     PackedType* pt = PackedType::get(ETy, NumElements);
1833     PATypeHolder* PTy = new PATypeHolder(
1834                                          HandleUpRefs(
1835                                             PackedType::get(
1836                                                 ETy, 
1837                                                 NumElements)
1838                                             )
1839                                          );
1840     
1841     // Verify all elements are correct type!
1842     for (unsigned i = 0; i < $2->size(); i++) {
1843       if (ETy != (*$2)[i]->getType())
1844         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1845                      ETy->getDescription() +"' as required!\nIt is of type '" +
1846                      (*$2)[i]->getType()->getDescription() + "'.");
1847     }
1848
1849     $$ = ValID::create(ConstantPacked::get(pt, *$2));
1850     delete PTy; delete $2;
1851   }
1852   | ConstExpr {
1853     $$ = ValID::create($1);
1854   };
1855
1856 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1857 // another value.
1858 //
1859 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1860     $$ = ValID::create($1);
1861   }
1862   | Name {                   // Is it a named reference...?
1863     $$ = ValID::create($1);
1864   };
1865
1866 // ValueRef - A reference to a definition... either constant or symbolic
1867 ValueRef : SymbolicValueRef | ConstValueRef;
1868
1869
1870 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1871 // type immediately preceeds the value reference, and allows complex constant
1872 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1873 ResolvedVal : Types ValueRef {
1874     $$ = getVal(*$1, $2); delete $1;
1875   };
1876
1877 BasicBlockList : BasicBlockList BasicBlock {
1878     $$ = $1;
1879   }
1880   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1881     $$ = $1;
1882   };
1883
1884
1885 // Basic blocks are terminated by branching instructions: 
1886 // br, br/cc, switch, ret
1887 //
1888 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1889     setValueName($3, $2);
1890     InsertValue($3);
1891
1892     $1->getInstList().push_back($3);
1893     InsertValue($1);
1894     $$ = $1;
1895   };
1896
1897 InstructionList : InstructionList Inst {
1898     $1->getInstList().push_back($2);
1899     $$ = $1;
1900   }
1901   | /* empty */ {
1902     $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1903
1904     // Make sure to move the basic block to the correct location in the
1905     // function, instead of leaving it inserted wherever it was first
1906     // referenced.
1907     Function::BasicBlockListType &BBL = 
1908       CurFun.CurrentFunction->getBasicBlockList();
1909     BBL.splice(BBL.end(), BBL, $$);
1910   }
1911   | LABELSTR {
1912     $$ = CurBB = getBBVal(ValID::create($1), true);
1913
1914     // Make sure to move the basic block to the correct location in the
1915     // function, instead of leaving it inserted wherever it was first
1916     // referenced.
1917     Function::BasicBlockListType &BBL = 
1918       CurFun.CurrentFunction->getBasicBlockList();
1919     BBL.splice(BBL.end(), BBL, $$);
1920   };
1921
1922 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1923     $$ = new ReturnInst($2);
1924   }
1925   | RET VOID {                                       // Return with no result...
1926     $$ = new ReturnInst();
1927   }
1928   | BR LABEL ValueRef {                         // Unconditional Branch...
1929     $$ = new BranchInst(getBBVal($3));
1930   }                                                  // Conditional Branch...
1931   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1932     $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1933   }
1934   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1935     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1936     $$ = S;
1937
1938     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1939       E = $8->end();
1940     for (; I != E; ++I) {
1941       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1942           S->addCase(CI, I->second);
1943       else
1944         ThrowException("Switch case is constant, but not a simple integer!");
1945     }
1946     delete $8;
1947   }
1948   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1949     SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1950     $$ = S;
1951   }
1952   | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1953     TO LABEL ValueRef UNWIND LABEL ValueRef {
1954     const PointerType *PFTy;
1955     const FunctionType *Ty;
1956
1957     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1958         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1959       // Pull out the types of all of the arguments...
1960       std::vector<const Type*> ParamTypes;
1961       if ($6) {
1962         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1963              I != E; ++I)
1964           ParamTypes.push_back((*I)->getType());
1965       }
1966
1967       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1968       if (isVarArg) ParamTypes.pop_back();
1969
1970       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1971       PFTy = PointerType::get(Ty);
1972     }
1973
1974     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
1975
1976     BasicBlock *Normal = getBBVal($10);
1977     BasicBlock *Except = getBBVal($13);
1978
1979     // Create the call node...
1980     if (!$6) {                                   // Has no arguments?
1981       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1982     } else {                                     // Has arguments?
1983       // Loop through FunctionType's arguments and ensure they are specified
1984       // correctly!
1985       //
1986       FunctionType::param_iterator I = Ty->param_begin();
1987       FunctionType::param_iterator E = Ty->param_end();
1988       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
1989
1990       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1991         if ((*ArgI)->getType() != *I)
1992           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1993                          (*I)->getDescription() + "'!");
1994
1995       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1996         ThrowException("Invalid number of parameters detected!");
1997
1998       $$ = new InvokeInst(V, Normal, Except, *$6);
1999     }
2000     cast<InvokeInst>($$)->setCallingConv($2);
2001   
2002     delete $3;
2003     delete $6;
2004   }
2005   | UNWIND {
2006     $$ = new UnwindInst();
2007   }
2008   | UNREACHABLE {
2009     $$ = new UnreachableInst();
2010   };
2011
2012
2013
2014 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2015     $$ = $1;
2016     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2017     if (V == 0)
2018       ThrowException("May only switch on a constant pool value!");
2019
2020     $$->push_back(std::make_pair(V, getBBVal($6)));
2021   }
2022   | IntType ConstValueRef ',' LABEL ValueRef {
2023     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2024     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2025
2026     if (V == 0)
2027       ThrowException("May only switch on a constant pool value!");
2028
2029     $$->push_back(std::make_pair(V, getBBVal($5)));
2030   };
2031
2032 Inst : OptAssign InstVal {
2033   // Is this definition named?? if so, assign the name...
2034   setValueName($2, $1);
2035   InsertValue($2);
2036   $$ = $2;
2037 };
2038
2039 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2040     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2041     $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2042     delete $1;
2043   }
2044   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2045     $$ = $1;
2046     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2047                                  getBBVal($6)));
2048   };
2049
2050
2051 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
2052     $$ = new std::vector<Value*>();
2053     $$->push_back($1);
2054   }
2055   | ValueRefList ',' ResolvedVal {
2056     $$ = $1;
2057     $1->push_back($3);
2058   };
2059
2060 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2061 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2062
2063 OptTailCall : TAIL CALL {
2064     $$ = true;
2065   }
2066   | CALL {
2067     $$ = false;
2068   };
2069
2070
2071
2072 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2073     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
2074         !isa<PackedType>((*$2).get()))
2075       ThrowException(
2076         "Arithmetic operator requires integer, FP, or packed operands!");
2077     if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2078       ThrowException("Rem not supported on packed types!");
2079     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2080     if ($$ == 0)
2081       ThrowException("binary operator returned null!");
2082     delete $2;
2083   }
2084   | LogicalOps Types ValueRef ',' ValueRef {
2085     if (!(*$2)->isIntegral()) {
2086       if (!isa<PackedType>($2->get()) ||
2087           !cast<PackedType>($2->get())->getElementType()->isIntegral())
2088         ThrowException("Logical operator requires integral operands!");
2089     }
2090     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2091     if ($$ == 0)
2092       ThrowException("binary operator returned null!");
2093     delete $2;
2094   }
2095   | SetCondOps Types ValueRef ',' ValueRef {
2096     if(isa<PackedType>((*$2).get())) {
2097       ThrowException(
2098         "PackedTypes currently not supported in setcc instructions!");
2099     }
2100     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2101     if ($$ == 0)
2102       ThrowException("binary operator returned null!");
2103     delete $2;
2104   }
2105   | NOT ResolvedVal {
2106     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2107               << " Replacing with 'xor'.\n";
2108
2109     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2110     if (Ones == 0)
2111       ThrowException("Expected integral type for not instruction!");
2112
2113     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2114     if ($$ == 0)
2115       ThrowException("Could not create a xor instruction!");
2116   }
2117   | ShiftOps ResolvedVal ',' ResolvedVal {
2118     if ($4->getType() != Type::UByteTy)
2119       ThrowException("Shift amount must be ubyte!");
2120     if (!$2->getType()->isInteger())
2121       ThrowException("Shift constant expression requires integer operand!");
2122     $$ = new ShiftInst($1, $2, $4);
2123   }
2124   | CAST ResolvedVal TO Types {
2125     if (!$4->get()->isFirstClassType())
2126       ThrowException("cast instruction to a non-primitive type: '" +
2127                      $4->get()->getDescription() + "'!");
2128     $$ = new CastInst($2, *$4);
2129     delete $4;
2130   }
2131   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2132     if ($2->getType() != Type::BoolTy)
2133       ThrowException("select condition must be boolean!");
2134     if ($4->getType() != $6->getType())
2135       ThrowException("select value types should match!");
2136     $$ = new SelectInst($2, $4, $6);
2137   }
2138   | VAARG ResolvedVal ',' Types {
2139     NewVarArgs = true;
2140     $$ = new VAArgInst($2, *$4);
2141     delete $4;
2142   }
2143   | VAARG_old ResolvedVal ',' Types {
2144     ObsoleteVarArgs = true;
2145     const Type* ArgTy = $2->getType();
2146     Function* NF = CurModule.CurrentModule->
2147       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2148
2149     //b = vaarg a, t -> 
2150     //foo = alloca 1 of t
2151     //bar = vacopy a 
2152     //store bar -> foo
2153     //b = vaarg foo, t
2154     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2155     CurBB->getInstList().push_back(foo);
2156     CallInst* bar = new CallInst(NF, $2);
2157     CurBB->getInstList().push_back(bar);
2158     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2159     $$ = new VAArgInst(foo, *$4);
2160     delete $4;
2161   }
2162   | VANEXT_old ResolvedVal ',' Types {
2163     ObsoleteVarArgs = true;
2164     const Type* ArgTy = $2->getType();
2165     Function* NF = CurModule.CurrentModule->
2166       getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2167
2168     //b = vanext a, t ->
2169     //foo = alloca 1 of t
2170     //bar = vacopy a
2171     //store bar -> foo
2172     //tmp = vaarg foo, t
2173     //b = load foo
2174     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2175     CurBB->getInstList().push_back(foo);
2176     CallInst* bar = new CallInst(NF, $2);
2177     CurBB->getInstList().push_back(bar);
2178     CurBB->getInstList().push_back(new StoreInst(bar, foo));
2179     Instruction* tmp = new VAArgInst(foo, *$4);
2180     CurBB->getInstList().push_back(tmp);
2181     $$ = new LoadInst(foo);
2182     delete $4;
2183   }
2184   | PHI_TOK PHIList {
2185     const Type *Ty = $2->front().first->getType();
2186     if (!Ty->isFirstClassType())
2187       ThrowException("PHI node operands must be of first class type!");
2188     $$ = new PHINode(Ty);
2189     ((PHINode*)$$)->reserveOperandSpace($2->size());
2190     while ($2->begin() != $2->end()) {
2191       if ($2->front().first->getType() != Ty) 
2192         ThrowException("All elements of a PHI node must be of the same type!");
2193       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2194       $2->pop_front();
2195     }
2196     delete $2;  // Free the list...
2197   }
2198   | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')'  {
2199     const PointerType *PFTy;
2200     const FunctionType *Ty;
2201
2202     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2203         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2204       // Pull out the types of all of the arguments...
2205       std::vector<const Type*> ParamTypes;
2206       if ($6) {
2207         for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2208              I != E; ++I)
2209           ParamTypes.push_back((*I)->getType());
2210       }
2211
2212       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2213       if (isVarArg) ParamTypes.pop_back();
2214
2215       if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2216         ThrowException("LLVM functions cannot return aggregate types!");
2217
2218       Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2219       PFTy = PointerType::get(Ty);
2220     }
2221
2222     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2223
2224     // Create the call node...
2225     if (!$6) {                                   // Has no arguments?
2226       // Make sure no arguments is a good thing!
2227       if (Ty->getNumParams() != 0)
2228         ThrowException("No arguments passed to a function that "
2229                        "expects arguments!");
2230
2231       $$ = new CallInst(V, std::vector<Value*>());
2232     } else {                                     // Has arguments?
2233       // Loop through FunctionType's arguments and ensure they are specified
2234       // correctly!
2235       //
2236       FunctionType::param_iterator I = Ty->param_begin();
2237       FunctionType::param_iterator E = Ty->param_end();
2238       std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2239
2240       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2241         if ((*ArgI)->getType() != *I)
2242           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2243                          (*I)->getDescription() + "'!");
2244
2245       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2246         ThrowException("Invalid number of parameters detected!");
2247
2248       $$ = new CallInst(V, *$6);
2249     }
2250     cast<CallInst>($$)->setTailCall($1);
2251     cast<CallInst>($$)->setCallingConv($2);
2252     delete $3;
2253     delete $6;
2254   }
2255   | MemoryInst {
2256     $$ = $1;
2257   };
2258
2259
2260 // IndexList - List of indices for GEP based instructions...
2261 IndexList : ',' ValueRefList { 
2262     $$ = $2; 
2263   } | /* empty */ { 
2264     $$ = new std::vector<Value*>(); 
2265   };
2266
2267 OptVolatile : VOLATILE {
2268     $$ = true;
2269   }
2270   | /* empty */ {
2271     $$ = false;
2272   };
2273
2274
2275
2276 MemoryInst : MALLOC Types OptCAlign {
2277     $$ = new MallocInst(*$2, 0, $3);
2278     delete $2;
2279   }
2280   | MALLOC Types ',' UINT ValueRef OptCAlign {
2281     $$ = new MallocInst(*$2, getVal($4, $5), $6);
2282     delete $2;
2283   }
2284   | ALLOCA Types OptCAlign {
2285     $$ = new AllocaInst(*$2, 0, $3);
2286     delete $2;
2287   }
2288   | ALLOCA Types ',' UINT ValueRef OptCAlign {
2289     $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2290     delete $2;
2291   }
2292   | FREE ResolvedVal {
2293     if (!isa<PointerType>($2->getType()))
2294       ThrowException("Trying to free nonpointer type " + 
2295                      $2->getType()->getDescription() + "!");
2296     $$ = new FreeInst($2);
2297   }
2298
2299   | OptVolatile LOAD Types ValueRef {
2300     if (!isa<PointerType>($3->get()))
2301       ThrowException("Can't load from nonpointer type: " +
2302                      (*$3)->getDescription());
2303     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2304       ThrowException("Can't load from pointer of non-first-class type: " +
2305                      (*$3)->getDescription());
2306     $$ = new LoadInst(getVal(*$3, $4), "", $1);
2307     delete $3;
2308   }
2309   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2310     const PointerType *PT = dyn_cast<PointerType>($5->get());
2311     if (!PT)
2312       ThrowException("Can't store to a nonpointer type: " +
2313                      (*$5)->getDescription());
2314     const Type *ElTy = PT->getElementType();
2315     if (ElTy != $3->getType())
2316       ThrowException("Can't store '" + $3->getType()->getDescription() +
2317                      "' into space of type '" + ElTy->getDescription() + "'!");
2318
2319     $$ = new StoreInst($3, getVal(*$5, $6), $1);
2320     delete $5;
2321   }
2322   | GETELEMENTPTR Types ValueRef IndexList {
2323     if (!isa<PointerType>($2->get()))
2324       ThrowException("getelementptr insn requires pointer operand!");
2325
2326     // LLVM 1.2 and earlier used ubyte struct indices.  Convert any ubyte struct
2327     // indices to uint struct indices for compatibility.
2328     generic_gep_type_iterator<std::vector<Value*>::iterator>
2329       GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2330       GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2331     for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2332       if (isa<StructType>(*GTI))        // Only change struct indices
2333         if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2334           if (CUI->getType() == Type::UByteTy)
2335             (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2336
2337     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2338       ThrowException("Invalid getelementptr indices for type '" +
2339                      (*$2)->getDescription()+ "'!");
2340     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2341     delete $2; delete $4;
2342   };
2343
2344
2345 %%
2346 int yyerror(const char *ErrorMsg) {
2347   std::string where 
2348     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2349                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2350   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2351   if (yychar == YYEMPTY || yychar == 0)
2352     errMsg += "end-of-file.";
2353   else
2354     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2355   ThrowException(errMsg);
2356   return 0;
2357 }