Instead of searching the entire type graph for a type to determine if it
[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/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOperators.h"
21 #include "llvm/iPHINode.h"
22 #include "Support/STLExtras.h"
23 #include "Support/DepthFirstIterator.h"
24 #include <list>
25 #include <utility>
26 #include <algorithm>
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
34 static Module *ParserResult;
35 std::string CurFilename;
36
37 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
38 // relating to upreferences in the input stream.
39 //
40 //#define DEBUG_UPREFS 1
41 #ifdef DEBUG_UPREFS
42 #define UR_OUT(X) std::cerr << X
43 #else
44 #define UR_OUT(X)
45 #endif
46
47 #define YYERROR_VERBOSE 1
48
49 // HACK ALERT: This variable is used to implement the automatic conversion of
50 // variable argument instructions from their old to new forms.  When this
51 // compatiblity "Feature" is removed, this should be too.
52 //
53 static BasicBlock *CurBB;
54 static bool ObsoleteVarArgs;
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 ResolveDefinitions(std::vector<ValueList> &LateResolvers,
62                                std::vector<ValueList> *FutureLateResolvers = 0);
63
64 static struct PerModuleInfo {
65   Module *CurrentModule;
66   std::vector<ValueList>    Values;     // Module level numbered definitions
67   std::vector<ValueList>    LateResolveValues;
68   std::vector<PATypeHolder> Types;
69   std::map<ValID, PATypeHolder> LateResolveTypes;
70
71   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
72   // references to global values.  Global values may be referenced before they
73   // are defined, and if so, the temporary object that they represent is held
74   // here.  This is used for forward references of ConstantPointerRefs.
75   //
76   typedef std::map<std::pair<const PointerType *,
77                              ValID>, GlobalVariable*> GlobalRefsType;
78   GlobalRefsType GlobalRefs;
79
80   void ModuleDone() {
81     // If we could not resolve some functions at function compilation time
82     // (calls to functions before they are defined), resolve them now...  Types
83     // are resolved when the constant pool has been completely parsed.
84     //
85     ResolveDefinitions(LateResolveValues);
86
87     // Check to make sure that all global value forward references have been
88     // resolved!
89     //
90     if (!GlobalRefs.empty()) {
91       std::string UndefinedReferences = "Unresolved global references exist:\n";
92       
93       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
94            I != E; ++I) {
95         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
96                                I->first.second.getName() + "\n";
97       }
98       ThrowException(UndefinedReferences);
99     }
100
101     Values.clear();         // Clear out function local definitions
102     Types.clear();
103     CurrentModule = 0;
104   }
105
106
107   // DeclareNewGlobalValue - Called every time a new GV has been defined.  This
108   // is used to remove things from the forward declaration map, resolving them
109   // to the correct thing as needed.
110   //
111   void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
112     // Check to see if there is a forward reference to this global variable...
113     // if there is, eliminate it and patch the reference to use the new def'n.
114     GlobalRefsType::iterator I =
115       GlobalRefs.find(std::make_pair(GV->getType(), D));
116
117     if (I != GlobalRefs.end()) {
118       GlobalVariable *OldGV = I->second;   // Get the placeholder...
119       I->first.second.destroy();  // Free string memory if necessary
120       
121       // Loop over all of the uses of the GlobalValue.  The only thing they are
122       // allowed to be is ConstantPointerRef's.
123       assert(OldGV->hasOneUse() && "Only one reference should exist!");
124       User *U = OldGV->use_back();  // Must be a ConstantPointerRef...
125       ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
126         
127       // Change the const pool reference to point to the real global variable
128       // now.  This should drop a use from the OldGV.
129       CPR->mutateReferences(OldGV, GV);
130       assert(OldGV->use_empty() && "All uses should be gone now!");
131       
132       // Remove OldGV from the module...
133       CurrentModule->getGlobalList().remove(OldGV);
134       delete OldGV;                        // Delete the old placeholder
135       
136       // Remove the map entry for the global now that it has been created...
137       GlobalRefs.erase(I);
138     }
139   }
140
141 } CurModule;
142
143 static struct PerFunctionInfo {
144   Function *CurrentFunction;     // Pointer to current function being created
145
146   std::vector<ValueList> Values;      // Keep track of numbered definitions
147   std::vector<ValueList> LateResolveValues;
148   std::vector<PATypeHolder> Types;
149   std::map<ValID, PATypeHolder> LateResolveTypes;
150   SymbolTable LocalSymtab;
151   bool isDeclare;                // Is this function a forward declararation?
152
153   inline PerFunctionInfo() {
154     CurrentFunction = 0;
155     isDeclare = false;
156   }
157
158   inline void FunctionStart(Function *M) {
159     CurrentFunction = M;
160   }
161
162   void FunctionDone() {
163     // If we could not resolve some blocks at parsing time (forward branches)
164     // resolve the branches now...
165     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
166
167     // Make sure to resolve any constant expr references that might exist within
168     // the function we just declared itself.
169     ValID FID;
170     if (CurrentFunction->hasName()) {
171       FID = ValID::create((char*)CurrentFunction->getName().c_str());
172     } else {
173       unsigned Slot = CurrentFunction->getType()->getUniqueID();
174       assert(CurModule.Values.size() > Slot && "Function not inserted?");
175       // Figure out which slot number if is...
176       for (unsigned i = 0; ; ++i) {
177         assert(i < CurModule.Values[Slot].size() && "Function not found!");
178         if (CurModule.Values[Slot][i] == CurrentFunction) {
179           FID = ValID::create((int)i);
180           break;
181         }
182       }
183     }
184     CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
185
186     Values.clear();         // Clear out function local definitions
187     Types.clear();          // Clear out function local types
188     LocalSymtab.clear();    // Clear out function local symbol table
189     CurrentFunction = 0;
190     isDeclare = false;
191   }
192 } CurFun;  // Info for the current function...
193
194 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
195
196
197 //===----------------------------------------------------------------------===//
198 //               Code to handle definitions of all the types
199 //===----------------------------------------------------------------------===//
200
201 static int InsertValue(Value *D,
202                        std::vector<ValueList> &ValueTab = CurFun.Values) {
203   if (D->hasName()) return -1;           // Is this a numbered definition?
204
205   // Yes, insert the value into the value table...
206   unsigned type = D->getType()->getUniqueID();
207   if (ValueTab.size() <= type)
208     ValueTab.resize(type+1, ValueList());
209   //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
210   ValueTab[type].push_back(D);
211   return ValueTab[type].size()-1;
212 }
213
214 // TODO: FIXME when Type are not const
215 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
216   Types.push_back(Ty);
217 }
218
219 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
220   switch (D.Type) {
221   case ValID::NumberVal: {                 // Is it a numbered definition?
222     unsigned Num = (unsigned)D.Num;
223
224     // Module constants occupy the lowest numbered slots...
225     if (Num < CurModule.Types.size()) 
226       return CurModule.Types[Num];
227
228     Num -= CurModule.Types.size();
229
230     // Check that the number is within bounds...
231     if (Num <= CurFun.Types.size())
232       return CurFun.Types[Num];
233     break;
234   }
235   case ValID::NameVal: {                // Is it a named definition?
236     std::string Name(D.Name);
237     SymbolTable *SymTab = 0;
238     Value *N = 0;
239     if (inFunctionScope()) {
240       SymTab = &CurFun.CurrentFunction->getSymbolTable();
241       N = SymTab->lookup(Type::TypeTy, Name);
242     }
243
244     if (N == 0) {
245       // Symbol table doesn't automatically chain yet... because the function
246       // hasn't been added to the module...
247       //
248       SymTab = &CurModule.CurrentModule->getSymbolTable();
249       N = SymTab->lookup(Type::TypeTy, Name);
250       if (N == 0) break;
251     }
252
253     D.destroy();  // Free old strdup'd memory...
254     return cast<Type>(N);
255   }
256   default:
257     ThrowException("Internal parser error: Invalid symbol type reference!");
258   }
259
260   // If we reached here, we referenced either a symbol that we don't know about
261   // or an id number that hasn't been read yet.  We may be referencing something
262   // forward, so just create an entry to be resolved later and get to it...
263   //
264   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
265
266   std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
267     CurFun.LateResolveTypes : CurModule.LateResolveTypes;
268   
269   std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
270   if (I != LateResolver.end()) {
271     return I->second;
272   }
273
274   Type *Typ = OpaqueType::get();
275   LateResolver.insert(std::make_pair(D, Typ));
276   return Typ;
277 }
278
279 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
280   SymbolTable &SymTab = 
281     inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
282                         CurModule.CurrentModule->getSymbolTable();
283   return SymTab.lookup(Ty, Name);
284 }
285
286 // getValNonImprovising - Look up the value specified by the provided type and
287 // the provided ValID.  If the value exists and has already been defined, return
288 // it.  Otherwise return null.
289 //
290 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
291   if (isa<FunctionType>(Ty))
292     ThrowException("Functions are not values and "
293                    "must be referenced as pointers");
294
295   switch (D.Type) {
296   case ValID::NumberVal: {                 // Is it a numbered definition?
297     unsigned type = Ty->getUniqueID();
298     unsigned Num = (unsigned)D.Num;
299
300     // Module constants occupy the lowest numbered slots...
301     if (type < CurModule.Values.size()) {
302       if (Num < CurModule.Values[type].size()) 
303         return CurModule.Values[type][Num];
304
305       Num -= CurModule.Values[type].size();
306     }
307
308     // Make sure that our type is within bounds
309     if (CurFun.Values.size() <= type) return 0;
310
311     // Check that the number is within bounds...
312     if (CurFun.Values[type].size() <= Num) return 0;
313   
314     return CurFun.Values[type][Num];
315   }
316
317   case ValID::NameVal: {                // Is it a named definition?
318     Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
319     if (N == 0) return 0;
320
321     D.destroy();  // Free old strdup'd memory...
322     return N;
323   }
324
325   // Check to make sure that "Ty" is an integral type, and that our 
326   // value will fit into the specified type...
327   case ValID::ConstSIntVal:    // Is it a constant pool reference??
328     if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
329       ThrowException("Signed integral constant '" +
330                      itostr(D.ConstPool64) + "' is invalid for type '" + 
331                      Ty->getDescription() + "'!");
332     return ConstantSInt::get(Ty, D.ConstPool64);
333
334   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
335     if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
336       if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
337         ThrowException("Integral constant '" + utostr(D.UConstPool64) +
338                        "' is invalid or out of range!");
339       } else {     // This is really a signed reference.  Transmogrify.
340         return ConstantSInt::get(Ty, D.ConstPool64);
341       }
342     } else {
343       return ConstantUInt::get(Ty, D.UConstPool64);
344     }
345
346   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
347     if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
348       ThrowException("FP constant invalid for type!!");
349     return ConstantFP::get(Ty, D.ConstPoolFP);
350     
351   case ValID::ConstNullVal:      // Is it a null value?
352     if (!isa<PointerType>(Ty))
353       ThrowException("Cannot create a a non pointer null!");
354     return ConstantPointerNull::get(cast<PointerType>(Ty));
355     
356   case ValID::ConstantVal:       // Fully resolved constant?
357     if (D.ConstantValue->getType() != Ty)
358       ThrowException("Constant expression type different from required type!");
359     return D.ConstantValue;
360
361   default:
362     assert(0 && "Unhandled case!");
363     return 0;
364   }   // End of switch
365
366   assert(0 && "Unhandled case!");
367   return 0;
368 }
369
370
371 // getVal - This function is identical to getValNonImprovising, except that if a
372 // value is not already defined, it "improvises" by creating a placeholder var
373 // that looks and acts just like the requested variable.  When the value is
374 // defined later, all uses of the placeholder variable are replaced with the
375 // real thing.
376 //
377 static Value *getVal(const Type *Ty, const ValID &D) {
378   assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
379
380   // See if the value has already been defined...
381   Value *V = getValNonImprovising(Ty, D);
382   if (V) return V;
383
384   // If we reached here, we referenced either a symbol that we don't know about
385   // or an id number that hasn't been read yet.  We may be referencing something
386   // forward, so just create an entry to be resolved later and get to it...
387   //
388   Value *d = 0;
389   switch (Ty->getPrimitiveID()) {
390   case Type::LabelTyID:  d = new   BBPlaceHolder(Ty, D); break;
391   default:               d = new ValuePlaceHolder(Ty, D); break;
392   }
393
394   assert(d != 0 && "How did we not make something?");
395   if (inFunctionScope())
396     InsertValue(d, CurFun.LateResolveValues);
397   else 
398     InsertValue(d, CurModule.LateResolveValues);
399   return d;
400 }
401
402
403 //===----------------------------------------------------------------------===//
404 //              Code to handle forward references in instructions
405 //===----------------------------------------------------------------------===//
406 //
407 // This code handles the late binding needed with statements that reference
408 // values not defined yet... for example, a forward branch, or the PHI node for
409 // a loop body.
410 //
411 // This keeps a table (CurFun.LateResolveValues) of all such forward references
412 // and back patchs after we are done.
413 //
414
415 // ResolveDefinitions - If we could not resolve some defs at parsing 
416 // time (forward branches, phi functions for loops, etc...) resolve the 
417 // defs now...
418 //
419 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
420                                std::vector<ValueList> *FutureLateResolvers) {
421   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
422   for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
423     while (!LateResolvers[ty].empty()) {
424       Value *V = LateResolvers[ty].back();
425       assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
426
427       LateResolvers[ty].pop_back();
428       ValID &DID = getValIDFromPlaceHolder(V);
429
430       Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
431       if (TheRealValue) {
432         V->replaceAllUsesWith(TheRealValue);
433         delete V;
434       } else if (FutureLateResolvers) {
435         // Functions have their unresolved items forwarded to the module late
436         // resolver table
437         InsertValue(V, *FutureLateResolvers);
438       } else {
439         if (DID.Type == ValID::NameVal)
440           ThrowException("Reference to an invalid definition: '" +DID.getName()+
441                          "' of type '" + V->getType()->getDescription() + "'",
442                          getLineNumFromPlaceHolder(V));
443         else
444           ThrowException("Reference to an invalid definition: #" +
445                          itostr(DID.Num) + " of type '" + 
446                          V->getType()->getDescription() + "'",
447                          getLineNumFromPlaceHolder(V));
448       }
449     }
450   }
451
452   LateResolvers.clear();
453 }
454
455 // ResolveTypeTo - A brand new type was just declared.  This means that (if
456 // name is not null) things referencing Name can be resolved.  Otherwise, things
457 // refering to the number can be resolved.  Do this now.
458 //
459 static void ResolveTypeTo(char *Name, const Type *ToTy) {
460   std::vector<PATypeHolder> &Types = inFunctionScope() ? 
461      CurFun.Types : CurModule.Types;
462
463    ValID D;
464    if (Name) D = ValID::create(Name);
465    else      D = ValID::create((int)Types.size());
466
467    std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ? 
468      CurFun.LateResolveTypes : CurModule.LateResolveTypes;
469   
470    std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
471    if (I != LateResolver.end()) {
472      ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
473      LateResolver.erase(I);
474    }
475 }
476
477 // ResolveTypes - At this point, all types should be resolved.  Any that aren't
478 // are errors.
479 //
480 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
481   if (!LateResolveTypes.empty()) {
482     const ValID &DID = LateResolveTypes.begin()->first;
483
484     if (DID.Type == ValID::NameVal)
485       ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
486     else
487       ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
488   }
489 }
490
491
492 // setValueName - Set the specified value to the name given.  The name may be
493 // null potentially, in which case this is a noop.  The string passed in is
494 // assumed to be a malloc'd string buffer, and is freed by this function.
495 //
496 // This function returns true if the value has already been defined, but is
497 // allowed to be redefined in the specified context.  If the name is a new name
498 // for the typeplane, false is returned.
499 //
500 static bool setValueName(Value *V, char *NameStr) {
501   if (NameStr == 0) return false;
502   
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 + 
508                    "' to a null valued instruction!");
509
510   SymbolTable &ST = inFunctionScope() ? 
511     CurFun.CurrentFunction->getSymbolTable() : 
512     CurModule.CurrentModule->getSymbolTable();
513
514   Value *Existing = ST.lookup(V->getType(), Name);
515   if (Existing) {    // Inserting a name that is already defined???
516     // There is only one case where this is allowed: when we are refining an
517     // opaque type.  In this case, Existing will be an opaque type.
518     if (const Type *Ty = dyn_cast<Type>(Existing)) {
519       if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
520         // We ARE replacing an opaque type!
521         ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
522         return true;
523       }
524     }
525
526     // Otherwise, we are a simple redefinition of a value, check to see if it
527     // is defined the same as the old one...
528     if (const Type *Ty = dyn_cast<Type>(Existing)) {
529       if (Ty == cast<Type>(V)) return true;  // Yes, it's equal.
530       // std::cerr << "Type: " << Ty->getDescription() << " != "
531       //      << cast<Type>(V)->getDescription() << "!\n";
532     } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
533       if (C == V) return true;      // Constants are equal to themselves
534     } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
535       // We are allowed to redefine a global variable in two circumstances:
536       // 1. If at least one of the globals is uninitialized or 
537       // 2. If both initializers have the same value.
538       //
539       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
540         if (!EGV->hasInitializer() || !GV->hasInitializer() ||
541              EGV->getInitializer() == GV->getInitializer()) {
542
543           // Make sure the existing global version gets the initializer!  Make
544           // sure that it also gets marked const if the new version is.
545           if (GV->hasInitializer() && !EGV->hasInitializer())
546             EGV->setInitializer(GV->getInitializer());
547           if (GV->isConstant())
548             EGV->setConstant(true);
549           EGV->setLinkage(GV->getLinkage());
550           
551           delete GV;     // Destroy the duplicate!
552           return true;   // They are equivalent!
553         }
554       }
555     }
556
557     ThrowException("Redefinition of value named '" + Name + "' in the '" +
558                    V->getType()->getDescription() + "' type plane!");
559   }
560
561   // Set the name
562   V->setName(Name, &ST);
563
564   // If we're in function scope
565   if (inFunctionScope()) {
566     // Look up the symbol in the function's local symboltable
567     Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
568
569     // If it already exists
570     if (Existing) {
571       // Bail
572       ThrowException("Redefinition of value named '" + Name + "' in the '" +
573                    V->getType()->getDescription() + "' type plane!");
574
575     // otherwise, since it doesn't exist
576     } else {
577       // Insert it.
578       CurFun.LocalSymtab.insert(V);
579     }
580   }
581   return false;
582 }
583
584
585 //===----------------------------------------------------------------------===//
586 // Code for handling upreferences in type names...
587 //
588
589 // TypeContains - Returns true if Ty directly contains E in it.
590 //
591 static bool TypeContains(const Type *Ty, const Type *E) {
592   return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
593 }
594
595 namespace {
596   struct UpRefRecord {
597     // NestingLevel - The number of nesting levels that need to be popped before
598     // this type is resolved.
599     unsigned NestingLevel;
600     
601     // LastContainedTy - This is the type at the current binding level for the
602     // type.  Every time we reduce the nesting level, this gets updated.
603     const Type *LastContainedTy;
604
605     // UpRefTy - This is the actual opaque type that the upreference is
606     // represented with.
607     OpaqueType *UpRefTy;
608
609     UpRefRecord(unsigned NL, OpaqueType *URTy)
610       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
611   };
612 }
613
614 // UpRefs - A list of the outstanding upreferences that need to be resolved.
615 static std::vector<UpRefRecord> UpRefs;
616
617 /// HandleUpRefs - Every time we finish a new layer of types, this function is
618 /// called.  It loops through the UpRefs vector, which is a list of the
619 /// currently active types.  For each type, if the up reference is contained in
620 /// the newly completed type, we decrement the level count.  When the level
621 /// count reaches zero, the upreferenced type is the type that is passed in:
622 /// thus we can complete the cycle.
623 ///
624 static PATypeHolder HandleUpRefs(const Type *ty) {
625   if (!ty->isAbstract()) return ty;
626   PATypeHolder Ty(ty);
627   UR_OUT("Type '" << Ty->getDescription() << 
628          "' newly formed.  Resolving upreferences.\n" <<
629          UpRefs.size() << " upreferences active!\n");
630   for (unsigned i = 0; i != UpRefs.size(); ++i) {
631     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " 
632            << UpRefs[i].second->getDescription() << ") = " 
633            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
634     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
635       // Decrement level of upreference
636       unsigned Level = --UpRefs[i].NestingLevel;
637       UpRefs[i].LastContainedTy = Ty;
638       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
639       if (Level == 0) {                     // Upreference should be resolved! 
640         UR_OUT("  * Resolving upreference for "
641                << UpRefs[i].second->getDescription() << "\n";
642                std::string OldName = UpRefs[i].UpRefTy->getDescription());
643         UpRefs[i].UpRefTy->refineAbstractTypeTo(Ty);
644         UR_OUT("  * Type '" << OldName << "' refined upreference to: "
645                << (const void*)Ty << ", " << Ty->getDescription() << "\n");
646         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
647         --i;                                // Do not skip the next element...
648       }
649     }
650   }
651
652   return Ty;
653 }
654
655
656 //===----------------------------------------------------------------------===//
657 //            RunVMAsmParser - Define an interface to this parser
658 //===----------------------------------------------------------------------===//
659 //
660 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
661   llvmAsmin = F;
662   CurFilename = Filename;
663   llvmAsmlineno = 1;      // Reset the current line number...
664   ObsoleteVarArgs = false;
665
666   // Allocate a new module to read
667   CurModule.CurrentModule = new Module(Filename);
668
669   try {
670     yyparse();       // Parse the file.
671   } catch (...) {
672     // Clear the symbol table so it doesn't complain when it
673     // gets destructed
674     CurFun.LocalSymtab.clear();
675     throw;
676   }
677
678   Module *Result = ParserResult;
679
680   // Check to see if they called va_start but not va_arg..
681   if (!ObsoleteVarArgs)
682     if (Function *F = Result->getNamedFunction("llvm.va_start"))
683       if (F->asize() == 1) {
684         std::cerr << "WARNING: this file uses obsolete features.  "
685                   << "Assemble and disassemble to update it.\n";
686         ObsoleteVarArgs = true;
687       }
688
689
690   if (ObsoleteVarArgs) {
691     // If the user is making use of obsolete varargs intrinsics, adjust them for
692     // the user.
693     if (Function *F = Result->getNamedFunction("llvm.va_start")) {
694       assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
695
696       const Type *RetTy = F->getFunctionType()->getParamType(0);
697       RetTy = cast<PointerType>(RetTy)->getElementType();
698       Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
699       
700       while (!F->use_empty()) {
701         CallInst *CI = cast<CallInst>(F->use_back());
702         Value *V = new CallInst(NF, "", CI);
703         new StoreInst(V, CI->getOperand(1), CI);
704         CI->getParent()->getInstList().erase(CI);
705       }
706       Result->getFunctionList().erase(F);
707     }
708     
709     if (Function *F = Result->getNamedFunction("llvm.va_end")) {
710       assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
711       const Type *ArgTy = F->getFunctionType()->getParamType(0);
712       ArgTy = cast<PointerType>(ArgTy)->getElementType();
713       Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
714                                                  ArgTy, 0);
715
716       while (!F->use_empty()) {
717         CallInst *CI = cast<CallInst>(F->use_back());
718         Value *V = new LoadInst(CI->getOperand(1), "", CI);
719         new CallInst(NF, V, "", CI);
720         CI->getParent()->getInstList().erase(CI);
721       }
722       Result->getFunctionList().erase(F);
723     }
724
725     if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
726       assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
727       const Type *ArgTy = F->getFunctionType()->getParamType(0);
728       ArgTy = cast<PointerType>(ArgTy)->getElementType();
729       Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
730                                                  ArgTy, 0);
731
732       while (!F->use_empty()) {
733         CallInst *CI = cast<CallInst>(F->use_back());
734         Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
735         new StoreInst(V, CI->getOperand(1), CI);
736         CI->getParent()->getInstList().erase(CI);
737       }
738       Result->getFunctionList().erase(F);
739     }
740   }
741
742   llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
743   ParserResult = 0;
744
745   return Result;
746 }
747
748 } // End llvm namespace
749
750 using namespace llvm;
751
752 %}
753
754 %union {
755   llvm::Module                           *ModuleVal;
756   llvm::Function                         *FunctionVal;
757   std::pair<llvm::PATypeHolder*, char*>  *ArgVal;
758   llvm::BasicBlock                       *BasicBlockVal;
759   llvm::TerminatorInst                   *TermInstVal;
760   llvm::Instruction                      *InstVal;
761   llvm::Constant                         *ConstVal;
762
763   const llvm::Type                       *PrimType;
764   llvm::PATypeHolder                     *TypeVal;
765   llvm::Value                            *ValueVal;
766
767   std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
768   std::vector<llvm::Value*>              *ValueList;
769   std::list<llvm::PATypeHolder>          *TypeList;
770   std::list<std::pair<llvm::Value*,
771                       llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
772   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
773   std::vector<llvm::Constant*>           *ConstVector;
774
775   llvm::GlobalValue::LinkageTypes         Linkage;
776   int64_t                           SInt64Val;
777   uint64_t                          UInt64Val;
778   int                               SIntVal;
779   unsigned                          UIntVal;
780   double                            FPVal;
781   bool                              BoolVal;
782
783   char                             *StrVal;   // This memory is strdup'd!
784   llvm::ValID                             ValIDVal; // strdup'd memory maybe!
785
786   llvm::Instruction::BinaryOps            BinaryOpVal;
787   llvm::Instruction::TermOps              TermOpVal;
788   llvm::Instruction::MemoryOps            MemOpVal;
789   llvm::Instruction::OtherOps             OtherOpVal;
790   llvm::Module::Endianness                Endianness;
791 }
792
793 %type <ModuleVal>     Module FunctionList
794 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
795 %type <BasicBlockVal> BasicBlock InstructionList
796 %type <TermInstVal>   BBTerminatorInst
797 %type <InstVal>       Inst InstVal MemoryInst
798 %type <ConstVal>      ConstVal ConstExpr
799 %type <ConstVector>   ConstVector
800 %type <ArgList>       ArgList ArgListH
801 %type <ArgVal>        ArgVal
802 %type <PHIList>       PHIList
803 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
804 %type <ValueList>     IndexList                   // For GEP derived indices
805 %type <TypeList>      TypeListI ArgTypeListI
806 %type <JumpTable>     JumpTable
807 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
808 %type <BoolVal>       OptVolatile                 // 'volatile' or not
809 %type <Linkage>       OptLinkage
810 %type <Endianness>    BigOrLittle
811
812 // ValueRef - Unresolved reference to a definition or BB
813 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
814 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
815 // Tokens and types for handling constant integer values
816 //
817 // ESINT64VAL - A negative number within long long range
818 %token <SInt64Val> ESINT64VAL
819
820 // EUINT64VAL - A positive number within uns. long long range
821 %token <UInt64Val> EUINT64VAL
822 %type  <SInt64Val> EINT64VAL
823
824 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
825 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
826 %type   <SIntVal>   INTVAL
827 %token  <FPVal>     FPVAL     // Float or Double constant
828
829 // Built in types...
830 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
831 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
832 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
833 %token <PrimType> FLOAT DOUBLE TYPE LABEL
834
835 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
836 %type  <StrVal> Name OptName OptAssign
837
838
839 %token IMPLEMENTATION ZEROINITIALIZER TRUE FALSE BEGINTOK ENDTOK
840 %token DECLARE GLOBAL CONSTANT VOLATILE
841 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK  APPENDING
842 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
843
844 // Basic Block Terminating Operators 
845 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
846
847 // Binary Operators 
848 %type  <BinaryOpVal> BinaryOps  // all the binary operators
849 %type  <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
850 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
851 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
852
853 // Memory Instructions
854 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
855
856 // Other Operators
857 %type  <OtherOpVal> ShiftOps
858 %token <OtherOpVal> PHI_TOK CALL CAST SHL SHR VAARG VANEXT
859 %token VA_ARG // FIXME: OBSOLETE
860
861 %start Module
862 %%
863
864 // Handle constant integer size restriction and conversion...
865 //
866 INTVAL : SINTVAL;
867 INTVAL : UINTVAL {
868   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
869     ThrowException("Value too large for type!");
870   $$ = (int32_t)$1;
871 };
872
873
874 EINT64VAL : ESINT64VAL;      // These have same type and can't cause problems...
875 EINT64VAL : EUINT64VAL {
876   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
877     ThrowException("Value too large for type!");
878   $$ = (int64_t)$1;
879 };
880
881 // Operations that are notably excluded from this list include: 
882 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
883 //
884 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
885 LogicalOps   : AND | OR | XOR;
886 SetCondOps   : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
887 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
888
889 ShiftOps  : SHL | SHR;
890
891 // These are some types that allow classification if we only want a particular 
892 // thing... for example, only a signed, unsigned, or integral type.
893 SIntType :  LONG |  INT |  SHORT | SBYTE;
894 UIntType : ULONG | UINT | USHORT | UBYTE;
895 IntType  : SIntType | UIntType;
896 FPType   : FLOAT | DOUBLE;
897
898 // OptAssign - Value producing statements have an optional assignment component
899 OptAssign : Name '=' {
900     $$ = $1;
901   }
902   | /*empty*/ { 
903     $$ = 0; 
904   };
905
906 OptLinkage : INTERNAL  { $$ = GlobalValue::InternalLinkage; } |
907              LINKONCE  { $$ = GlobalValue::LinkOnceLinkage; } |
908              WEAK      { $$ = GlobalValue::WeakLinkage; } |
909              APPENDING { $$ = GlobalValue::AppendingLinkage; } |
910              /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
911
912 //===----------------------------------------------------------------------===//
913 // Types includes all predefined types... except void, because it can only be
914 // used in specific contexts (function returning void for example).  To have
915 // access to it, a user must explicitly use TypesV.
916 //
917
918 // TypesV includes all of 'Types', but it also includes the void type.
919 TypesV    : Types    | VOID { $$ = new PATypeHolder($1); };
920 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
921
922 Types     : UpRTypes {
923     if (!UpRefs.empty())
924       ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
925     $$ = $1;
926   };
927
928
929 // Derived types are added later...
930 //
931 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT ;
932 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL;
933 UpRTypes : OPAQUE {
934     $$ = new PATypeHolder(OpaqueType::get());
935   }
936   | PrimType {
937     $$ = new PATypeHolder($1);
938   };
939 UpRTypes : SymbolicValueRef {            // Named types are also simple types...
940   $$ = new PATypeHolder(getTypeVal($1));
941 };
942
943 // Include derived types in the Types production.
944 //
945 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
946     if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
947     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
948     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
949     $$ = new PATypeHolder(OT);
950     UR_OUT("New Upreference!\n");
951   }
952   | UpRTypesV '(' ArgTypeListI ')' {           // Function derived type?
953     std::vector<const Type*> Params;
954     mapto($3->begin(), $3->end(), std::back_inserter(Params), 
955           std::mem_fun_ref(&PATypeHolder::get));
956     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
957     if (isVarArg) Params.pop_back();
958
959     $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
960     delete $3;      // Delete the argument list
961     delete $1;      // Delete the return type handle
962   }
963   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
964     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
965     delete $4;
966   }
967   | '{' TypeListI '}' {                        // Structure type?
968     std::vector<const Type*> Elements;
969     mapto($2->begin(), $2->end(), std::back_inserter(Elements), 
970         std::mem_fun_ref(&PATypeHolder::get));
971
972     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
973     delete $2;
974   }
975   | '{' '}' {                                  // Empty structure type?
976     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
977   }
978   | UpRTypes '*' {                             // Pointer type?
979     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
980     delete $1;
981   };
982
983 // TypeList - Used for struct declarations and as a basis for function type 
984 // declaration type lists
985 //
986 TypeListI : UpRTypes {
987     $$ = new std::list<PATypeHolder>();
988     $$->push_back(*$1); delete $1;
989   }
990   | TypeListI ',' UpRTypes {
991     ($$=$1)->push_back(*$3); delete $3;
992   };
993
994 // ArgTypeList - List of types for a function type declaration...
995 ArgTypeListI : TypeListI
996   | TypeListI ',' DOTDOTDOT {
997     ($$=$1)->push_back(Type::VoidTy);
998   }
999   | DOTDOTDOT {
1000     ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1001   }
1002   | /*empty*/ {
1003     $$ = new std::list<PATypeHolder>();
1004   };
1005
1006 // ConstVal - The various declarations that go into the constant pool.  This
1007 // production is used ONLY to represent constants that show up AFTER a 'const',
1008 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1009 // into other expressions (such as integers and constexprs) are handled by the
1010 // ResolvedVal, ValueRef and ConstValueRef productions.
1011 //
1012 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1013     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1014     if (ATy == 0)
1015       ThrowException("Cannot make array constant with type: '" + 
1016                      (*$1)->getDescription() + "'!");
1017     const Type *ETy = ATy->getElementType();
1018     int NumElements = ATy->getNumElements();
1019
1020     // Verify that we have the correct size...
1021     if (NumElements != -1 && NumElements != (int)$3->size())
1022       ThrowException("Type mismatch: constant sized array initialized with " +
1023                      utostr($3->size()) +  " arguments, but has size of " + 
1024                      itostr(NumElements) + "!");
1025
1026     // Verify all elements are correct type!
1027     for (unsigned i = 0; i < $3->size(); i++) {
1028       if (ETy != (*$3)[i]->getType())
1029         ThrowException("Element #" + utostr(i) + " is not of type '" + 
1030                        ETy->getDescription() +"' as required!\nIt is of type '"+
1031                        (*$3)[i]->getType()->getDescription() + "'.");
1032     }
1033
1034     $$ = ConstantArray::get(ATy, *$3);
1035     delete $1; delete $3;
1036   }
1037   | Types '[' ']' {
1038     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1039     if (ATy == 0)
1040       ThrowException("Cannot make array constant with type: '" + 
1041                      (*$1)->getDescription() + "'!");
1042
1043     int NumElements = ATy->getNumElements();
1044     if (NumElements != -1 && NumElements != 0) 
1045       ThrowException("Type mismatch: constant sized array initialized with 0"
1046                      " arguments, but has size of " + itostr(NumElements) +"!");
1047     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1048     delete $1;
1049   }
1050   | Types 'c' STRINGCONSTANT {
1051     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1052     if (ATy == 0)
1053       ThrowException("Cannot make array constant with type: '" + 
1054                      (*$1)->getDescription() + "'!");
1055
1056     int NumElements = ATy->getNumElements();
1057     const Type *ETy = ATy->getElementType();
1058     char *EndStr = UnEscapeLexed($3, true);
1059     if (NumElements != -1 && NumElements != (EndStr-$3))
1060       ThrowException("Can't build string constant of size " + 
1061                      itostr((int)(EndStr-$3)) +
1062                      " when array has size " + itostr(NumElements) + "!");
1063     std::vector<Constant*> Vals;
1064     if (ETy == Type::SByteTy) {
1065       for (char *C = $3; C != EndStr; ++C)
1066         Vals.push_back(ConstantSInt::get(ETy, *C));
1067     } else if (ETy == Type::UByteTy) {
1068       for (char *C = $3; C != EndStr; ++C)
1069         Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1070     } else {
1071       free($3);
1072       ThrowException("Cannot build string arrays of non byte sized elements!");
1073     }
1074     free($3);
1075     $$ = ConstantArray::get(ATy, Vals);
1076     delete $1;
1077   }
1078   | Types '{' ConstVector '}' {
1079     const StructType *STy = dyn_cast<StructType>($1->get());
1080     if (STy == 0)
1081       ThrowException("Cannot make struct constant with type: '" + 
1082                      (*$1)->getDescription() + "'!");
1083
1084     if ($3->size() != STy->getNumContainedTypes())
1085       ThrowException("Illegal number of initializers for structure type!");
1086
1087     // Check to ensure that constants are compatible with the type initializer!
1088     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1089       if ((*$3)[i]->getType() != STy->getElementTypes()[i])
1090         ThrowException("Expected type '" +
1091                        STy->getElementTypes()[i]->getDescription() +
1092                        "' for element #" + utostr(i) +
1093                        " of structure initializer!");
1094
1095     $$ = ConstantStruct::get(STy, *$3);
1096     delete $1; delete $3;
1097   }
1098   | Types '{' '}' {
1099     const StructType *STy = dyn_cast<StructType>($1->get());
1100     if (STy == 0)
1101       ThrowException("Cannot make struct constant with type: '" + 
1102                      (*$1)->getDescription() + "'!");
1103
1104     if (STy->getNumContainedTypes() != 0)
1105       ThrowException("Illegal number of initializers for structure type!");
1106
1107     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1108     delete $1;
1109   }
1110   | Types NULL_TOK {
1111     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1112     if (PTy == 0)
1113       ThrowException("Cannot make null pointer constant with type: '" + 
1114                      (*$1)->getDescription() + "'!");
1115
1116     $$ = ConstantPointerNull::get(PTy);
1117     delete $1;
1118   }
1119   | Types SymbolicValueRef {
1120     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1121     if (Ty == 0)
1122       ThrowException("Global const reference must be a pointer type!");
1123
1124     // ConstExprs can exist in the body of a function, thus creating
1125     // ConstantPointerRefs whenever they refer to a variable.  Because we are in
1126     // the context of a function, getValNonImprovising will search the functions
1127     // symbol table instead of the module symbol table for the global symbol,
1128     // which throws things all off.  To get around this, we just tell
1129     // getValNonImprovising that we are at global scope here.
1130     //
1131     Function *SavedCurFn = CurFun.CurrentFunction;
1132     CurFun.CurrentFunction = 0;
1133
1134     Value *V = getValNonImprovising(Ty, $2);
1135
1136     CurFun.CurrentFunction = SavedCurFn;
1137
1138     // If this is an initializer for a constant pointer, which is referencing a
1139     // (currently) undefined variable, create a stub now that shall be replaced
1140     // in the future with the right type of variable.
1141     //
1142     if (V == 0) {
1143       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1144       const PointerType *PT = cast<PointerType>(Ty);
1145
1146       // First check to see if the forward references value is already created!
1147       PerModuleInfo::GlobalRefsType::iterator I =
1148         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1149     
1150       if (I != CurModule.GlobalRefs.end()) {
1151         V = I->second;             // Placeholder already exists, use it...
1152         $2.destroy();
1153       } else {
1154         // Create a placeholder for the global variable reference...
1155         GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1156                                                 false,
1157                                                 GlobalValue::ExternalLinkage);
1158         // Keep track of the fact that we have a forward ref to recycle it
1159         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1160
1161         // Must temporarily push this value into the module table...
1162         CurModule.CurrentModule->getGlobalList().push_back(GV);
1163         V = GV;
1164       }
1165     }
1166
1167     GlobalValue *GV = cast<GlobalValue>(V);
1168     $$ = ConstantPointerRef::get(GV);
1169     delete $1;            // Free the type handle
1170   }
1171   | Types ConstExpr {
1172     if ($1->get() != $2->getType())
1173       ThrowException("Mismatched types for constant expression!");
1174     $$ = $2;
1175     delete $1;
1176   }
1177   | Types ZEROINITIALIZER {
1178     $$ = Constant::getNullValue($1->get());
1179     delete $1;
1180   };
1181
1182 ConstVal : SIntType EINT64VAL {      // integral constants
1183     if (!ConstantSInt::isValueValidForType($1, $2))
1184       ThrowException("Constant value doesn't fit in type!");
1185     $$ = ConstantSInt::get($1, $2);
1186   }
1187   | UIntType EUINT64VAL {            // integral constants
1188     if (!ConstantUInt::isValueValidForType($1, $2))
1189       ThrowException("Constant value doesn't fit in type!");
1190     $$ = ConstantUInt::get($1, $2);
1191   }
1192   | BOOL TRUE {                      // Boolean constants
1193     $$ = ConstantBool::True;
1194   }
1195   | BOOL FALSE {                     // Boolean constants
1196     $$ = ConstantBool::False;
1197   }
1198   | FPType FPVAL {                   // Float & Double constants
1199     $$ = ConstantFP::get($1, $2);
1200   };
1201
1202
1203 ConstExpr: CAST '(' ConstVal TO Types ')' {
1204     if (!$3->getType()->isFirstClassType())
1205       ThrowException("cast constant expression from a non-primitive type: '" +
1206                      $3->getType()->getDescription() + "'!");
1207     if (!$5->get()->isFirstClassType())
1208       ThrowException("cast constant expression to a non-primitive type: '" +
1209                      $5->get()->getDescription() + "'!");
1210     $$ = ConstantExpr::getCast($3, $5->get());
1211     delete $5;
1212   }
1213   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1214     if (!isa<PointerType>($3->getType()))
1215       ThrowException("GetElementPtr requires a pointer operand!");
1216
1217     const Type *IdxTy =
1218       GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1219     if (!IdxTy)
1220       ThrowException("Index list invalid for constant getelementptr!");
1221
1222     std::vector<Constant*> IdxVec;
1223     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1224       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1225         IdxVec.push_back(C);
1226       else
1227         ThrowException("Indices to constant getelementptr must be constants!");
1228
1229     delete $4;
1230
1231     $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1232   }
1233   | BinaryOps '(' ConstVal ',' ConstVal ')' {
1234     if ($3->getType() != $5->getType())
1235       ThrowException("Binary operator types must match!");
1236     $$ = ConstantExpr::get($1, $3, $5);
1237   }
1238   | ShiftOps '(' ConstVal ',' ConstVal ')' {
1239     if ($5->getType() != Type::UByteTy)
1240       ThrowException("Shift count for shift constant must be unsigned byte!");
1241     if (!$3->getType()->isInteger())
1242       ThrowException("Shift constant expression requires integer operand!");
1243     $$ = ConstantExpr::get($1, $3, $5);
1244   };
1245
1246
1247 // ConstVector - A list of comma separated constants.
1248 ConstVector : ConstVector ',' ConstVal {
1249     ($$ = $1)->push_back($3);
1250   }
1251   | ConstVal {
1252     $$ = new std::vector<Constant*>();
1253     $$->push_back($1);
1254   };
1255
1256
1257 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1258 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1259
1260
1261 //===----------------------------------------------------------------------===//
1262 //                             Rules to match Modules
1263 //===----------------------------------------------------------------------===//
1264
1265 // Module rule: Capture the result of parsing the whole file into a result
1266 // variable...
1267 //
1268 Module : FunctionList {
1269   $$ = ParserResult = $1;
1270   CurModule.ModuleDone();
1271 };
1272
1273 // FunctionList - A list of functions, preceeded by a constant pool.
1274 //
1275 FunctionList : FunctionList Function {
1276     $$ = $1;
1277     assert($2->getParent() == 0 && "Function already in module!");
1278     $1->getFunctionList().push_back($2);
1279     CurFun.FunctionDone();
1280   } 
1281   | FunctionList FunctionProto {
1282     $$ = $1;
1283   }
1284   | FunctionList IMPLEMENTATION {
1285     $$ = $1;
1286   }
1287   | ConstPool {
1288     $$ = CurModule.CurrentModule;
1289     // Resolve circular types before we parse the body of the module
1290     ResolveTypes(CurModule.LateResolveTypes);
1291   };
1292
1293 // ConstPool - Constants with optional names assigned to them.
1294 ConstPool : ConstPool OptAssign CONST ConstVal { 
1295     if (!setValueName($4, $2))
1296       InsertValue($4);
1297   }
1298   | ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
1299     // Eagerly resolve types.  This is not an optimization, this is a
1300     // requirement that is due to the fact that we could have this:
1301     //
1302     // %list = type { %list * }
1303     // %list = type { %list * }    ; repeated type decl
1304     //
1305     // If types are not resolved eagerly, then the two types will not be
1306     // determined to be the same type!
1307     //
1308     ResolveTypeTo($2, $4->get());
1309
1310     // TODO: FIXME when Type are not const
1311     if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1312       // If this is not a redefinition of a type...
1313       if (!$2) {
1314         InsertType($4->get(),
1315                    inFunctionScope() ? CurFun.Types : CurModule.Types);
1316       }
1317     }
1318
1319     delete $4;
1320   }
1321   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1322   }
1323   | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1324     const Type *Ty = $5->getType();
1325     // Global declarations appear in Constant Pool
1326     Constant *Initializer = $5;
1327     if (Initializer == 0)
1328       ThrowException("Global value initializer is not a constant!");
1329     
1330     GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1331     if (!setValueName(GV, $2)) {   // If not redefining...
1332       CurModule.CurrentModule->getGlobalList().push_back(GV);
1333       int Slot = InsertValue(GV, CurModule.Values);
1334
1335       if (Slot != -1) {
1336         CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1337       } else {
1338         CurModule.DeclareNewGlobalValue(GV, ValID::create(
1339                                                 (char*)GV->getName().c_str()));
1340       }
1341     }
1342   }
1343   | ConstPool OptAssign EXTERNAL GlobalType Types {
1344     const Type *Ty = *$5;
1345     // Global declarations appear in Constant Pool
1346     GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1347     if (!setValueName(GV, $2)) {   // If not redefining...
1348       CurModule.CurrentModule->getGlobalList().push_back(GV);
1349       int Slot = InsertValue(GV, CurModule.Values);
1350
1351       if (Slot != -1) {
1352         CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1353       } else {
1354         assert(GV->hasName() && "Not named and not numbered!?");
1355         CurModule.DeclareNewGlobalValue(GV, ValID::create(
1356                                                 (char*)GV->getName().c_str()));
1357       }
1358     }
1359     delete $5;
1360   }
1361   | ConstPool TARGET TargetDefinition { 
1362   }
1363   | /* empty: end of list */ { 
1364   };
1365
1366
1367
1368 BigOrLittle : BIG    { $$ = Module::BigEndian; };
1369 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1370
1371 TargetDefinition : ENDIAN '=' BigOrLittle {
1372     CurModule.CurrentModule->setEndianness($3);
1373   }
1374   | POINTERSIZE '=' EUINT64VAL {
1375     if ($3 == 32)
1376       CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1377     else if ($3 == 64)
1378       CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1379     else
1380       ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1381   };
1382
1383
1384 //===----------------------------------------------------------------------===//
1385 //                       Rules to match Function Headers
1386 //===----------------------------------------------------------------------===//
1387
1388 Name : VAR_ID | STRINGCONSTANT;
1389 OptName : Name | /*empty*/ { $$ = 0; };
1390
1391 ArgVal : Types OptName {
1392   if (*$1 == Type::VoidTy)
1393     ThrowException("void typed arguments are invalid!");
1394   $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1395 };
1396
1397 ArgListH : ArgListH ',' ArgVal {
1398     $$ = $1;
1399     $1->push_back(*$3);
1400     delete $3;
1401   }
1402   | ArgVal {
1403     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1404     $$->push_back(*$1);
1405     delete $1;
1406   };
1407
1408 ArgList : ArgListH {
1409     $$ = $1;
1410   }
1411   | ArgListH ',' DOTDOTDOT {
1412     $$ = $1;
1413     $$->push_back(std::pair<PATypeHolder*,
1414                             char*>(new PATypeHolder(Type::VoidTy), 0));
1415   }
1416   | DOTDOTDOT {
1417     $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1418     $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1419   }
1420   | /* empty */ {
1421     $$ = 0;
1422   };
1423
1424 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1425   UnEscapeLexed($2);
1426   std::string FunctionName($2);
1427   
1428   if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1429     ThrowException("LLVM functions cannot return aggregate types!");
1430
1431   std::vector<const Type*> ParamTypeList;
1432   if ($4) {   // If there are arguments...
1433     for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1434          I != $4->end(); ++I)
1435       ParamTypeList.push_back(I->first->get());
1436   }
1437
1438   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1439   if (isVarArg) ParamTypeList.pop_back();
1440
1441   const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1442   const PointerType *PFT = PointerType::get(FT);
1443   delete $1;
1444
1445   Function *Fn = 0;
1446   // Is the function already in symtab?
1447   if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1448     // Yes it is.  If this is the case, either we need to be a forward decl,
1449     // or it needs to be.
1450     if (!CurFun.isDeclare && !Fn->isExternal())
1451       ThrowException("Redefinition of function '" + FunctionName + "'!");
1452     
1453     // If we found a preexisting function prototype, remove it from the
1454     // module, so that we don't get spurious conflicts with global & local
1455     // variables.
1456     //
1457     CurModule.CurrentModule->getFunctionList().remove(Fn);
1458
1459     // Make sure to strip off any argument names so we can't get conflicts...
1460     for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1461       AI->setName("");
1462
1463   } else  {  // Not already defined?
1464     Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName);
1465     InsertValue(Fn, CurModule.Values);
1466     CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1467   }
1468   free($2);  // Free strdup'd memory!
1469
1470   CurFun.FunctionStart(Fn);
1471
1472   // Add all of the arguments we parsed to the function...
1473   if ($4) {                     // Is null if empty...
1474     if (isVarArg) {  // Nuke the last entry
1475       assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1476              "Not a varargs marker!");
1477       delete $4->back().first;
1478       $4->pop_back();  // Delete the last entry
1479     }
1480     Function::aiterator ArgIt = Fn->abegin();
1481     for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1482          I != $4->end(); ++I, ++ArgIt) {
1483       delete I->first;                          // Delete the typeholder...
1484
1485       if (setValueName(ArgIt, I->second))       // Insert arg into symtab...
1486         assert(0 && "No arg redef allowed!");
1487       
1488       InsertValue(ArgIt);
1489     }
1490
1491     delete $4;                     // We're now done with the argument list
1492   }
1493 };
1494
1495 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1496
1497 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1498   $$ = CurFun.CurrentFunction;
1499
1500   // Make sure that we keep track of the linkage type even if there was a
1501   // previous "declare".
1502   $$->setLinkage($1);
1503
1504   // Resolve circular types before we parse the body of the function.
1505   ResolveTypes(CurFun.LateResolveTypes);
1506 };
1507
1508 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1509
1510 Function : BasicBlockList END {
1511   $$ = $1;
1512 };
1513
1514 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1515   $$ = CurFun.CurrentFunction;
1516   assert($$->getParent() == 0 && "Function already in module!");
1517   CurModule.CurrentModule->getFunctionList().push_back($$);
1518   CurFun.FunctionDone();
1519 };
1520
1521 //===----------------------------------------------------------------------===//
1522 //                        Rules to match Basic Blocks
1523 //===----------------------------------------------------------------------===//
1524
1525 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1526     $$ = ValID::create($1);
1527   }
1528   | EUINT64VAL {
1529     $$ = ValID::create($1);
1530   }
1531   | FPVAL {                     // Perhaps it's an FP constant?
1532     $$ = ValID::create($1);
1533   }
1534   | TRUE {
1535     $$ = ValID::create(ConstantBool::True);
1536   } 
1537   | FALSE {
1538     $$ = ValID::create(ConstantBool::False);
1539   }
1540   | NULL_TOK {
1541     $$ = ValID::createNull();
1542   }
1543   | ConstExpr {
1544     $$ = ValID::create($1);
1545   };
1546
1547 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1548 // another value.
1549 //
1550 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1551     $$ = ValID::create($1);
1552   }
1553   | Name {                   // Is it a named reference...?
1554     $$ = ValID::create($1);
1555   };
1556
1557 // ValueRef - A reference to a definition... either constant or symbolic
1558 ValueRef : SymbolicValueRef | ConstValueRef;
1559
1560
1561 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1562 // type immediately preceeds the value reference, and allows complex constant
1563 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1564 ResolvedVal : Types ValueRef {
1565     $$ = getVal(*$1, $2); delete $1;
1566   };
1567
1568 BasicBlockList : BasicBlockList BasicBlock {
1569     ($$ = $1)->getBasicBlockList().push_back($2);
1570   }
1571   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1572     ($$ = $1)->getBasicBlockList().push_back($2);
1573   };
1574
1575
1576 // Basic blocks are terminated by branching instructions: 
1577 // br, br/cc, switch, ret
1578 //
1579 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1580     if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1581     InsertValue($3);
1582
1583     $1->getInstList().push_back($3);
1584     InsertValue($1);
1585     $$ = $1;
1586   }
1587   | LABELSTR InstructionList OptAssign BBTerminatorInst  {
1588     if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1589     InsertValue($4);
1590
1591     $2->getInstList().push_back($4);
1592     if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1593
1594     InsertValue($2);
1595     $$ = $2;
1596   };
1597
1598 InstructionList : InstructionList Inst {
1599     $1->getInstList().push_back($2);
1600     $$ = $1;
1601   }
1602   | /* empty */ {
1603     $$ = CurBB = new BasicBlock();
1604   };
1605
1606 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1607     $$ = new ReturnInst($2);
1608   }
1609   | RET VOID {                                       // Return with no result...
1610     $$ = new ReturnInst();
1611   }
1612   | BR LABEL ValueRef {                         // Unconditional Branch...
1613     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1614   }                                                  // Conditional Branch...
1615   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1616     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)), 
1617                         cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1618                         getVal(Type::BoolTy, $3));
1619   }
1620   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1621     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1622                                    cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1623     $$ = S;
1624
1625     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1626       E = $8->end();
1627     for (; I != E; ++I)
1628       S->addCase(I->first, I->second);
1629   }
1630   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1631     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1632                                    cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1633     $$ = S;
1634   }
1635   | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal 
1636     UNWIND ResolvedVal {
1637     const PointerType *PFTy;
1638     const FunctionType *Ty;
1639
1640     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1641         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1642       // Pull out the types of all of the arguments...
1643       std::vector<const Type*> ParamTypes;
1644       if ($5) {
1645         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1646              I != E; ++I)
1647           ParamTypes.push_back((*I)->getType());
1648       }
1649
1650       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1651       if (isVarArg) ParamTypes.pop_back();
1652
1653       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1654       PFTy = PointerType::get(Ty);
1655     }
1656
1657     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
1658
1659     BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1660     BasicBlock *Except = dyn_cast<BasicBlock>($10);
1661
1662     if (Normal == 0 || Except == 0)
1663       ThrowException("Invoke instruction without label destinations!");
1664
1665     // Create the call node...
1666     if (!$5) {                                   // Has no arguments?
1667       $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1668     } else {                                     // Has arguments?
1669       // Loop through FunctionType's arguments and ensure they are specified
1670       // correctly!
1671       //
1672       FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1673       FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1674       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1675
1676       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1677         if ((*ArgI)->getType() != *I)
1678           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1679                          (*I)->getDescription() + "'!");
1680
1681       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1682         ThrowException("Invalid number of parameters detected!");
1683
1684       $$ = new InvokeInst(V, Normal, Except, *$5);
1685     }
1686     delete $2;
1687     delete $5;
1688   }
1689   | UNWIND {
1690     $$ = new UnwindInst();
1691   };
1692
1693
1694
1695 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1696     $$ = $1;
1697     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1698     if (V == 0)
1699       ThrowException("May only switch on a constant pool value!");
1700
1701     $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1702   }
1703   | IntType ConstValueRef ',' LABEL ValueRef {
1704     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1705     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1706
1707     if (V == 0)
1708       ThrowException("May only switch on a constant pool value!");
1709
1710     $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1711   };
1712
1713 Inst : OptAssign InstVal {
1714   // Is this definition named?? if so, assign the name...
1715   if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1716   InsertValue($2);
1717   $$ = $2;
1718 };
1719
1720 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1721     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1722     $$->push_back(std::make_pair(getVal(*$1, $3), 
1723                                  cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1724     delete $1;
1725   }
1726   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1727     $$ = $1;
1728     $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1729                                  cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1730   };
1731
1732
1733 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1734     $$ = new std::vector<Value*>();
1735     $$->push_back($1);
1736   }
1737   | ValueRefList ',' ResolvedVal {
1738     $$ = $1;
1739     $1->push_back($3);
1740   };
1741
1742 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1743 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1744
1745 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1746     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1747       ThrowException("Arithmetic operator requires integer or FP operands!");
1748     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1749     if ($$ == 0)
1750       ThrowException("binary operator returned null!");
1751     delete $2;
1752   }
1753   | LogicalOps Types ValueRef ',' ValueRef {
1754     if (!(*$2)->isIntegral())
1755       ThrowException("Logical operator requires integral operands!");
1756     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1757     if ($$ == 0)
1758       ThrowException("binary operator returned null!");
1759     delete $2;
1760   }
1761   | SetCondOps Types ValueRef ',' ValueRef {
1762     $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1763     if ($$ == 0)
1764       ThrowException("binary operator returned null!");
1765     delete $2;
1766   }
1767   | NOT ResolvedVal {
1768     std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1769               << " Replacing with 'xor'.\n";
1770
1771     Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1772     if (Ones == 0)
1773       ThrowException("Expected integral type for not instruction!");
1774
1775     $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1776     if ($$ == 0)
1777       ThrowException("Could not create a xor instruction!");
1778   }
1779   | ShiftOps ResolvedVal ',' ResolvedVal {
1780     if ($4->getType() != Type::UByteTy)
1781       ThrowException("Shift amount must be ubyte!");
1782     if (!$2->getType()->isInteger())
1783       ThrowException("Shift constant expression requires integer operand!");
1784     $$ = new ShiftInst($1, $2, $4);
1785   }
1786   | CAST ResolvedVal TO Types {
1787     if (!$4->get()->isFirstClassType())
1788       ThrowException("cast instruction to a non-primitive type: '" +
1789                      $4->get()->getDescription() + "'!");
1790     $$ = new CastInst($2, *$4);
1791     delete $4;
1792   }
1793   | VA_ARG ResolvedVal ',' Types {
1794     // FIXME: This is emulation code for an obsolete syntax.  This should be
1795     // removed at some point.
1796     if (!ObsoleteVarArgs) {
1797       std::cerr << "WARNING: this file uses obsolete features.  "
1798                 << "Assemble and disassemble to update it.\n";
1799       ObsoleteVarArgs = true;
1800     }
1801
1802     // First, load the valist...
1803     Instruction *CurVAList = new LoadInst($2, "");
1804     CurBB->getInstList().push_back(CurVAList);
1805
1806     // Emit the vaarg instruction.
1807     $$ = new VAArgInst(CurVAList, *$4);
1808     
1809     // Now we must advance the pointer and update it in memory.
1810     Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1811     CurBB->getInstList().push_back(TheVANext);
1812
1813     CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1814     delete $4;
1815   }
1816   | VAARG ResolvedVal ',' Types {
1817     $$ = new VAArgInst($2, *$4);
1818     delete $4;
1819   }
1820   | VANEXT ResolvedVal ',' Types {
1821     $$ = new VANextInst($2, *$4);
1822     delete $4;
1823   }
1824   | PHI_TOK PHIList {
1825     const Type *Ty = $2->front().first->getType();
1826     if (!Ty->isFirstClassType())
1827       ThrowException("PHI node operands must be of first class type!");
1828     $$ = new PHINode(Ty);
1829     $$->op_reserve($2->size()*2);
1830     while ($2->begin() != $2->end()) {
1831       if ($2->front().first->getType() != Ty) 
1832         ThrowException("All elements of a PHI node must be of the same type!");
1833       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1834       $2->pop_front();
1835     }
1836     delete $2;  // Free the list...
1837   } 
1838   | CALL TypesV ValueRef '(' ValueRefListE ')' {
1839     const PointerType *PFTy;
1840     const FunctionType *Ty;
1841
1842     if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1843         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1844       // Pull out the types of all of the arguments...
1845       std::vector<const Type*> ParamTypes;
1846       if ($5) {
1847         for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1848              I != E; ++I)
1849           ParamTypes.push_back((*I)->getType());
1850       }
1851
1852       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1853       if (isVarArg) ParamTypes.pop_back();
1854
1855       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1856       PFTy = PointerType::get(Ty);
1857     }
1858
1859     Value *V = getVal(PFTy, $3);   // Get the function we're calling...
1860
1861     // Create the call node...
1862     if (!$5) {                                   // Has no arguments?
1863       // Make sure no arguments is a good thing!
1864       if (Ty->getNumParams() != 0)
1865         ThrowException("No arguments passed to a function that "
1866                        "expects arguments!");
1867
1868       $$ = new CallInst(V, std::vector<Value*>());
1869     } else {                                     // Has arguments?
1870       // Loop through FunctionType's arguments and ensure they are specified
1871       // correctly!
1872       //
1873       FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1874       FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1875       std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1876
1877       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1878         if ((*ArgI)->getType() != *I)
1879           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1880                          (*I)->getDescription() + "'!");
1881
1882       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1883         ThrowException("Invalid number of parameters detected!");
1884
1885       $$ = new CallInst(V, *$5);
1886     }
1887     delete $2;
1888     delete $5;
1889   }
1890   | MemoryInst {
1891     $$ = $1;
1892   };
1893
1894
1895 // IndexList - List of indices for GEP based instructions...
1896 IndexList : ',' ValueRefList { 
1897     $$ = $2; 
1898   } | /* empty */ { 
1899     $$ = new std::vector<Value*>(); 
1900   };
1901
1902 OptVolatile : VOLATILE {
1903     $$ = true;
1904   }
1905   | /* empty */ {
1906     $$ = false;
1907   };
1908
1909
1910 MemoryInst : MALLOC Types {
1911     $$ = new MallocInst(*$2);
1912     delete $2;
1913   }
1914   | MALLOC Types ',' UINT ValueRef {
1915     $$ = new MallocInst(*$2, getVal($4, $5));
1916     delete $2;
1917   }
1918   | ALLOCA Types {
1919     $$ = new AllocaInst(*$2);
1920     delete $2;
1921   }
1922   | ALLOCA Types ',' UINT ValueRef {
1923     $$ = new AllocaInst(*$2, getVal($4, $5));
1924     delete $2;
1925   }
1926   | FREE ResolvedVal {
1927     if (!isa<PointerType>($2->getType()))
1928       ThrowException("Trying to free nonpointer type " + 
1929                      $2->getType()->getDescription() + "!");
1930     $$ = new FreeInst($2);
1931   }
1932
1933   | OptVolatile LOAD Types ValueRef {
1934     if (!isa<PointerType>($3->get()))
1935       ThrowException("Can't load from nonpointer type: " +
1936                      (*$3)->getDescription());
1937     $$ = new LoadInst(getVal(*$3, $4), "", $1);
1938     delete $3;
1939   }
1940   | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1941     const PointerType *PT = dyn_cast<PointerType>($5->get());
1942     if (!PT)
1943       ThrowException("Can't store to a nonpointer type: " +
1944                      (*$5)->getDescription());
1945     const Type *ElTy = PT->getElementType();
1946     if (ElTy != $3->getType())
1947       ThrowException("Can't store '" + $3->getType()->getDescription() +
1948                      "' into space of type '" + ElTy->getDescription() + "'!");
1949
1950     $$ = new StoreInst($3, getVal(*$5, $6), $1);
1951     delete $5;
1952   }
1953   | GETELEMENTPTR Types ValueRef IndexList {
1954     if (!isa<PointerType>($2->get()))
1955       ThrowException("getelementptr insn requires pointer operand!");
1956     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1957       ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1958     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1959     delete $2; delete $4;
1960   };
1961
1962
1963 %%
1964 int yyerror(const char *ErrorMsg) {
1965   std::string where 
1966     = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1967                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1968   std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1969   if (yychar == YYEMPTY)
1970     errMsg += "end-of-file.";
1971   else
1972     errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
1973   ThrowException(errMsg);
1974   return 0;
1975 }