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