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