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