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