Rename some GC classes so that their roll will hopefully be clearer.
[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 is distributed under the University of Illinois Open Source
6 // 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/ValueSymbolTable.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
28 #include <algorithm>
29 #include <list>
30 #include <map>
31 #include <utility>
32
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each 
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR 
38 // (a goto) to put YACC in error state. Furthermore, several calls to 
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a 
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
47
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex();                       // declaration" of xxx warnings.
50 int yyparse();
51 using namespace llvm;
52
53 static Module *ParserResult;
54
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
57 //
58 //#define DEBUG_UPREFS 1
59 #ifdef DEBUG_UPREFS
60 #define UR_OUT(X) cerr << X
61 #else
62 #define UR_OUT(X)
63 #endif
64
65 #define YYERROR_VERBOSE 1
66
67 static GlobalVariable *CurGV;
68
69
70 // This contains info used when building the body of a function.  It is
71 // destroyed when the function is completed.
72 //
73 typedef std::vector<Value *> ValueList;           // Numbered defs
74
75 static void 
76 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
77
78 static struct PerModuleInfo {
79   Module *CurrentModule;
80   ValueList Values; // Module level numbered definitions
81   ValueList LateResolveValues;
82   std::vector<PATypeHolder>    Types;
83   std::map<ValID, PATypeHolder> LateResolveTypes;
84
85   /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86   /// how they were referenced and on which line of the input they came from so
87   /// that we can resolve them later and print error messages as appropriate.
88   std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
89
90   // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91   // references to global values.  Global values may be referenced before they
92   // are defined, and if so, the temporary object that they represent is held
93   // here.  This is used for forward references of GlobalValues.
94   //
95   typedef std::map<std::pair<const PointerType *,
96                              ValID>, GlobalValue*> GlobalRefsType;
97   GlobalRefsType GlobalRefs;
98
99   void ModuleDone() {
100     // If we could not resolve some functions at function compilation time
101     // (calls to functions before they are defined), resolve them now...  Types
102     // are resolved when the constant pool has been completely parsed.
103     //
104     ResolveDefinitions(LateResolveValues);
105     if (TriggerError)
106       return;
107
108     // Check to make sure that all global value forward references have been
109     // resolved!
110     //
111     if (!GlobalRefs.empty()) {
112       std::string UndefinedReferences = "Unresolved global references exist:\n";
113
114       for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115            I != E; ++I) {
116         UndefinedReferences += "  " + I->first.first->getDescription() + " " +
117                                I->first.second.getName() + "\n";
118       }
119       GenerateError(UndefinedReferences);
120       return;
121     }
122
123     // Look for intrinsic functions and CallInst that need to be upgraded
124     for (Module::iterator FI = CurrentModule->begin(),
125          FE = CurrentModule->end(); FI != FE; )
126       UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
127
128     Values.clear();         // Clear out function local definitions
129     Types.clear();
130     CurrentModule = 0;
131   }
132
133   // GetForwardRefForGlobal - Check to see if there is a forward reference
134   // for this global.  If so, remove it from the GlobalRefs map and return it.
135   // If not, just return null.
136   GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137     // Check to see if there is a forward reference to this global variable...
138     // if there is, eliminate it and patch the reference to use the new def'n.
139     GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140     GlobalValue *Ret = 0;
141     if (I != GlobalRefs.end()) {
142       Ret = I->second;
143       GlobalRefs.erase(I);
144     }
145     return Ret;
146   }
147
148   bool TypeIsUnresolved(PATypeHolder* PATy) {
149     // If it isn't abstract, its resolved
150     const Type* Ty = PATy->get();
151     if (!Ty->isAbstract())
152       return false;
153     // Traverse the type looking for abstract types. If it isn't abstract then
154     // we don't need to traverse that leg of the type. 
155     std::vector<const Type*> WorkList, SeenList;
156     WorkList.push_back(Ty);
157     while (!WorkList.empty()) {
158       const Type* Ty = WorkList.back();
159       SeenList.push_back(Ty);
160       WorkList.pop_back();
161       if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162         // Check to see if this is an unresolved type
163         std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164         std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165         for ( ; I != E; ++I) {
166           if (I->second.get() == OpTy)
167             return true;
168         }
169       } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170         const Type* TheTy = SeqTy->getElementType();
171         if (TheTy->isAbstract() && TheTy != Ty) {
172           std::vector<const Type*>::iterator I = SeenList.begin(), 
173                                              E = SeenList.end();
174           for ( ; I != E; ++I)
175             if (*I == TheTy)
176               break;
177           if (I == E)
178             WorkList.push_back(TheTy);
179         }
180       } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181         for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182           const Type* TheTy = StrTy->getElementType(i);
183           if (TheTy->isAbstract() && TheTy != Ty) {
184             std::vector<const Type*>::iterator I = SeenList.begin(), 
185                                                E = SeenList.end();
186             for ( ; I != E; ++I)
187               if (*I == TheTy)
188                 break;
189             if (I == E)
190               WorkList.push_back(TheTy);
191           }
192         }
193       }
194     }
195     return false;
196   }
197 } CurModule;
198
199 static struct PerFunctionInfo {
200   Function *CurrentFunction;     // Pointer to current function being created
201
202   ValueList Values; // Keep track of #'d definitions
203   unsigned NextValNum;
204   ValueList LateResolveValues;
205   bool isDeclare;                   // Is this function a forward declararation?
206   GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207   GlobalValue::VisibilityTypes Visibility;
208
209   /// BBForwardRefs - When we see forward references to basic blocks, keep
210   /// track of them here.
211   std::map<ValID, BasicBlock*> BBForwardRefs;
212
213   inline PerFunctionInfo() {
214     CurrentFunction = 0;
215     isDeclare = false;
216     Linkage = GlobalValue::ExternalLinkage;
217     Visibility = GlobalValue::DefaultVisibility;
218   }
219
220   inline void FunctionStart(Function *M) {
221     CurrentFunction = M;
222     NextValNum = 0;
223   }
224
225   void FunctionDone() {
226     // Any forward referenced blocks left?
227     if (!BBForwardRefs.empty()) {
228       GenerateError("Undefined reference to label " +
229                      BBForwardRefs.begin()->second->getName());
230       return;
231     }
232
233     // Resolve all forward references now.
234     ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
235
236     Values.clear();         // Clear out function local definitions
237     BBForwardRefs.clear();
238     CurrentFunction = 0;
239     isDeclare = false;
240     Linkage = GlobalValue::ExternalLinkage;
241     Visibility = GlobalValue::DefaultVisibility;
242   }
243 } CurFun;  // Info for the current function...
244
245 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
246
247
248 //===----------------------------------------------------------------------===//
249 //               Code to handle definitions of all the types
250 //===----------------------------------------------------------------------===//
251
252 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
253   // Things that have names or are void typed don't get slot numbers
254   if (V->hasName() || (V->getType() == Type::VoidTy))
255     return;
256
257   // In the case of function values, we have to allow for the forward reference
258   // of basic blocks, which are included in the numbering. Consequently, we keep
259   // track of the next insertion location with NextValNum. When a BB gets 
260   // inserted, it could change the size of the CurFun.Values vector.
261   if (&ValueTab == &CurFun.Values) {
262     if (ValueTab.size() <= CurFun.NextValNum)
263       ValueTab.resize(CurFun.NextValNum+1);
264     ValueTab[CurFun.NextValNum++] = V;
265     return;
266   } 
267   // For all other lists, its okay to just tack it on the back of the vector.
268   ValueTab.push_back(V);
269 }
270
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
272   switch (D.Type) {
273   case ValID::LocalID:               // Is it a numbered definition?
274     // Module constants occupy the lowest numbered slots...
275     if (D.Num < CurModule.Types.size())
276       return CurModule.Types[D.Num];
277     break;
278   case ValID::LocalName:                 // Is it a named definition?
279     if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
280       D.destroy();  // Free old strdup'd memory...
281       return N;
282     }
283     break;
284   default:
285     GenerateError("Internal parser error: Invalid symbol type reference");
286     return 0;
287   }
288
289   // If we reached here, we referenced either a symbol that we don't know about
290   // or an id number that hasn't been read yet.  We may be referencing something
291   // forward, so just create an entry to be resolved later and get to it...
292   //
293   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
294
295
296   if (inFunctionScope()) {
297     if (D.Type == ValID::LocalName) {
298       GenerateError("Reference to an undefined type: '" + D.getName() + "'");
299       return 0;
300     } else {
301       GenerateError("Reference to an undefined type: #" + utostr(D.Num));
302       return 0;
303     }
304   }
305
306   std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307   if (I != CurModule.LateResolveTypes.end())
308     return I->second;
309
310   Type *Typ = OpaqueType::get();
311   CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
312   return Typ;
313  }
314
315 // getExistingVal - Look up the value specified by the provided type and
316 // the provided ValID.  If the value exists and has already been defined, return
317 // it.  Otherwise return null.
318 //
319 static Value *getExistingVal(const Type *Ty, const ValID &D) {
320   if (isa<FunctionType>(Ty)) {
321     GenerateError("Functions are not values and "
322                    "must be referenced as pointers");
323     return 0;
324   }
325
326   switch (D.Type) {
327   case ValID::LocalID: {                 // Is it a numbered definition?
328     // Check that the number is within bounds.
329     if (D.Num >= CurFun.Values.size()) 
330       return 0;
331     Value *Result = CurFun.Values[D.Num];
332     if (Ty != Result->getType()) {
333       GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
334                     Result->getType()->getDescription() + "' does not match " 
335                     "expected type, '" + Ty->getDescription() + "'");
336       return 0;
337     }
338     return Result;
339   }
340   case ValID::GlobalID: {                 // Is it a numbered definition?
341     if (D.Num >= CurModule.Values.size()) 
342       return 0;
343     Value *Result = CurModule.Values[D.Num];
344     if (Ty != Result->getType()) {
345       GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
346                     Result->getType()->getDescription() + "' does not match " 
347                     "expected type, '" + Ty->getDescription() + "'");
348       return 0;
349     }
350     return Result;
351   }
352     
353   case ValID::LocalName: {                // Is it a named definition?
354     if (!inFunctionScope()) 
355       return 0;
356     ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
357     Value *N = SymTab.lookup(D.getName());
358     if (N == 0) 
359       return 0;
360     if (N->getType() != Ty)
361       return 0;
362     
363     D.destroy();  // Free old strdup'd memory...
364     return N;
365   }
366   case ValID::GlobalName: {                // Is it a named definition?
367     ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
368     Value *N = SymTab.lookup(D.getName());
369     if (N == 0) 
370       return 0;
371     if (N->getType() != Ty)
372       return 0;
373
374     D.destroy();  // Free old strdup'd memory...
375     return N;
376   }
377
378   // Check to make sure that "Ty" is an integral type, and that our
379   // value will fit into the specified type...
380   case ValID::ConstSIntVal:    // Is it a constant pool reference??
381     if (!isa<IntegerType>(Ty) ||
382         !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
383       GenerateError("Signed integral constant '" +
384                      itostr(D.ConstPool64) + "' is invalid for type '" +
385                      Ty->getDescription() + "'");
386       return 0;
387     }
388     return ConstantInt::get(Ty, D.ConstPool64, true);
389
390   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
391     if (isa<IntegerType>(Ty) &&
392         ConstantInt::isValueValidForType(Ty, D.UConstPool64))
393       return ConstantInt::get(Ty, D.UConstPool64);
394
395     if (!isa<IntegerType>(Ty) ||
396         !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397       GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398                     "' is invalid or out of range for type '" +
399                     Ty->getDescription() + "'");
400       return 0;
401     }
402     // This is really a signed reference.  Transmogrify.
403     return ConstantInt::get(Ty, D.ConstPool64, true);
404
405   case ValID::ConstAPInt:     // Is it an unsigned const pool reference?
406     if (!isa<IntegerType>(Ty)) {
407       GenerateError("Integral constant '" + D.getName() +
408                     "' is invalid or out of range for type '" +
409                     Ty->getDescription() + "'");
410       return 0;
411     }
412       
413     {
414       APSInt Tmp = *D.ConstPoolInt;
415       Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
416       return ConstantInt::get(Tmp);
417     }
418       
419   case ValID::ConstFPVal:        // Is it a floating point const pool reference?
420     if (!Ty->isFloatingPoint() ||
421         !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
422       GenerateError("FP constant invalid for type");
423       return 0;
424     }
425     // Lexer has no type info, so builds all float and double FP constants 
426     // as double.  Fix this here.  Long double does not need this.
427     if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
428         Ty==Type::FloatTy)
429       D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
430     return ConstantFP::get(*D.ConstPoolFP);
431
432   case ValID::ConstNullVal:      // Is it a null value?
433     if (!isa<PointerType>(Ty)) {
434       GenerateError("Cannot create a a non pointer null");
435       return 0;
436     }
437     return ConstantPointerNull::get(cast<PointerType>(Ty));
438
439   case ValID::ConstUndefVal:      // Is it an undef value?
440     return UndefValue::get(Ty);
441
442   case ValID::ConstZeroVal:      // Is it a zero value?
443     return Constant::getNullValue(Ty);
444     
445   case ValID::ConstantVal:       // Fully resolved constant?
446     if (D.ConstantValue->getType() != Ty) {
447       GenerateError("Constant expression type different from required type");
448       return 0;
449     }
450     return D.ConstantValue;
451
452   case ValID::InlineAsmVal: {    // Inline asm expression
453     const PointerType *PTy = dyn_cast<PointerType>(Ty);
454     const FunctionType *FTy =
455       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
456     if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
457       GenerateError("Invalid type for asm constraint string");
458       return 0;
459     }
460     InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
461                                    D.IAD->HasSideEffects);
462     D.destroy();   // Free InlineAsmDescriptor.
463     return IA;
464   }
465   default:
466     assert(0 && "Unhandled case!");
467     return 0;
468   }   // End of switch
469
470   assert(0 && "Unhandled case!");
471   return 0;
472 }
473
474 // getVal - This function is identical to getExistingVal, except that if a
475 // value is not already defined, it "improvises" by creating a placeholder var
476 // that looks and acts just like the requested variable.  When the value is
477 // defined later, all uses of the placeholder variable are replaced with the
478 // real thing.
479 //
480 static Value *getVal(const Type *Ty, const ValID &ID) {
481   if (Ty == Type::LabelTy) {
482     GenerateError("Cannot use a basic block here");
483     return 0;
484   }
485
486   // See if the value has already been defined.
487   Value *V = getExistingVal(Ty, ID);
488   if (V) return V;
489   if (TriggerError) return 0;
490
491   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
492     GenerateError("Invalid use of a non-first-class type");
493     return 0;
494   }
495
496   // If we reached here, we referenced either a symbol that we don't know about
497   // or an id number that hasn't been read yet.  We may be referencing something
498   // forward, so just create an entry to be resolved later and get to it...
499   //
500   switch (ID.Type) {
501   case ValID::GlobalName:
502   case ValID::GlobalID: {
503    const PointerType *PTy = dyn_cast<PointerType>(Ty);
504    if (!PTy) {
505      GenerateError("Invalid type for reference to global" );
506      return 0;
507    }
508    const Type* ElTy = PTy->getElementType();
509    if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
510      V = Function::Create(FTy, GlobalValue::ExternalLinkage);
511    else
512      V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
513                             (Module*)0, false, PTy->getAddressSpace());
514    break;
515   }
516   default:
517    V = new Argument(Ty);
518   }
519   
520   // Remember where this forward reference came from.  FIXME, shouldn't we try
521   // to recycle these things??
522   CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
523                                                               LLLgetLineNo())));
524
525   if (inFunctionScope())
526     InsertValue(V, CurFun.LateResolveValues);
527   else
528     InsertValue(V, CurModule.LateResolveValues);
529   return V;
530 }
531
532 /// defineBBVal - This is a definition of a new basic block with the specified
533 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
534 static BasicBlock *defineBBVal(const ValID &ID) {
535   assert(inFunctionScope() && "Can't get basic block at global scope!");
536
537   BasicBlock *BB = 0;
538
539   // First, see if this was forward referenced
540
541   std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
542   if (BBI != CurFun.BBForwardRefs.end()) {
543     BB = BBI->second;
544     // The forward declaration could have been inserted anywhere in the
545     // function: insert it into the correct place now.
546     CurFun.CurrentFunction->getBasicBlockList().remove(BB);
547     CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
548
549     // We're about to erase the entry, save the key so we can clean it up.
550     ValID Tmp = BBI->first;
551
552     // Erase the forward ref from the map as its no longer "forward"
553     CurFun.BBForwardRefs.erase(ID);
554
555     // The key has been removed from the map but so we don't want to leave 
556     // strdup'd memory around so destroy it too.
557     Tmp.destroy();
558
559     // If its a numbered definition, bump the number and set the BB value.
560     if (ID.Type == ValID::LocalID) {
561       assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
562       InsertValue(BB);
563     }
564   } else { 
565     // We haven't seen this BB before and its first mention is a definition. 
566     // Just create it and return it.
567     std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
568     BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
569     if (ID.Type == ValID::LocalID) {
570       assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
571       InsertValue(BB);
572     }
573   }
574
575   ID.destroy();
576   return BB;
577 }
578
579 /// getBBVal - get an existing BB value or create a forward reference for it.
580 /// 
581 static BasicBlock *getBBVal(const ValID &ID) {
582   assert(inFunctionScope() && "Can't get basic block at global scope!");
583
584   BasicBlock *BB =  0;
585
586   std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
587   if (BBI != CurFun.BBForwardRefs.end()) {
588     BB = BBI->second;
589   } if (ID.Type == ValID::LocalName) {
590     std::string Name = ID.getName();
591     Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
592     if (N) {
593       if (N->getType()->getTypeID() == Type::LabelTyID)
594         BB = cast<BasicBlock>(N);
595       else
596         GenerateError("Reference to label '" + Name + "' is actually of type '"+
597           N->getType()->getDescription() + "'");
598     }
599   } else if (ID.Type == ValID::LocalID) {
600     if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
601       if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
602         BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
603       else
604         GenerateError("Reference to label '%" + utostr(ID.Num) + 
605           "' is actually of type '"+ 
606           CurFun.Values[ID.Num]->getType()->getDescription() + "'");
607     }
608   } else {
609     GenerateError("Illegal label reference " + ID.getName());
610     return 0;
611   }
612
613   // If its already been defined, return it now.
614   if (BB) {
615     ID.destroy(); // Free strdup'd memory.
616     return BB;
617   }
618
619   // Otherwise, this block has not been seen before, create it.
620   std::string Name;
621   if (ID.Type == ValID::LocalName)
622     Name = ID.getName();
623   BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
624
625   // Insert it in the forward refs map.
626   CurFun.BBForwardRefs[ID] = BB;
627
628   return BB;
629 }
630
631
632 //===----------------------------------------------------------------------===//
633 //              Code to handle forward references in instructions
634 //===----------------------------------------------------------------------===//
635 //
636 // This code handles the late binding needed with statements that reference
637 // values not defined yet... for example, a forward branch, or the PHI node for
638 // a loop body.
639 //
640 // This keeps a table (CurFun.LateResolveValues) of all such forward references
641 // and back patchs after we are done.
642 //
643
644 // ResolveDefinitions - If we could not resolve some defs at parsing
645 // time (forward branches, phi functions for loops, etc...) resolve the
646 // defs now...
647 //
648 static void 
649 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
650   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
651   while (!LateResolvers.empty()) {
652     Value *V = LateResolvers.back();
653     LateResolvers.pop_back();
654
655     std::map<Value*, std::pair<ValID, int> >::iterator PHI =
656       CurModule.PlaceHolderInfo.find(V);
657     assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
658
659     ValID &DID = PHI->second.first;
660
661     Value *TheRealValue = getExistingVal(V->getType(), DID);
662     if (TriggerError)
663       return;
664     if (TheRealValue) {
665       V->replaceAllUsesWith(TheRealValue);
666       delete V;
667       CurModule.PlaceHolderInfo.erase(PHI);
668     } else if (FutureLateResolvers) {
669       // Functions have their unresolved items forwarded to the module late
670       // resolver table
671       InsertValue(V, *FutureLateResolvers);
672     } else {
673       if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
674         GenerateError("Reference to an invalid definition: '" +DID.getName()+
675                        "' of type '" + V->getType()->getDescription() + "'",
676                        PHI->second.second);
677         return;
678       } else {
679         GenerateError("Reference to an invalid definition: #" +
680                        itostr(DID.Num) + " of type '" +
681                        V->getType()->getDescription() + "'",
682                        PHI->second.second);
683         return;
684       }
685     }
686   }
687   LateResolvers.clear();
688 }
689
690 // ResolveTypeTo - A brand new type was just declared.  This means that (if
691 // name is not null) things referencing Name can be resolved.  Otherwise, things
692 // refering to the number can be resolved.  Do this now.
693 //
694 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
695   ValID D;
696   if (Name)
697     D = ValID::createLocalName(*Name);
698   else      
699     D = ValID::createLocalID(CurModule.Types.size());
700
701   std::map<ValID, PATypeHolder>::iterator I =
702     CurModule.LateResolveTypes.find(D);
703   if (I != CurModule.LateResolveTypes.end()) {
704     ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
705     CurModule.LateResolveTypes.erase(I);
706   }
707 }
708
709 // setValueName - Set the specified value to the name given.  The name may be
710 // null potentially, in which case this is a noop.  The string passed in is
711 // assumed to be a malloc'd string buffer, and is free'd by this function.
712 //
713 static void setValueName(Value *V, std::string *NameStr) {
714   if (!NameStr) return;
715   std::string Name(*NameStr);      // Copy string
716   delete NameStr;                  // Free old string
717
718   if (V->getType() == Type::VoidTy) {
719     GenerateError("Can't assign name '" + Name+"' to value with void type");
720     return;
721   }
722
723   assert(inFunctionScope() && "Must be in function scope!");
724   ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
725   if (ST.lookup(Name)) {
726     GenerateError("Redefinition of value '" + Name + "' of type '" +
727                    V->getType()->getDescription() + "'");
728     return;
729   }
730
731   // Set the name.
732   V->setName(Name);
733 }
734
735 /// ParseGlobalVariable - Handle parsing of a global.  If Initializer is null,
736 /// this is a declaration, otherwise it is a definition.
737 static GlobalVariable *
738 ParseGlobalVariable(std::string *NameStr,
739                     GlobalValue::LinkageTypes Linkage,
740                     GlobalValue::VisibilityTypes Visibility,
741                     bool isConstantGlobal, const Type *Ty,
742                     Constant *Initializer, bool IsThreadLocal,
743                     unsigned AddressSpace = 0) {
744   if (isa<FunctionType>(Ty)) {
745     GenerateError("Cannot declare global vars of function type");
746     return 0;
747   }
748   if (Ty == Type::LabelTy) {
749     GenerateError("Cannot declare global vars of label type");
750     return 0;
751   }
752
753   const PointerType *PTy = PointerType::get(Ty, AddressSpace);
754
755   std::string Name;
756   if (NameStr) {
757     Name = *NameStr;      // Copy string
758     delete NameStr;       // Free old string
759   }
760
761   // See if this global value was forward referenced.  If so, recycle the
762   // object.
763   ValID ID;
764   if (!Name.empty()) {
765     ID = ValID::createGlobalName(Name);
766   } else {
767     ID = ValID::createGlobalID(CurModule.Values.size());
768   }
769
770   if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
771     // Move the global to the end of the list, from whereever it was
772     // previously inserted.
773     GlobalVariable *GV = cast<GlobalVariable>(FWGV);
774     CurModule.CurrentModule->getGlobalList().remove(GV);
775     CurModule.CurrentModule->getGlobalList().push_back(GV);
776     GV->setInitializer(Initializer);
777     GV->setLinkage(Linkage);
778     GV->setVisibility(Visibility);
779     GV->setConstant(isConstantGlobal);
780     GV->setThreadLocal(IsThreadLocal);
781     InsertValue(GV, CurModule.Values);
782     return GV;
783   }
784
785   // If this global has a name
786   if (!Name.empty()) {
787     // if the global we're parsing has an initializer (is a definition) and
788     // has external linkage.
789     if (Initializer && Linkage != GlobalValue::InternalLinkage)
790       // If there is already a global with external linkage with this name
791       if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
792         // If we allow this GVar to get created, it will be renamed in the
793         // symbol table because it conflicts with an existing GVar. We can't
794         // allow redefinition of GVars whose linking indicates that their name
795         // must stay the same. Issue the error.
796         GenerateError("Redefinition of global variable named '" + Name +
797                        "' of type '" + Ty->getDescription() + "'");
798         return 0;
799       }
800   }
801
802   // Otherwise there is no existing GV to use, create one now.
803   GlobalVariable *GV =
804     new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
805                        CurModule.CurrentModule, IsThreadLocal, AddressSpace);
806   GV->setVisibility(Visibility);
807   InsertValue(GV, CurModule.Values);
808   return GV;
809 }
810
811 // setTypeName - Set the specified type to the name given.  The name may be
812 // null potentially, in which case this is a noop.  The string passed in is
813 // assumed to be a malloc'd string buffer, and is freed by this function.
814 //
815 // This function returns true if the type has already been defined, but is
816 // allowed to be redefined in the specified context.  If the name is a new name
817 // for the type plane, it is inserted and false is returned.
818 static bool setTypeName(const Type *T, std::string *NameStr) {
819   assert(!inFunctionScope() && "Can't give types function-local names!");
820   if (NameStr == 0) return false;
821  
822   std::string Name(*NameStr);      // Copy string
823   delete NameStr;                  // Free old string
824
825   // We don't allow assigning names to void type
826   if (T == Type::VoidTy) {
827     GenerateError("Can't assign name '" + Name + "' to the void type");
828     return false;
829   }
830
831   // Set the type name, checking for conflicts as we do so.
832   bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
833
834   if (AlreadyExists) {   // Inserting a name that is already defined???
835     const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
836     assert(Existing && "Conflict but no matching type?!");
837
838     // There is only one case where this is allowed: when we are refining an
839     // opaque type.  In this case, Existing will be an opaque type.
840     if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
841       // We ARE replacing an opaque type!
842       const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
843       return true;
844     }
845
846     // Otherwise, this is an attempt to redefine a type. That's okay if
847     // the redefinition is identical to the original. This will be so if
848     // Existing and T point to the same Type object. In this one case we
849     // allow the equivalent redefinition.
850     if (Existing == T) return true;  // Yes, it's equal.
851
852     // Any other kind of (non-equivalent) redefinition is an error.
853     GenerateError("Redefinition of type named '" + Name + "' of type '" +
854                    T->getDescription() + "'");
855   }
856
857   return false;
858 }
859
860 //===----------------------------------------------------------------------===//
861 // Code for handling upreferences in type names...
862 //
863
864 // TypeContains - Returns true if Ty directly contains E in it.
865 //
866 static bool TypeContains(const Type *Ty, const Type *E) {
867   return std::find(Ty->subtype_begin(), Ty->subtype_end(),
868                    E) != Ty->subtype_end();
869 }
870
871 namespace {
872   struct UpRefRecord {
873     // NestingLevel - The number of nesting levels that need to be popped before
874     // this type is resolved.
875     unsigned NestingLevel;
876
877     // LastContainedTy - This is the type at the current binding level for the
878     // type.  Every time we reduce the nesting level, this gets updated.
879     const Type *LastContainedTy;
880
881     // UpRefTy - This is the actual opaque type that the upreference is
882     // represented with.
883     OpaqueType *UpRefTy;
884
885     UpRefRecord(unsigned NL, OpaqueType *URTy)
886       : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
887   };
888 }
889
890 // UpRefs - A list of the outstanding upreferences that need to be resolved.
891 static std::vector<UpRefRecord> UpRefs;
892
893 /// HandleUpRefs - Every time we finish a new layer of types, this function is
894 /// called.  It loops through the UpRefs vector, which is a list of the
895 /// currently active types.  For each type, if the up reference is contained in
896 /// the newly completed type, we decrement the level count.  When the level
897 /// count reaches zero, the upreferenced type is the type that is passed in:
898 /// thus we can complete the cycle.
899 ///
900 static PATypeHolder HandleUpRefs(const Type *ty) {
901   // If Ty isn't abstract, or if there are no up-references in it, then there is
902   // nothing to resolve here.
903   if (!ty->isAbstract() || UpRefs.empty()) return ty;
904   
905   PATypeHolder Ty(ty);
906   UR_OUT("Type '" << Ty->getDescription() <<
907          "' newly formed.  Resolving upreferences.\n" <<
908          UpRefs.size() << " upreferences active!\n");
909
910   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
911   // to zero), we resolve them all together before we resolve them to Ty.  At
912   // the end of the loop, if there is anything to resolve to Ty, it will be in
913   // this variable.
914   OpaqueType *TypeToResolve = 0;
915
916   for (unsigned i = 0; i != UpRefs.size(); ++i) {
917     UR_OUT("  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
918            << UpRefs[i].second->getDescription() << ") = "
919            << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
920     if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
921       // Decrement level of upreference
922       unsigned Level = --UpRefs[i].NestingLevel;
923       UpRefs[i].LastContainedTy = Ty;
924       UR_OUT("  Uplevel Ref Level = " << Level << "\n");
925       if (Level == 0) {                     // Upreference should be resolved!
926         if (!TypeToResolve) {
927           TypeToResolve = UpRefs[i].UpRefTy;
928         } else {
929           UR_OUT("  * Resolving upreference for "
930                  << UpRefs[i].second->getDescription() << "\n";
931                  std::string OldName = UpRefs[i].UpRefTy->getDescription());
932           UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
933           UR_OUT("  * Type '" << OldName << "' refined upreference to: "
934                  << (const void*)Ty << ", " << Ty->getDescription() << "\n");
935         }
936         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
937         --i;                                // Do not skip the next element...
938       }
939     }
940   }
941
942   if (TypeToResolve) {
943     UR_OUT("  * Resolving upreference for "
944            << UpRefs[i].second->getDescription() << "\n";
945            std::string OldName = TypeToResolve->getDescription());
946     TypeToResolve->refineAbstractTypeTo(Ty);
947   }
948
949   return Ty;
950 }
951
952 //===----------------------------------------------------------------------===//
953 //            RunVMAsmParser - Define an interface to this parser
954 //===----------------------------------------------------------------------===//
955 //
956 static Module* RunParser(Module * M);
957
958 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
959   InitLLLexer(MB);
960   Module *M = RunParser(new Module(LLLgetFilename()));
961   FreeLexer();
962   return M;
963 }
964
965 %}
966
967 %union {
968   llvm::Module                           *ModuleVal;
969   llvm::Function                         *FunctionVal;
970   llvm::BasicBlock                       *BasicBlockVal;
971   llvm::TerminatorInst                   *TermInstVal;
972   llvm::Instruction                      *InstVal;
973   llvm::Constant                         *ConstVal;
974
975   const llvm::Type                       *PrimType;
976   std::list<llvm::PATypeHolder>          *TypeList;
977   llvm::PATypeHolder                     *TypeVal;
978   llvm::Value                            *ValueVal;
979   std::vector<llvm::Value*>              *ValueList;
980   std::vector<unsigned>                  *ConstantList;
981   llvm::ArgListType                      *ArgList;
982   llvm::TypeWithAttrs                     TypeWithAttrs;
983   llvm::TypeWithAttrsList                *TypeWithAttrsList;
984   llvm::ParamList                        *ParamList;
985
986   // Represent the RHS of PHI node
987   std::list<std::pair<llvm::Value*,
988                       llvm::BasicBlock*> > *PHIList;
989   std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
990   std::vector<llvm::Constant*>           *ConstVector;
991
992   llvm::GlobalValue::LinkageTypes         Linkage;
993   llvm::GlobalValue::VisibilityTypes      Visibility;
994   llvm::ParameterAttributes         ParamAttrs;
995   llvm::APInt                       *APIntVal;
996   int64_t                           SInt64Val;
997   uint64_t                          UInt64Val;
998   int                               SIntVal;
999   unsigned                          UIntVal;
1000   llvm::APFloat                    *FPVal;
1001   bool                              BoolVal;
1002
1003   std::string                      *StrVal;   // This memory must be deleted
1004   llvm::ValID                       ValIDVal;
1005
1006   llvm::Instruction::BinaryOps      BinaryOpVal;
1007   llvm::Instruction::TermOps        TermOpVal;
1008   llvm::Instruction::MemoryOps      MemOpVal;
1009   llvm::Instruction::CastOps        CastOpVal;
1010   llvm::Instruction::OtherOps       OtherOpVal;
1011   llvm::ICmpInst::Predicate         IPredicate;
1012   llvm::FCmpInst::Predicate         FPredicate;
1013 }
1014
1015 %type <ModuleVal>     Module 
1016 %type <FunctionVal>   Function FunctionProto FunctionHeader BasicBlockList
1017 %type <BasicBlockVal> BasicBlock InstructionList
1018 %type <TermInstVal>   BBTerminatorInst
1019 %type <InstVal>       Inst InstVal MemoryInst
1020 %type <ConstVal>      ConstVal ConstExpr AliaseeRef
1021 %type <ConstVector>   ConstVector
1022 %type <ArgList>       ArgList ArgListH
1023 %type <PHIList>       PHIList
1024 %type <ParamList>     ParamList      // For call param lists & GEP indices
1025 %type <ValueList>     IndexList         // For GEP indices
1026 %type <ConstantList>  ConstantIndexList // For insertvalue/extractvalue indices
1027 %type <TypeList>      TypeListI 
1028 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1029 %type <TypeWithAttrs> ArgType
1030 %type <JumpTable>     JumpTable
1031 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
1032 %type <BoolVal>       ThreadLocal                 // 'thread_local' or not
1033 %type <BoolVal>       OptVolatile                 // 'volatile' or not
1034 %type <BoolVal>       OptTailCall                 // TAIL CALL or plain CALL.
1035 %type <BoolVal>       OptSideEffect               // 'sideeffect' or not.
1036 %type <Linkage>       GVInternalLinkage GVExternalLinkage
1037 %type <Linkage>       FunctionDefineLinkage FunctionDeclareLinkage
1038 %type <Linkage>       AliasLinkage
1039 %type <Visibility>    GVVisibilityStyle
1040
1041 // ValueRef - Unresolved reference to a definition or BB
1042 %type <ValIDVal>      ValueRef ConstValueRef SymbolicValueRef
1043 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
1044 %type <ValueList>     ReturnedVal
1045 // Tokens and types for handling constant integer values
1046 //
1047 // ESINT64VAL - A negative number within long long range
1048 %token <SInt64Val> ESINT64VAL
1049
1050 // EUINT64VAL - A positive number within uns. long long range
1051 %token <UInt64Val> EUINT64VAL
1052
1053 // ESAPINTVAL - A negative number with arbitrary precision 
1054 %token <APIntVal>  ESAPINTVAL
1055
1056 // EUAPINTVAL - A positive number with arbitrary precision 
1057 %token <APIntVal>  EUAPINTVAL
1058
1059 %token  <UIntVal>   LOCALVAL_ID GLOBALVAL_ID  // %123 @123
1060 %token  <FPVal>     FPVAL     // Float or Double constant
1061
1062 // Built in types...
1063 %type  <TypeVal> Types ResultTypes
1064 %type  <PrimType> IntType FPType PrimType           // Classifications
1065 %token <PrimType> VOID INTTYPE 
1066 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1067 %token TYPE
1068
1069
1070 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR 
1071 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1072 %type <StrVal> LocalName OptLocalName OptLocalAssign
1073 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1074 %type <StrVal> OptSection SectionString OptGC
1075
1076 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1077
1078 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1079 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1080 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1081 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1082 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1083 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1084 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1085 %token X86_SSECALLCC_TOK
1086 %token DATALAYOUT
1087 %type <UIntVal> OptCallingConv
1088 %type <ParamAttrs> OptParamAttrs ParamAttr 
1089 %type <ParamAttrs> OptFuncAttrs  FuncAttr
1090
1091 // Basic Block Terminating Operators
1092 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1093
1094 // Binary Operators
1095 %type  <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1096 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1097 %token <BinaryOpVal> SHL LSHR ASHR
1098
1099 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1100 %type  <IPredicate> IPredicates
1101 %type  <FPredicate> FPredicates
1102 %token  EQ NE SLT SGT SLE SGE ULT UGT ULE UGE 
1103 %token  OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1104
1105 // Memory Instructions
1106 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1107
1108 // Cast Operators
1109 %type <CastOpVal> CastOps
1110 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1111 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1112
1113 // Other Operators
1114 %token <OtherOpVal> PHI_TOK SELECT VAARG
1115 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1116 %token <OtherOpVal> GETRESULT
1117 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1118
1119 // Function Attributes
1120 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1121 %token READNONE READONLY GC
1122
1123 // Visibility Styles
1124 %token DEFAULT HIDDEN PROTECTED
1125
1126 %start Module
1127 %%
1128
1129
1130 // Operations that are notably excluded from this list include:
1131 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1132 //
1133 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1134 LogicalOps   : SHL | LSHR | ASHR | AND | OR | XOR;
1135 CastOps      : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST | 
1136                UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1137
1138 IPredicates  
1139   : EQ   { $$ = ICmpInst::ICMP_EQ; }  | NE   { $$ = ICmpInst::ICMP_NE; }
1140   | SLT  { $$ = ICmpInst::ICMP_SLT; } | SGT  { $$ = ICmpInst::ICMP_SGT; }
1141   | SLE  { $$ = ICmpInst::ICMP_SLE; } | SGE  { $$ = ICmpInst::ICMP_SGE; }
1142   | ULT  { $$ = ICmpInst::ICMP_ULT; } | UGT  { $$ = ICmpInst::ICMP_UGT; }
1143   | ULE  { $$ = ICmpInst::ICMP_ULE; } | UGE  { $$ = ICmpInst::ICMP_UGE; } 
1144   ;
1145
1146 FPredicates  
1147   : OEQ  { $$ = FCmpInst::FCMP_OEQ; } | ONE  { $$ = FCmpInst::FCMP_ONE; }
1148   | OLT  { $$ = FCmpInst::FCMP_OLT; } | OGT  { $$ = FCmpInst::FCMP_OGT; }
1149   | OLE  { $$ = FCmpInst::FCMP_OLE; } | OGE  { $$ = FCmpInst::FCMP_OGE; }
1150   | ORD  { $$ = FCmpInst::FCMP_ORD; } | UNO  { $$ = FCmpInst::FCMP_UNO; }
1151   | UEQ  { $$ = FCmpInst::FCMP_UEQ; } | UNE  { $$ = FCmpInst::FCMP_UNE; }
1152   | ULT  { $$ = FCmpInst::FCMP_ULT; } | UGT  { $$ = FCmpInst::FCMP_UGT; }
1153   | ULE  { $$ = FCmpInst::FCMP_ULE; } | UGE  { $$ = FCmpInst::FCMP_UGE; }
1154   | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1155   | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1156   ;
1157
1158 // These are some types that allow classification if we only want a particular 
1159 // thing... for example, only a signed, unsigned, or integral type.
1160 IntType :  INTTYPE;
1161 FPType   : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1162
1163 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1164 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1165
1166 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1167              | /*empty*/                    { $$=0; };
1168
1169 /// OptLocalAssign - Value producing statements have an optional assignment
1170 /// component.
1171 OptLocalAssign : LocalName '=' {
1172     $$ = $1;
1173     CHECK_FOR_ERROR
1174   }
1175   | /*empty*/ {
1176     $$ = 0;
1177     CHECK_FOR_ERROR
1178   };
1179
1180 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1181
1182 OptGlobalAssign : GlobalAssign
1183   | /*empty*/ {
1184     $$ = 0;
1185     CHECK_FOR_ERROR
1186   };
1187
1188 GlobalAssign : GlobalName '=' {
1189     $$ = $1;
1190     CHECK_FOR_ERROR
1191   };
1192
1193 GVInternalLinkage 
1194   : INTERNAL    { $$ = GlobalValue::InternalLinkage; } 
1195   | WEAK        { $$ = GlobalValue::WeakLinkage; } 
1196   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1197   | APPENDING   { $$ = GlobalValue::AppendingLinkage; }
1198   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1199   | COMMON      { $$ = GlobalValue::CommonLinkage; }
1200   ;
1201
1202 GVExternalLinkage
1203   : DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; }
1204   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1205   | EXTERNAL    { $$ = GlobalValue::ExternalLinkage; }
1206   ;
1207
1208 GVVisibilityStyle
1209   : /*empty*/ { $$ = GlobalValue::DefaultVisibility;   }
1210   | DEFAULT   { $$ = GlobalValue::DefaultVisibility;   }
1211   | HIDDEN    { $$ = GlobalValue::HiddenVisibility;    }
1212   | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1213   ;
1214
1215 FunctionDeclareLinkage
1216   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1217   | DLLIMPORT   { $$ = GlobalValue::DLLImportLinkage; } 
1218   | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1219   ;
1220   
1221 FunctionDefineLinkage
1222   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1223   | INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1224   | LINKONCE    { $$ = GlobalValue::LinkOnceLinkage; }
1225   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1226   | DLLEXPORT   { $$ = GlobalValue::DLLExportLinkage; } 
1227   ; 
1228
1229 AliasLinkage
1230   : /*empty*/   { $$ = GlobalValue::ExternalLinkage; }
1231   | WEAK        { $$ = GlobalValue::WeakLinkage; }
1232   | INTERNAL    { $$ = GlobalValue::InternalLinkage; }
1233   ;
1234
1235 OptCallingConv : /*empty*/          { $$ = CallingConv::C; } |
1236                  CCC_TOK            { $$ = CallingConv::C; } |
1237                  FASTCC_TOK         { $$ = CallingConv::Fast; } |
1238                  COLDCC_TOK         { $$ = CallingConv::Cold; } |
1239                  X86_STDCALLCC_TOK  { $$ = CallingConv::X86_StdCall; } |
1240                  X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1241                  X86_SSECALLCC_TOK  { $$ = CallingConv::X86_SSECall; } |
1242                  CC_TOK EUINT64VAL  {
1243                    if ((unsigned)$2 != $2)
1244                      GEN_ERROR("Calling conv too large");
1245                    $$ = $2;
1246                   CHECK_FOR_ERROR
1247                  };
1248
1249 ParamAttr     : ZEROEXT { $$ = ParamAttr::ZExt;      }
1250               | ZEXT    { $$ = ParamAttr::ZExt;      }
1251               | SIGNEXT { $$ = ParamAttr::SExt;      }
1252               | SEXT    { $$ = ParamAttr::SExt;      }
1253               | INREG   { $$ = ParamAttr::InReg;     }
1254               | SRET    { $$ = ParamAttr::StructRet; }
1255               | NOALIAS { $$ = ParamAttr::NoAlias;   }
1256               | BYVAL   { $$ = ParamAttr::ByVal;     }
1257               | NEST    { $$ = ParamAttr::Nest;      }
1258               | ALIGN EUINT64VAL { $$ = 
1259                           ParamAttr::constructAlignmentFromInt($2);    }
1260               ;
1261
1262 OptParamAttrs : /* empty */  { $$ = ParamAttr::None; }
1263               | OptParamAttrs ParamAttr {
1264                 $$ = $1 | $2;
1265               }
1266               ;
1267
1268 FuncAttr      : NORETURN { $$ = ParamAttr::NoReturn; }
1269               | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1270               | ZEROEXT  { $$ = ParamAttr::ZExt;     }
1271               | SIGNEXT  { $$ = ParamAttr::SExt;     }
1272               | READNONE { $$ = ParamAttr::ReadNone; }
1273               | READONLY { $$ = ParamAttr::ReadOnly; }
1274               ;
1275
1276 OptFuncAttrs  : /* empty */ { $$ = ParamAttr::None; }
1277               | OptFuncAttrs FuncAttr {
1278                 $$ = $1 | $2;
1279               }
1280               ;
1281
1282 OptGC         : /* empty */ { $$ = 0; }
1283               | GC STRINGCONSTANT {
1284                 $$ = $2;
1285               }
1286               ;
1287
1288 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1289 // a comma before it.
1290 OptAlign : /*empty*/        { $$ = 0; } |
1291            ALIGN EUINT64VAL {
1292   $$ = $2;
1293   if ($$ != 0 && !isPowerOf2_32($$))
1294     GEN_ERROR("Alignment must be a power of two");
1295   CHECK_FOR_ERROR
1296 };
1297 OptCAlign : /*empty*/            { $$ = 0; } |
1298             ',' ALIGN EUINT64VAL {
1299   $$ = $3;
1300   if ($$ != 0 && !isPowerOf2_32($$))
1301     GEN_ERROR("Alignment must be a power of two");
1302   CHECK_FOR_ERROR
1303 };
1304
1305
1306
1307 SectionString : SECTION STRINGCONSTANT {
1308   for (unsigned i = 0, e = $2->length(); i != e; ++i)
1309     if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1310       GEN_ERROR("Invalid character in section name");
1311   $$ = $2;
1312   CHECK_FOR_ERROR
1313 };
1314
1315 OptSection : /*empty*/ { $$ = 0; } |
1316              SectionString { $$ = $1; };
1317
1318 // GlobalVarAttributes - Used to pass the attributes string on a global.  CurGV
1319 // is set to be the global we are processing.
1320 //
1321 GlobalVarAttributes : /* empty */ {} |
1322                      ',' GlobalVarAttribute GlobalVarAttributes {};
1323 GlobalVarAttribute : SectionString {
1324     CurGV->setSection(*$1);
1325     delete $1;
1326     CHECK_FOR_ERROR
1327   } 
1328   | ALIGN EUINT64VAL {
1329     if ($2 != 0 && !isPowerOf2_32($2))
1330       GEN_ERROR("Alignment must be a power of two");
1331     CurGV->setAlignment($2);
1332     CHECK_FOR_ERROR
1333   };
1334
1335 //===----------------------------------------------------------------------===//
1336 // Types includes all predefined types... except void, because it can only be
1337 // used in specific contexts (function returning void for example).  
1338
1339 // Derived types are added later...
1340 //
1341 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1342
1343 Types 
1344   : OPAQUE {
1345     $$ = new PATypeHolder(OpaqueType::get());
1346     CHECK_FOR_ERROR
1347   }
1348   | PrimType {
1349     $$ = new PATypeHolder($1);
1350     CHECK_FOR_ERROR
1351   }
1352   | Types OptAddrSpace '*' {                             // Pointer type?
1353     if (*$1 == Type::LabelTy)
1354       GEN_ERROR("Cannot form a pointer to a basic block");
1355     $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1356     delete $1;
1357     CHECK_FOR_ERROR
1358   }
1359   | SymbolicValueRef {            // Named types are also simple types...
1360     const Type* tmp = getTypeVal($1);
1361     CHECK_FOR_ERROR
1362     $$ = new PATypeHolder(tmp);
1363   }
1364   | '\\' EUINT64VAL {                   // Type UpReference
1365     if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1366     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
1367     UpRefs.push_back(UpRefRecord((unsigned)$2, OT));  // Add to vector...
1368     $$ = new PATypeHolder(OT);
1369     UR_OUT("New Upreference!\n");
1370     CHECK_FOR_ERROR
1371   }
1372   | Types '(' ArgTypeListI ')' OptFuncAttrs {
1373     // Allow but ignore attributes on function types; this permits auto-upgrade.
1374     // FIXME: remove in LLVM 3.0.
1375     const Type *RetTy = *$1;
1376     if (!FunctionType::isValidReturnType(RetTy))
1377       GEN_ERROR("Invalid result type for LLVM function");
1378       
1379     std::vector<const Type*> Params;
1380     TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1381     for (; I != E; ++I ) {
1382       const Type *Ty = I->Ty->get();
1383       Params.push_back(Ty);
1384     }
1385
1386     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1387     if (isVarArg) Params.pop_back();
1388
1389     for (unsigned i = 0; i != Params.size(); ++i)
1390       if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1391         GEN_ERROR("Function arguments must be value types!");
1392
1393     CHECK_FOR_ERROR
1394
1395     FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1396     delete $3;   // Delete the argument list
1397     delete $1;   // Delete the return type handle
1398     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1399     CHECK_FOR_ERROR
1400   }
1401   | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1402     // Allow but ignore attributes on function types; this permits auto-upgrade.
1403     // FIXME: remove in LLVM 3.0.
1404     std::vector<const Type*> Params;
1405     TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1406     for ( ; I != E; ++I ) {
1407       const Type* Ty = I->Ty->get();
1408       Params.push_back(Ty);
1409     }
1410
1411     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1412     if (isVarArg) Params.pop_back();
1413
1414     for (unsigned i = 0; i != Params.size(); ++i)
1415       if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1416         GEN_ERROR("Function arguments must be value types!");
1417
1418     CHECK_FOR_ERROR
1419
1420     FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1421     delete $3;      // Delete the argument list
1422     $$ = new PATypeHolder(HandleUpRefs(FT)); 
1423     CHECK_FOR_ERROR
1424   }
1425
1426   | '[' EUINT64VAL 'x' Types ']' {          // Sized array type?
1427     $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1428     delete $4;
1429     CHECK_FOR_ERROR
1430   }
1431   | '<' EUINT64VAL 'x' Types '>' {          // Vector type?
1432      const llvm::Type* ElemTy = $4->get();
1433      if ((unsigned)$2 != $2)
1434         GEN_ERROR("Unsigned result not equal to signed result");
1435      if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1436         GEN_ERROR("Element type of a VectorType must be primitive");
1437      $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1438      delete $4;
1439      CHECK_FOR_ERROR
1440   }
1441   | '{' TypeListI '}' {                        // Structure type?
1442     std::vector<const Type*> Elements;
1443     for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1444            E = $2->end(); I != E; ++I)
1445       Elements.push_back(*I);
1446
1447     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1448     delete $2;
1449     CHECK_FOR_ERROR
1450   }
1451   | '{' '}' {                                  // Empty structure type?
1452     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1453     CHECK_FOR_ERROR
1454   }
1455   | '<' '{' TypeListI '}' '>' {
1456     std::vector<const Type*> Elements;
1457     for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1458            E = $3->end(); I != E; ++I)
1459       Elements.push_back(*I);
1460
1461     $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1462     delete $3;
1463     CHECK_FOR_ERROR
1464   }
1465   | '<' '{' '}' '>' {                         // Empty structure type?
1466     $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1467     CHECK_FOR_ERROR
1468   }
1469   ;
1470
1471 ArgType 
1472   : Types OptParamAttrs {
1473     // Allow but ignore attributes on function types; this permits auto-upgrade.
1474     // FIXME: remove in LLVM 3.0.
1475     $$.Ty = $1; 
1476     $$.Attrs = ParamAttr::None;
1477   }
1478   ;
1479
1480 ResultTypes
1481   : Types {
1482     if (!UpRefs.empty())
1483       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1484     if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1485       GEN_ERROR("LLVM functions cannot return aggregate types");
1486     $$ = $1;
1487   }
1488   | VOID {
1489     $$ = new PATypeHolder(Type::VoidTy);
1490   }
1491   ;
1492
1493 ArgTypeList : ArgType {
1494     $$ = new TypeWithAttrsList();
1495     $$->push_back($1);
1496     CHECK_FOR_ERROR
1497   }
1498   | ArgTypeList ',' ArgType {
1499     ($$=$1)->push_back($3);
1500     CHECK_FOR_ERROR
1501   }
1502   ;
1503
1504 ArgTypeListI 
1505   : ArgTypeList
1506   | ArgTypeList ',' DOTDOTDOT {
1507     $$=$1;
1508     TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1509     TWA.Ty = new PATypeHolder(Type::VoidTy);
1510     $$->push_back(TWA);
1511     CHECK_FOR_ERROR
1512   }
1513   | DOTDOTDOT {
1514     $$ = new TypeWithAttrsList;
1515     TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1516     TWA.Ty = new PATypeHolder(Type::VoidTy);
1517     $$->push_back(TWA);
1518     CHECK_FOR_ERROR
1519   }
1520   | /*empty*/ {
1521     $$ = new TypeWithAttrsList();
1522     CHECK_FOR_ERROR
1523   };
1524
1525 // TypeList - Used for struct declarations and as a basis for function type 
1526 // declaration type lists
1527 //
1528 TypeListI : Types {
1529     $$ = new std::list<PATypeHolder>();
1530     $$->push_back(*$1); 
1531     delete $1;
1532     CHECK_FOR_ERROR
1533   }
1534   | TypeListI ',' Types {
1535     ($$=$1)->push_back(*$3); 
1536     delete $3;
1537     CHECK_FOR_ERROR
1538   };
1539
1540 // ConstVal - The various declarations that go into the constant pool.  This
1541 // production is used ONLY to represent constants that show up AFTER a 'const',
1542 // 'constant' or 'global' token at global scope.  Constants that can be inlined
1543 // into other expressions (such as integers and constexprs) are handled by the
1544 // ResolvedVal, ValueRef and ConstValueRef productions.
1545 //
1546 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1547     if (!UpRefs.empty())
1548       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1549     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1550     if (ATy == 0)
1551       GEN_ERROR("Cannot make array constant with type: '" + 
1552                      (*$1)->getDescription() + "'");
1553     const Type *ETy = ATy->getElementType();
1554     uint64_t NumElements = ATy->getNumElements();
1555
1556     // Verify that we have the correct size...
1557     if (NumElements != uint64_t(-1) && NumElements != $3->size())
1558       GEN_ERROR("Type mismatch: constant sized array initialized with " +
1559                      utostr($3->size()) +  " arguments, but has size of " + 
1560                      utostr(NumElements) + "");
1561
1562     // Verify all elements are correct type!
1563     for (unsigned i = 0; i < $3->size(); i++) {
1564       if (ETy != (*$3)[i]->getType())
1565         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1566                        ETy->getDescription() +"' as required!\nIt is of type '"+
1567                        (*$3)[i]->getType()->getDescription() + "'.");
1568     }
1569
1570     $$ = ConstantArray::get(ATy, *$3);
1571     delete $1; delete $3;
1572     CHECK_FOR_ERROR
1573   }
1574   | Types '[' ']' {
1575     if (!UpRefs.empty())
1576       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1577     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1578     if (ATy == 0)
1579       GEN_ERROR("Cannot make array constant with type: '" + 
1580                      (*$1)->getDescription() + "'");
1581
1582     uint64_t NumElements = ATy->getNumElements();
1583     if (NumElements != uint64_t(-1) && NumElements != 0) 
1584       GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1585                      " arguments, but has size of " + utostr(NumElements) +"");
1586     $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1587     delete $1;
1588     CHECK_FOR_ERROR
1589   }
1590   | Types 'c' STRINGCONSTANT {
1591     if (!UpRefs.empty())
1592       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1593     const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1594     if (ATy == 0)
1595       GEN_ERROR("Cannot make array constant with type: '" + 
1596                      (*$1)->getDescription() + "'");
1597
1598     uint64_t NumElements = ATy->getNumElements();
1599     const Type *ETy = ATy->getElementType();
1600     if (NumElements != uint64_t(-1) && NumElements != $3->length())
1601       GEN_ERROR("Can't build string constant of size " + 
1602                      utostr($3->length()) +
1603                      " when array has size " + utostr(NumElements) + "");
1604     std::vector<Constant*> Vals;
1605     if (ETy == Type::Int8Ty) {
1606       for (uint64_t i = 0; i < $3->length(); ++i)
1607         Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1608     } else {
1609       delete $3;
1610       GEN_ERROR("Cannot build string arrays of non byte sized elements");
1611     }
1612     delete $3;
1613     $$ = ConstantArray::get(ATy, Vals);
1614     delete $1;
1615     CHECK_FOR_ERROR
1616   }
1617   | Types '<' ConstVector '>' { // Nonempty unsized arr
1618     if (!UpRefs.empty())
1619       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1620     const VectorType *PTy = dyn_cast<VectorType>($1->get());
1621     if (PTy == 0)
1622       GEN_ERROR("Cannot make packed constant with type: '" + 
1623                      (*$1)->getDescription() + "'");
1624     const Type *ETy = PTy->getElementType();
1625     unsigned NumElements = PTy->getNumElements();
1626
1627     // Verify that we have the correct size...
1628     if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1629       GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1630                      utostr($3->size()) +  " arguments, but has size of " + 
1631                      utostr(NumElements) + "");
1632
1633     // Verify all elements are correct type!
1634     for (unsigned i = 0; i < $3->size(); i++) {
1635       if (ETy != (*$3)[i]->getType())
1636         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
1637            ETy->getDescription() +"' as required!\nIt is of type '"+
1638            (*$3)[i]->getType()->getDescription() + "'.");
1639     }
1640
1641     $$ = ConstantVector::get(PTy, *$3);
1642     delete $1; delete $3;
1643     CHECK_FOR_ERROR
1644   }
1645   | Types '{' ConstVector '}' {
1646     const StructType *STy = dyn_cast<StructType>($1->get());
1647     if (STy == 0)
1648       GEN_ERROR("Cannot make struct constant with type: '" + 
1649                      (*$1)->getDescription() + "'");
1650
1651     if ($3->size() != STy->getNumContainedTypes())
1652       GEN_ERROR("Illegal number of initializers for structure type");
1653
1654     // Check to ensure that constants are compatible with the type initializer!
1655     for (unsigned i = 0, e = $3->size(); i != e; ++i)
1656       if ((*$3)[i]->getType() != STy->getElementType(i))
1657         GEN_ERROR("Expected type '" +
1658                        STy->getElementType(i)->getDescription() +
1659                        "' for element #" + utostr(i) +
1660                        " of structure initializer");
1661
1662     // Check to ensure that Type is not packed
1663     if (STy->isPacked())
1664       GEN_ERROR("Unpacked Initializer to vector type '" +
1665                 STy->getDescription() + "'");
1666
1667     $$ = ConstantStruct::get(STy, *$3);
1668     delete $1; delete $3;
1669     CHECK_FOR_ERROR
1670   }
1671   | Types '{' '}' {
1672     if (!UpRefs.empty())
1673       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1674     const StructType *STy = dyn_cast<StructType>($1->get());
1675     if (STy == 0)
1676       GEN_ERROR("Cannot make struct constant with type: '" + 
1677                      (*$1)->getDescription() + "'");
1678
1679     if (STy->getNumContainedTypes() != 0)
1680       GEN_ERROR("Illegal number of initializers for structure type");
1681
1682     // Check to ensure that Type is not packed
1683     if (STy->isPacked())
1684       GEN_ERROR("Unpacked Initializer to vector type '" +
1685                 STy->getDescription() + "'");
1686
1687     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1688     delete $1;
1689     CHECK_FOR_ERROR
1690   }
1691   | Types '<' '{' ConstVector '}' '>' {
1692     const StructType *STy = dyn_cast<StructType>($1->get());
1693     if (STy == 0)
1694       GEN_ERROR("Cannot make struct constant with type: '" + 
1695                      (*$1)->getDescription() + "'");
1696
1697     if ($4->size() != STy->getNumContainedTypes())
1698       GEN_ERROR("Illegal number of initializers for structure type");
1699
1700     // Check to ensure that constants are compatible with the type initializer!
1701     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1702       if ((*$4)[i]->getType() != STy->getElementType(i))
1703         GEN_ERROR("Expected type '" +
1704                        STy->getElementType(i)->getDescription() +
1705                        "' for element #" + utostr(i) +
1706                        " of structure initializer");
1707
1708     // Check to ensure that Type is packed
1709     if (!STy->isPacked())
1710       GEN_ERROR("Vector initializer to non-vector type '" + 
1711                 STy->getDescription() + "'");
1712
1713     $$ = ConstantStruct::get(STy, *$4);
1714     delete $1; delete $4;
1715     CHECK_FOR_ERROR
1716   }
1717   | Types '<' '{' '}' '>' {
1718     if (!UpRefs.empty())
1719       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1720     const StructType *STy = dyn_cast<StructType>($1->get());
1721     if (STy == 0)
1722       GEN_ERROR("Cannot make struct constant with type: '" + 
1723                      (*$1)->getDescription() + "'");
1724
1725     if (STy->getNumContainedTypes() != 0)
1726       GEN_ERROR("Illegal number of initializers for structure type");
1727
1728     // Check to ensure that Type is packed
1729     if (!STy->isPacked())
1730       GEN_ERROR("Vector initializer to non-vector type '" + 
1731                 STy->getDescription() + "'");
1732
1733     $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1734     delete $1;
1735     CHECK_FOR_ERROR
1736   }
1737   | Types NULL_TOK {
1738     if (!UpRefs.empty())
1739       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1740     const PointerType *PTy = dyn_cast<PointerType>($1->get());
1741     if (PTy == 0)
1742       GEN_ERROR("Cannot make null pointer constant with type: '" + 
1743                      (*$1)->getDescription() + "'");
1744
1745     $$ = ConstantPointerNull::get(PTy);
1746     delete $1;
1747     CHECK_FOR_ERROR
1748   }
1749   | Types UNDEF {
1750     if (!UpRefs.empty())
1751       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1752     $$ = UndefValue::get($1->get());
1753     delete $1;
1754     CHECK_FOR_ERROR
1755   }
1756   | Types SymbolicValueRef {
1757     if (!UpRefs.empty())
1758       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1759     const PointerType *Ty = dyn_cast<PointerType>($1->get());
1760     if (Ty == 0)
1761       GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1762
1763     // ConstExprs can exist in the body of a function, thus creating
1764     // GlobalValues whenever they refer to a variable.  Because we are in
1765     // the context of a function, getExistingVal will search the functions
1766     // symbol table instead of the module symbol table for the global symbol,
1767     // which throws things all off.  To get around this, we just tell
1768     // getExistingVal that we are at global scope here.
1769     //
1770     Function *SavedCurFn = CurFun.CurrentFunction;
1771     CurFun.CurrentFunction = 0;
1772
1773     Value *V = getExistingVal(Ty, $2);
1774     CHECK_FOR_ERROR
1775
1776     CurFun.CurrentFunction = SavedCurFn;
1777
1778     // If this is an initializer for a constant pointer, which is referencing a
1779     // (currently) undefined variable, create a stub now that shall be replaced
1780     // in the future with the right type of variable.
1781     //
1782     if (V == 0) {
1783       assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1784       const PointerType *PT = cast<PointerType>(Ty);
1785
1786       // First check to see if the forward references value is already created!
1787       PerModuleInfo::GlobalRefsType::iterator I =
1788         CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1789     
1790       if (I != CurModule.GlobalRefs.end()) {
1791         V = I->second;             // Placeholder already exists, use it...
1792         $2.destroy();
1793       } else {
1794         std::string Name;
1795         if ($2.Type == ValID::GlobalName)
1796           Name = $2.getName();
1797         else if ($2.Type != ValID::GlobalID)
1798           GEN_ERROR("Invalid reference to global");
1799
1800         // Create the forward referenced global.
1801         GlobalValue *GV;
1802         if (const FunctionType *FTy = 
1803                  dyn_cast<FunctionType>(PT->getElementType())) {
1804           GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1805                                 CurModule.CurrentModule);
1806         } else {
1807           GV = new GlobalVariable(PT->getElementType(), false,
1808                                   GlobalValue::ExternalWeakLinkage, 0,
1809                                   Name, CurModule.CurrentModule);
1810         }
1811
1812         // Keep track of the fact that we have a forward ref to recycle it
1813         CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1814         V = GV;
1815       }
1816     }
1817
1818     $$ = cast<GlobalValue>(V);
1819     delete $1;            // Free the type handle
1820     CHECK_FOR_ERROR
1821   }
1822   | Types ConstExpr {
1823     if (!UpRefs.empty())
1824       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1825     if ($1->get() != $2->getType())
1826       GEN_ERROR("Mismatched types for constant expression: " + 
1827         (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1828     $$ = $2;
1829     delete $1;
1830     CHECK_FOR_ERROR
1831   }
1832   | Types ZEROINITIALIZER {
1833     if (!UpRefs.empty())
1834       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1835     const Type *Ty = $1->get();
1836     if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1837       GEN_ERROR("Cannot create a null initialized value of this type");
1838     $$ = Constant::getNullValue(Ty);
1839     delete $1;
1840     CHECK_FOR_ERROR
1841   }
1842   | IntType ESINT64VAL {      // integral constants
1843     if (!ConstantInt::isValueValidForType($1, $2))
1844       GEN_ERROR("Constant value doesn't fit in type");
1845     $$ = ConstantInt::get($1, $2, true);
1846     CHECK_FOR_ERROR
1847   }
1848   | IntType ESAPINTVAL {      // arbitrary precision integer constants
1849     uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1850     if ($2->getBitWidth() > BitWidth) {
1851       GEN_ERROR("Constant value does not fit in type");
1852     }
1853     $2->sextOrTrunc(BitWidth);
1854     $$ = ConstantInt::get(*$2);
1855     delete $2;
1856     CHECK_FOR_ERROR
1857   }
1858   | IntType EUINT64VAL {      // integral constants
1859     if (!ConstantInt::isValueValidForType($1, $2))
1860       GEN_ERROR("Constant value doesn't fit in type");
1861     $$ = ConstantInt::get($1, $2, false);
1862     CHECK_FOR_ERROR
1863   }
1864   | IntType EUAPINTVAL {      // arbitrary precision integer constants
1865     uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1866     if ($2->getBitWidth() > BitWidth) {
1867       GEN_ERROR("Constant value does not fit in type");
1868     } 
1869     $2->zextOrTrunc(BitWidth);
1870     $$ = ConstantInt::get(*$2);
1871     delete $2;
1872     CHECK_FOR_ERROR
1873   }
1874   | INTTYPE TRUETOK {                      // Boolean constants
1875     if (cast<IntegerType>($1)->getBitWidth() != 1)
1876       GEN_ERROR("Constant true must have type i1");
1877     $$ = ConstantInt::getTrue();
1878     CHECK_FOR_ERROR
1879   }
1880   | INTTYPE FALSETOK {                     // Boolean constants
1881     if (cast<IntegerType>($1)->getBitWidth() != 1)
1882       GEN_ERROR("Constant false must have type i1");
1883     $$ = ConstantInt::getFalse();
1884     CHECK_FOR_ERROR
1885   }
1886   | FPType FPVAL {                   // Floating point constants
1887     if (!ConstantFP::isValueValidForType($1, *$2))
1888       GEN_ERROR("Floating point constant invalid for type");
1889     // Lexer has no type info, so builds all float and double FP constants 
1890     // as double.  Fix this here.  Long double is done right.
1891     if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1892       $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1893     $$ = ConstantFP::get(*$2);
1894     delete $2;
1895     CHECK_FOR_ERROR
1896   };
1897
1898
1899 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1900     if (!UpRefs.empty())
1901       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1902     Constant *Val = $3;
1903     const Type *DestTy = $5->get();
1904     if (!CastInst::castIsValid($1, $3, DestTy))
1905       GEN_ERROR("invalid cast opcode for cast from '" +
1906                 Val->getType()->getDescription() + "' to '" +
1907                 DestTy->getDescription() + "'"); 
1908     $$ = ConstantExpr::getCast($1, $3, DestTy);
1909     delete $5;
1910   }
1911   | GETELEMENTPTR '(' ConstVal IndexList ')' {
1912     if (!isa<PointerType>($3->getType()))
1913       GEN_ERROR("GetElementPtr requires a pointer operand");
1914
1915     const Type *IdxTy =
1916       GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1917     if (!IdxTy)
1918       GEN_ERROR("Index list invalid for constant getelementptr");
1919
1920     SmallVector<Constant*, 8> IdxVec;
1921     for (unsigned i = 0, e = $4->size(); i != e; ++i)
1922       if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1923         IdxVec.push_back(C);
1924       else
1925         GEN_ERROR("Indices to constant getelementptr must be constants");
1926
1927     delete $4;
1928
1929     $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1930     CHECK_FOR_ERROR
1931   }
1932   | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1933     if ($3->getType() != Type::Int1Ty)
1934       GEN_ERROR("Select condition must be of boolean type");
1935     if ($5->getType() != $7->getType())
1936       GEN_ERROR("Select operand types must match");
1937     $$ = ConstantExpr::getSelect($3, $5, $7);
1938     CHECK_FOR_ERROR
1939   }
1940   | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1941     if ($3->getType() != $5->getType())
1942       GEN_ERROR("Binary operator types must match");
1943     CHECK_FOR_ERROR;
1944     $$ = ConstantExpr::get($1, $3, $5);
1945   }
1946   | LogicalOps '(' ConstVal ',' ConstVal ')' {
1947     if ($3->getType() != $5->getType())
1948       GEN_ERROR("Logical operator types must match");
1949     if (!$3->getType()->isInteger()) {
1950       if (!isa<VectorType>($3->getType()) || 
1951           !cast<VectorType>($3->getType())->getElementType()->isInteger())
1952         GEN_ERROR("Logical operator requires integral operands");
1953     }
1954     $$ = ConstantExpr::get($1, $3, $5);
1955     CHECK_FOR_ERROR
1956   }
1957   | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1958     if ($4->getType() != $6->getType())
1959       GEN_ERROR("icmp operand types must match");
1960     $$ = ConstantExpr::getICmp($2, $4, $6);
1961   }
1962   | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1963     if ($4->getType() != $6->getType())
1964       GEN_ERROR("fcmp operand types must match");
1965     $$ = ConstantExpr::getFCmp($2, $4, $6);
1966   }
1967   | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1968     if ($4->getType() != $6->getType())
1969       GEN_ERROR("vicmp operand types must match");
1970     $$ = ConstantExpr::getVICmp($2, $4, $6);
1971   }
1972   | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1973     if ($4->getType() != $6->getType())
1974       GEN_ERROR("vfcmp operand types must match");
1975     $$ = ConstantExpr::getVFCmp($2, $4, $6);
1976   }
1977   | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1978     if (!ExtractElementInst::isValidOperands($3, $5))
1979       GEN_ERROR("Invalid extractelement operands");
1980     $$ = ConstantExpr::getExtractElement($3, $5);
1981     CHECK_FOR_ERROR
1982   }
1983   | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1984     if (!InsertElementInst::isValidOperands($3, $5, $7))
1985       GEN_ERROR("Invalid insertelement operands");
1986     $$ = ConstantExpr::getInsertElement($3, $5, $7);
1987     CHECK_FOR_ERROR
1988   }
1989   | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1990     if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1991       GEN_ERROR("Invalid shufflevector operands");
1992     $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1993     CHECK_FOR_ERROR
1994   }
1995   | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
1996     if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1997       GEN_ERROR("ExtractValue requires an aggregate operand");
1998
1999     $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2000     delete $4;
2001     CHECK_FOR_ERROR
2002   }
2003   | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2004     if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2005       GEN_ERROR("InsertValue requires an aggregate operand");
2006
2007     $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2008     delete $6;
2009     CHECK_FOR_ERROR
2010   };
2011
2012
2013 // ConstVector - A list of comma separated constants.
2014 ConstVector : ConstVector ',' ConstVal {
2015     ($$ = $1)->push_back($3);
2016     CHECK_FOR_ERROR
2017   }
2018   | ConstVal {
2019     $$ = new std::vector<Constant*>();
2020     $$->push_back($1);
2021     CHECK_FOR_ERROR
2022   };
2023
2024
2025 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2026 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2027
2028 // ThreadLocal 
2029 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2030
2031 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2032 AliaseeRef : ResultTypes SymbolicValueRef {
2033     const Type* VTy = $1->get();
2034     Value *V = getVal(VTy, $2);
2035     CHECK_FOR_ERROR
2036     GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2037     if (!Aliasee)
2038       GEN_ERROR("Aliases can be created only to global values");
2039
2040     $$ = Aliasee;
2041     CHECK_FOR_ERROR
2042     delete $1;
2043    }
2044    | BITCAST '(' AliaseeRef TO Types ')' {
2045     Constant *Val = $3;
2046     const Type *DestTy = $5->get();
2047     if (!CastInst::castIsValid($1, $3, DestTy))
2048       GEN_ERROR("invalid cast opcode for cast from '" +
2049                 Val->getType()->getDescription() + "' to '" +
2050                 DestTy->getDescription() + "'");
2051     
2052     $$ = ConstantExpr::getCast($1, $3, DestTy);
2053     CHECK_FOR_ERROR
2054     delete $5;
2055    };
2056
2057 //===----------------------------------------------------------------------===//
2058 //                             Rules to match Modules
2059 //===----------------------------------------------------------------------===//
2060
2061 // Module rule: Capture the result of parsing the whole file into a result
2062 // variable...
2063 //
2064 Module 
2065   : DefinitionList {
2066     $$ = ParserResult = CurModule.CurrentModule;
2067     CurModule.ModuleDone();
2068     CHECK_FOR_ERROR;
2069   }
2070   | /*empty*/ {
2071     $$ = ParserResult = CurModule.CurrentModule;
2072     CurModule.ModuleDone();
2073     CHECK_FOR_ERROR;
2074   }
2075   ;
2076
2077 DefinitionList
2078   : Definition
2079   | DefinitionList Definition
2080   ;
2081
2082 Definition 
2083   : DEFINE { CurFun.isDeclare = false; } Function {
2084     CurFun.FunctionDone();
2085     CHECK_FOR_ERROR
2086   }
2087   | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2088     CHECK_FOR_ERROR
2089   }
2090   | MODULE ASM_TOK AsmBlock {
2091     CHECK_FOR_ERROR
2092   }  
2093   | OptLocalAssign TYPE Types {
2094     if (!UpRefs.empty())
2095       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2096     // Eagerly resolve types.  This is not an optimization, this is a
2097     // requirement that is due to the fact that we could have this:
2098     //
2099     // %list = type { %list * }
2100     // %list = type { %list * }    ; repeated type decl
2101     //
2102     // If types are not resolved eagerly, then the two types will not be
2103     // determined to be the same type!
2104     //
2105     ResolveTypeTo($1, *$3);
2106
2107     if (!setTypeName(*$3, $1) && !$1) {
2108       CHECK_FOR_ERROR
2109       // If this is a named type that is not a redefinition, add it to the slot
2110       // table.
2111       CurModule.Types.push_back(*$3);
2112     }
2113
2114     delete $3;
2115     CHECK_FOR_ERROR
2116   }
2117   | OptLocalAssign TYPE VOID {
2118     ResolveTypeTo($1, $3);
2119
2120     if (!setTypeName($3, $1) && !$1) {
2121       CHECK_FOR_ERROR
2122       // If this is a named type that is not a redefinition, add it to the slot
2123       // table.
2124       CurModule.Types.push_back($3);
2125     }
2126     CHECK_FOR_ERROR
2127   }
2128   | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal 
2129     OptAddrSpace { 
2130     /* "Externally Visible" Linkage */
2131     if ($5 == 0) 
2132       GEN_ERROR("Global value initializer is not a constant");
2133     CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2134                                 $2, $4, $5->getType(), $5, $3, $6);
2135     CHECK_FOR_ERROR
2136   } GlobalVarAttributes {
2137     CurGV = 0;
2138   }
2139   | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2140     ConstVal OptAddrSpace {
2141     if ($6 == 0) 
2142       GEN_ERROR("Global value initializer is not a constant");
2143     CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2144     CHECK_FOR_ERROR
2145   } GlobalVarAttributes {
2146     CurGV = 0;
2147   }
2148   | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2149     Types OptAddrSpace {
2150     if (!UpRefs.empty())
2151       GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2152     CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2153     CHECK_FOR_ERROR
2154     delete $6;
2155   } GlobalVarAttributes {
2156     CurGV = 0;
2157     CHECK_FOR_ERROR
2158   }
2159   | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2160     std::string Name;
2161     if ($1) {
2162       Name = *$1;
2163       delete $1;
2164     }
2165     if (Name.empty())
2166       GEN_ERROR("Alias name cannot be empty");
2167     
2168     Constant* Aliasee = $5;
2169     if (Aliasee == 0)
2170       GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2171
2172     GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2173                                       CurModule.CurrentModule);
2174     GA->setVisibility($2);
2175     InsertValue(GA, CurModule.Values);
2176     
2177     
2178     // If there was a forward reference of this alias, resolve it now.
2179     
2180     ValID ID;
2181     if (!Name.empty())
2182       ID = ValID::createGlobalName(Name);
2183     else
2184       ID = ValID::createGlobalID(CurModule.Values.size()-1);
2185     
2186     if (GlobalValue *FWGV =
2187           CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2188       // Replace uses of the fwdref with the actual alias.
2189       FWGV->replaceAllUsesWith(GA);
2190       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2191         GV->eraseFromParent();
2192       else
2193         cast<Function>(FWGV)->eraseFromParent();
2194     }
2195     ID.destroy();
2196     
2197     CHECK_FOR_ERROR
2198   }
2199   | TARGET TargetDefinition { 
2200     CHECK_FOR_ERROR
2201   }
2202   | DEPLIBS '=' LibrariesDefinition {
2203     CHECK_FOR_ERROR
2204   }
2205   ;
2206
2207
2208 AsmBlock : STRINGCONSTANT {
2209   const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2210   if (AsmSoFar.empty())
2211     CurModule.CurrentModule->setModuleInlineAsm(*$1);
2212   else
2213     CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2214   delete $1;
2215   CHECK_FOR_ERROR
2216 };
2217
2218 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2219     CurModule.CurrentModule->setTargetTriple(*$3);
2220     delete $3;
2221   }
2222   | DATALAYOUT '=' STRINGCONSTANT {
2223     CurModule.CurrentModule->setDataLayout(*$3);
2224     delete $3;
2225   };
2226
2227 LibrariesDefinition : '[' LibList ']';
2228
2229 LibList : LibList ',' STRINGCONSTANT {
2230           CurModule.CurrentModule->addLibrary(*$3);
2231           delete $3;
2232           CHECK_FOR_ERROR
2233         }
2234         | STRINGCONSTANT {
2235           CurModule.CurrentModule->addLibrary(*$1);
2236           delete $1;
2237           CHECK_FOR_ERROR
2238         }
2239         | /* empty: end of list */ {
2240           CHECK_FOR_ERROR
2241         }
2242         ;
2243
2244 //===----------------------------------------------------------------------===//
2245 //                       Rules to match Function Headers
2246 //===----------------------------------------------------------------------===//
2247
2248 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2249     if (!UpRefs.empty())
2250       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2251     if (!(*$3)->isFirstClassType())
2252       GEN_ERROR("Argument types must be first-class");
2253     ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2254     $$ = $1;
2255     $1->push_back(E);
2256     CHECK_FOR_ERROR
2257   }
2258   | Types OptParamAttrs OptLocalName {
2259     if (!UpRefs.empty())
2260       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2261     if (!(*$1)->isFirstClassType())
2262       GEN_ERROR("Argument types must be first-class");
2263     ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2264     $$ = new ArgListType;
2265     $$->push_back(E);
2266     CHECK_FOR_ERROR
2267   };
2268
2269 ArgList : ArgListH {
2270     $$ = $1;
2271     CHECK_FOR_ERROR
2272   }
2273   | ArgListH ',' DOTDOTDOT {
2274     $$ = $1;
2275     struct ArgListEntry E;
2276     E.Ty = new PATypeHolder(Type::VoidTy);
2277     E.Name = 0;
2278     E.Attrs = ParamAttr::None;
2279     $$->push_back(E);
2280     CHECK_FOR_ERROR
2281   }
2282   | DOTDOTDOT {
2283     $$ = new ArgListType;
2284     struct ArgListEntry E;
2285     E.Ty = new PATypeHolder(Type::VoidTy);
2286     E.Name = 0;
2287     E.Attrs = ParamAttr::None;
2288     $$->push_back(E);
2289     CHECK_FOR_ERROR
2290   }
2291   | /* empty */ {
2292     $$ = 0;
2293     CHECK_FOR_ERROR
2294   };
2295
2296 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')' 
2297                   OptFuncAttrs OptSection OptAlign OptGC {
2298   std::string FunctionName(*$3);
2299   delete $3;  // Free strdup'd memory!
2300   
2301   // Check the function result for abstractness if this is a define. We should
2302   // have no abstract types at this point
2303   if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2304     GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2305
2306   if (!FunctionType::isValidReturnType(*$2))
2307     GEN_ERROR("Invalid result type for LLVM function");
2308     
2309   std::vector<const Type*> ParamTypeList;
2310   SmallVector<ParamAttrsWithIndex, 8> Attrs;
2311   if ($7 != ParamAttr::None)
2312     Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
2313   if ($5) {   // If there are arguments...
2314     unsigned index = 1;
2315     for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2316       const Type* Ty = I->Ty->get();
2317       if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2318         GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2319       ParamTypeList.push_back(Ty);
2320       if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2321         Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
2322     }
2323   }
2324
2325   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2326   if (isVarArg) ParamTypeList.pop_back();
2327
2328   PAListPtr PAL;
2329   if (!Attrs.empty())
2330     PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2331
2332   FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2333   const PointerType *PFT = PointerType::getUnqual(FT);
2334   delete $2;
2335
2336   ValID ID;
2337   if (!FunctionName.empty()) {
2338     ID = ValID::createGlobalName((char*)FunctionName.c_str());
2339   } else {
2340     ID = ValID::createGlobalID(CurModule.Values.size());
2341   }
2342
2343   Function *Fn = 0;
2344   // See if this function was forward referenced.  If so, recycle the object.
2345   if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2346     // Move the function to the end of the list, from whereever it was 
2347     // previously inserted.
2348     Fn = cast<Function>(FWRef);
2349     assert(Fn->getParamAttrs().isEmpty() &&
2350            "Forward reference has parameter attributes!");
2351     CurModule.CurrentModule->getFunctionList().remove(Fn);
2352     CurModule.CurrentModule->getFunctionList().push_back(Fn);
2353   } else if (!FunctionName.empty() &&     // Merge with an earlier prototype?
2354              (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2355     if (Fn->getFunctionType() != FT ) {
2356       // The existing function doesn't have the same type. This is an overload
2357       // error.
2358       GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2359     } else if (Fn->getParamAttrs() != PAL) {
2360       // The existing function doesn't have the same parameter attributes.
2361       // This is an overload error.
2362       GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2363     } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2364       // Neither the existing or the current function is a declaration and they
2365       // have the same name and same type. Clearly this is a redefinition.
2366       GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2367     } else if (Fn->isDeclaration()) {
2368       // Make sure to strip off any argument names so we can't get conflicts.
2369       for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2370            AI != AE; ++AI)
2371         AI->setName("");
2372     }
2373   } else  {  // Not already defined?
2374     Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2375                           CurModule.CurrentModule);
2376     InsertValue(Fn, CurModule.Values);
2377   }
2378
2379   CurFun.FunctionStart(Fn);
2380
2381   if (CurFun.isDeclare) {
2382     // If we have declaration, always overwrite linkage.  This will allow us to
2383     // correctly handle cases, when pointer to function is passed as argument to
2384     // another function.
2385     Fn->setLinkage(CurFun.Linkage);
2386     Fn->setVisibility(CurFun.Visibility);
2387   }
2388   Fn->setCallingConv($1);
2389   Fn->setParamAttrs(PAL);
2390   Fn->setAlignment($9);
2391   if ($8) {
2392     Fn->setSection(*$8);
2393     delete $8;
2394   }
2395   if ($10) {
2396     Fn->setGC($10->c_str());
2397     delete $10;
2398   }
2399
2400   // Add all of the arguments we parsed to the function...
2401   if ($5) {                     // Is null if empty...
2402     if (isVarArg) {  // Nuke the last entry
2403       assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2404              "Not a varargs marker!");
2405       delete $5->back().Ty;
2406       $5->pop_back();  // Delete the last entry
2407     }
2408     Function::arg_iterator ArgIt = Fn->arg_begin();
2409     Function::arg_iterator ArgEnd = Fn->arg_end();
2410     unsigned Idx = 1;
2411     for (ArgListType::iterator I = $5->begin(); 
2412          I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2413       delete I->Ty;                          // Delete the typeholder...
2414       setValueName(ArgIt, I->Name);       // Insert arg into symtab...
2415       CHECK_FOR_ERROR
2416       InsertValue(ArgIt);
2417       Idx++;
2418     }
2419
2420     delete $5;                     // We're now done with the argument list
2421   }
2422   CHECK_FOR_ERROR
2423 };
2424
2425 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
2426
2427 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2428   $$ = CurFun.CurrentFunction;
2429
2430   // Make sure that we keep track of the linkage type even if there was a
2431   // previous "declare".
2432   $$->setLinkage($1);
2433   $$->setVisibility($2);
2434 };
2435
2436 END : ENDTOK | '}';                    // Allow end of '}' to end a function
2437
2438 Function : BasicBlockList END {
2439   $$ = $1;
2440   CHECK_FOR_ERROR
2441 };
2442
2443 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2444     CurFun.CurrentFunction->setLinkage($1);
2445     CurFun.CurrentFunction->setVisibility($2);
2446     $$ = CurFun.CurrentFunction;
2447     CurFun.FunctionDone();
2448     CHECK_FOR_ERROR
2449   };
2450
2451 //===----------------------------------------------------------------------===//
2452 //                        Rules to match Basic Blocks
2453 //===----------------------------------------------------------------------===//
2454
2455 OptSideEffect : /* empty */ {
2456     $$ = false;
2457     CHECK_FOR_ERROR
2458   }
2459   | SIDEEFFECT {
2460     $$ = true;
2461     CHECK_FOR_ERROR
2462   };
2463
2464 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
2465     $$ = ValID::create($1);
2466     CHECK_FOR_ERROR
2467   }
2468   | EUINT64VAL {
2469     $$ = ValID::create($1);
2470     CHECK_FOR_ERROR
2471   }
2472   | ESAPINTVAL {      // arbitrary precision integer constants
2473     $$ = ValID::create(*$1, true);
2474     delete $1;
2475     CHECK_FOR_ERROR
2476   }  
2477   | EUAPINTVAL {      // arbitrary precision integer constants
2478     $$ = ValID::create(*$1, false);
2479     delete $1;
2480     CHECK_FOR_ERROR
2481   }
2482   | FPVAL {                     // Perhaps it's an FP constant?
2483     $$ = ValID::create($1);
2484     CHECK_FOR_ERROR
2485   }
2486   | TRUETOK {
2487     $$ = ValID::create(ConstantInt::getTrue());
2488     CHECK_FOR_ERROR
2489   } 
2490   | FALSETOK {
2491     $$ = ValID::create(ConstantInt::getFalse());
2492     CHECK_FOR_ERROR
2493   }
2494   | NULL_TOK {
2495     $$ = ValID::createNull();
2496     CHECK_FOR_ERROR
2497   }
2498   | UNDEF {
2499     $$ = ValID::createUndef();
2500     CHECK_FOR_ERROR
2501   }
2502   | ZEROINITIALIZER {     // A vector zero constant.
2503     $$ = ValID::createZeroInit();
2504     CHECK_FOR_ERROR
2505   }
2506   | '<' ConstVector '>' { // Nonempty unsized packed vector
2507     const Type *ETy = (*$2)[0]->getType();
2508     unsigned NumElements = $2->size(); 
2509
2510     if (!ETy->isInteger() && !ETy->isFloatingPoint())
2511       GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2512     
2513     VectorType* pt = VectorType::get(ETy, NumElements);
2514     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2515     
2516     // Verify all elements are correct type!
2517     for (unsigned i = 0; i < $2->size(); i++) {
2518       if (ETy != (*$2)[i]->getType())
2519         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2520                      ETy->getDescription() +"' as required!\nIt is of type '" +
2521                      (*$2)[i]->getType()->getDescription() + "'.");
2522     }
2523
2524     $$ = ValID::create(ConstantVector::get(pt, *$2));
2525     delete PTy; delete $2;
2526     CHECK_FOR_ERROR
2527   }
2528   | '[' ConstVector ']' { // Nonempty unsized arr
2529     const Type *ETy = (*$2)[0]->getType();
2530     uint64_t NumElements = $2->size(); 
2531
2532     if (!ETy->isFirstClassType())
2533       GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2534
2535     ArrayType *ATy = ArrayType::get(ETy, NumElements);
2536     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2537
2538     // Verify all elements are correct type!
2539     for (unsigned i = 0; i < $2->size(); i++) {
2540       if (ETy != (*$2)[i]->getType())
2541         GEN_ERROR("Element #" + utostr(i) + " is not of type '" + 
2542                        ETy->getDescription() +"' as required!\nIt is of type '"+
2543                        (*$2)[i]->getType()->getDescription() + "'.");
2544     }
2545
2546     $$ = ValID::create(ConstantArray::get(ATy, *$2));
2547     delete PTy; delete $2;
2548     CHECK_FOR_ERROR
2549   }
2550   | '[' ']' {
2551     // Use undef instead of an array because it's inconvenient to determine
2552     // the element type at this point, there being no elements to examine.
2553     $$ = ValID::createUndef();
2554     CHECK_FOR_ERROR
2555   }
2556   | 'c' STRINGCONSTANT {
2557     uint64_t NumElements = $2->length();
2558     const Type *ETy = Type::Int8Ty;
2559
2560     ArrayType *ATy = ArrayType::get(ETy, NumElements);
2561
2562     std::vector<Constant*> Vals;
2563     for (unsigned i = 0; i < $2->length(); ++i)
2564       Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2565     delete $2;
2566     $$ = ValID::create(ConstantArray::get(ATy, Vals));
2567     CHECK_FOR_ERROR
2568   }
2569   | '{' ConstVector '}' {
2570     std::vector<const Type*> Elements($2->size());
2571     for (unsigned i = 0, e = $2->size(); i != e; ++i)
2572       Elements[i] = (*$2)[i]->getType();
2573
2574     const StructType *STy = StructType::get(Elements);
2575     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2576
2577     $$ = ValID::create(ConstantStruct::get(STy, *$2));
2578     delete PTy; delete $2;
2579     CHECK_FOR_ERROR
2580   }
2581   | '{' '}' {
2582     const StructType *STy = StructType::get(std::vector<const Type*>());
2583     $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2584     CHECK_FOR_ERROR
2585   }
2586   | '<' '{' ConstVector '}' '>' {
2587     std::vector<const Type*> Elements($3->size());
2588     for (unsigned i = 0, e = $3->size(); i != e; ++i)
2589       Elements[i] = (*$3)[i]->getType();
2590
2591     const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2592     PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2593
2594     $$ = ValID::create(ConstantStruct::get(STy, *$3));
2595     delete PTy; delete $3;
2596     CHECK_FOR_ERROR
2597   }
2598   | '<' '{' '}' '>' {
2599     const StructType *STy = StructType::get(std::vector<const Type*>(),
2600                                             /*isPacked=*/true);
2601     $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2602     CHECK_FOR_ERROR
2603   }
2604   | ConstExpr {
2605     $$ = ValID::create($1);
2606     CHECK_FOR_ERROR
2607   }
2608   | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2609     $$ = ValID::createInlineAsm(*$3, *$5, $2);
2610     delete $3;
2611     delete $5;
2612     CHECK_FOR_ERROR
2613   };
2614
2615 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2616 // another value.
2617 //
2618 SymbolicValueRef : LOCALVAL_ID {  // Is it an integer reference...?
2619     $$ = ValID::createLocalID($1);
2620     CHECK_FOR_ERROR
2621   }
2622   | GLOBALVAL_ID {
2623     $$ = ValID::createGlobalID($1);
2624     CHECK_FOR_ERROR
2625   }
2626   | LocalName {                   // Is it a named reference...?
2627     $$ = ValID::createLocalName(*$1);
2628     delete $1;
2629     CHECK_FOR_ERROR
2630   }
2631   | GlobalName {                   // Is it a named reference...?
2632     $$ = ValID::createGlobalName(*$1);
2633     delete $1;
2634     CHECK_FOR_ERROR
2635   };
2636
2637 // ValueRef - A reference to a definition... either constant or symbolic
2638 ValueRef : SymbolicValueRef | ConstValueRef;
2639
2640
2641 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
2642 // type immediately preceeds the value reference, and allows complex constant
2643 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2644 ResolvedVal : Types ValueRef {
2645     if (!UpRefs.empty())
2646       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2647     $$ = getVal(*$1, $2); 
2648     delete $1;
2649     CHECK_FOR_ERROR
2650   }
2651   ;
2652
2653 ReturnedVal : ResolvedVal {
2654     $$ = new std::vector<Value *>();
2655     $$->push_back($1); 
2656     CHECK_FOR_ERROR
2657   }
2658   | ReturnedVal ',' ResolvedVal {
2659     ($$=$1)->push_back($3); 
2660     CHECK_FOR_ERROR
2661   };
2662
2663 BasicBlockList : BasicBlockList BasicBlock {
2664     $$ = $1;
2665     CHECK_FOR_ERROR
2666   }
2667   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
2668     $$ = $1;
2669     CHECK_FOR_ERROR
2670   };
2671
2672
2673 // Basic blocks are terminated by branching instructions: 
2674 // br, br/cc, switch, ret
2675 //
2676 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst  {
2677     setValueName($3, $2);
2678     CHECK_FOR_ERROR
2679     InsertValue($3);
2680     $1->getInstList().push_back($3);
2681     $$ = $1;
2682     CHECK_FOR_ERROR
2683   };
2684
2685 InstructionList : InstructionList Inst {
2686     if (CastInst *CI1 = dyn_cast<CastInst>($2))
2687       if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2688         if (CI2->getParent() == 0)
2689           $1->getInstList().push_back(CI2);
2690     $1->getInstList().push_back($2);
2691     $$ = $1;
2692     CHECK_FOR_ERROR
2693   }
2694   | /* empty */ {          // Empty space between instruction lists
2695     $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2696     CHECK_FOR_ERROR
2697   }
2698   | LABELSTR {             // Labelled (named) basic block
2699     $$ = defineBBVal(ValID::createLocalName(*$1));
2700     delete $1;
2701     CHECK_FOR_ERROR
2702
2703   };
2704
2705 BBTerminatorInst : 
2706   RET ReturnedVal  { // Return with a result...
2707     ValueList &VL = *$2;
2708     assert(!VL.empty() && "Invalid ret operands!");
2709     const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2710     if (VL.size() > 1 ||
2711         (isa<StructType>(ReturnType) &&
2712          (VL.empty() || VL[0]->getType() != ReturnType))) {
2713       Value *RV = UndefValue::get(ReturnType);
2714       for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2715         Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2716         ($<BasicBlockVal>-1)->getInstList().push_back(I);
2717         RV = I;
2718       }
2719       $$ = ReturnInst::Create(RV);
2720     } else {
2721       $$ = ReturnInst::Create(VL[0]);
2722     }
2723     delete $2;
2724     CHECK_FOR_ERROR
2725   }
2726   | RET VOID {                                    // Return with no result...
2727     $$ = ReturnInst::Create();
2728     CHECK_FOR_ERROR
2729   }
2730   | BR LABEL ValueRef {                           // Unconditional Branch...
2731     BasicBlock* tmpBB = getBBVal($3);
2732     CHECK_FOR_ERROR
2733     $$ = BranchInst::Create(tmpBB);
2734   }                                               // Conditional Branch...
2735   | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
2736     if (cast<IntegerType>($2)->getBitWidth() != 1)
2737       GEN_ERROR("Branch condition must have type i1");
2738     BasicBlock* tmpBBA = getBBVal($6);
2739     CHECK_FOR_ERROR
2740     BasicBlock* tmpBBB = getBBVal($9);
2741     CHECK_FOR_ERROR
2742     Value* tmpVal = getVal(Type::Int1Ty, $3);
2743     CHECK_FOR_ERROR
2744     $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2745   }
2746   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2747     Value* tmpVal = getVal($2, $3);
2748     CHECK_FOR_ERROR
2749     BasicBlock* tmpBB = getBBVal($6);
2750     CHECK_FOR_ERROR
2751     SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2752     $$ = S;
2753
2754     std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2755       E = $8->end();
2756     for (; I != E; ++I) {
2757       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2758           S->addCase(CI, I->second);
2759       else
2760         GEN_ERROR("Switch case is constant, but not a simple integer");
2761     }
2762     delete $8;
2763     CHECK_FOR_ERROR
2764   }
2765   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2766     Value* tmpVal = getVal($2, $3);
2767     CHECK_FOR_ERROR
2768     BasicBlock* tmpBB = getBBVal($6);
2769     CHECK_FOR_ERROR
2770     SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2771     $$ = S;
2772     CHECK_FOR_ERROR
2773   }
2774   | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2775     TO LABEL ValueRef UNWIND LABEL ValueRef {
2776
2777     // Handle the short syntax
2778     const PointerType *PFTy = 0;
2779     const FunctionType *Ty = 0;
2780     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2781         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2782       // Pull out the types of all of the arguments...
2783       std::vector<const Type*> ParamTypes;
2784       ParamList::iterator I = $6->begin(), E = $6->end();
2785       for (; I != E; ++I) {
2786         const Type *Ty = I->Val->getType();
2787         if (Ty == Type::VoidTy)
2788           GEN_ERROR("Short call syntax cannot be used with varargs");
2789         ParamTypes.push_back(Ty);
2790       }
2791       
2792       if (!FunctionType::isValidReturnType(*$3))
2793         GEN_ERROR("Invalid result type for LLVM function");
2794
2795       Ty = FunctionType::get($3->get(), ParamTypes, false);
2796       PFTy = PointerType::getUnqual(Ty);
2797     }
2798
2799     delete $3;
2800
2801     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
2802     CHECK_FOR_ERROR
2803     BasicBlock *Normal = getBBVal($11);
2804     CHECK_FOR_ERROR
2805     BasicBlock *Except = getBBVal($14);
2806     CHECK_FOR_ERROR
2807
2808     SmallVector<ParamAttrsWithIndex, 8> Attrs;
2809     if ($8 != ParamAttr::None)
2810       Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
2811
2812     // Check the arguments
2813     ValueList Args;
2814     if ($6->empty()) {                                   // Has no arguments?
2815       // Make sure no arguments is a good thing!
2816       if (Ty->getNumParams() != 0)
2817         GEN_ERROR("No arguments passed to a function that "
2818                        "expects arguments");
2819     } else {                                     // Has arguments?
2820       // Loop through FunctionType's arguments and ensure they are specified
2821       // correctly!
2822       FunctionType::param_iterator I = Ty->param_begin();
2823       FunctionType::param_iterator E = Ty->param_end();
2824       ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2825       unsigned index = 1;
2826
2827       for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2828         if (ArgI->Val->getType() != *I)
2829           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2830                          (*I)->getDescription() + "'");
2831         Args.push_back(ArgI->Val);
2832         if (ArgI->Attrs != ParamAttr::None)
2833           Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2834       }
2835
2836       if (Ty->isVarArg()) {
2837         if (I == E)
2838           for (; ArgI != ArgE; ++ArgI, ++index) {
2839             Args.push_back(ArgI->Val); // push the remaining varargs
2840             if (ArgI->Attrs != ParamAttr::None)
2841               Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2842           }
2843       } else if (I != E || ArgI != ArgE)
2844         GEN_ERROR("Invalid number of parameters detected");
2845     }
2846
2847     PAListPtr PAL;
2848     if (!Attrs.empty())
2849       PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2850
2851     // Create the InvokeInst
2852     InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2853                                         Args.begin(), Args.end());
2854     II->setCallingConv($2);
2855     II->setParamAttrs(PAL);
2856     $$ = II;
2857     delete $6;
2858     CHECK_FOR_ERROR
2859   }
2860   | UNWIND {
2861     $$ = new UnwindInst();
2862     CHECK_FOR_ERROR
2863   }
2864   | UNREACHABLE {
2865     $$ = new UnreachableInst();
2866     CHECK_FOR_ERROR
2867   };
2868
2869
2870
2871 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2872     $$ = $1;
2873     Constant *V = cast<Constant>(getExistingVal($2, $3));
2874     CHECK_FOR_ERROR
2875     if (V == 0)
2876       GEN_ERROR("May only switch on a constant pool value");
2877
2878     BasicBlock* tmpBB = getBBVal($6);
2879     CHECK_FOR_ERROR
2880     $$->push_back(std::make_pair(V, tmpBB));
2881   }
2882   | IntType ConstValueRef ',' LABEL ValueRef {
2883     $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2884     Constant *V = cast<Constant>(getExistingVal($1, $2));
2885     CHECK_FOR_ERROR
2886
2887     if (V == 0)
2888       GEN_ERROR("May only switch on a constant pool value");
2889
2890     BasicBlock* tmpBB = getBBVal($5);
2891     CHECK_FOR_ERROR
2892     $$->push_back(std::make_pair(V, tmpBB)); 
2893   };
2894
2895 Inst : OptLocalAssign InstVal {
2896     // Is this definition named?? if so, assign the name...
2897     setValueName($2, $1);
2898     CHECK_FOR_ERROR
2899     InsertValue($2);
2900     $$ = $2;
2901     CHECK_FOR_ERROR
2902   };
2903
2904
2905 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
2906     if (!UpRefs.empty())
2907       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2908     $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2909     Value* tmpVal = getVal(*$1, $3);
2910     CHECK_FOR_ERROR
2911     BasicBlock* tmpBB = getBBVal($5);
2912     CHECK_FOR_ERROR
2913     $$->push_back(std::make_pair(tmpVal, tmpBB));
2914     delete $1;
2915   }
2916   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2917     $$ = $1;
2918     Value* tmpVal = getVal($1->front().first->getType(), $4);
2919     CHECK_FOR_ERROR
2920     BasicBlock* tmpBB = getBBVal($6);
2921     CHECK_FOR_ERROR
2922     $1->push_back(std::make_pair(tmpVal, tmpBB));
2923   };
2924
2925
2926 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2927     // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2928     if (!UpRefs.empty())
2929       GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2930     // Used for call and invoke instructions
2931     $$ = new ParamList();
2932     ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2933     $$->push_back(E);
2934     delete $1;
2935     CHECK_FOR_ERROR
2936   }
2937   | LABEL OptParamAttrs ValueRef OptParamAttrs {
2938     // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2939     // Labels are only valid in ASMs
2940     $$ = new ParamList();
2941     ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2942     $$->push_back(E);
2943     CHECK_FOR_ERROR
2944   }
2945   | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2946     // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2947     if (!UpRefs.empty())
2948       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2949     $$ = $1;
2950     ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2951     $$->push_back(E);
2952     delete $3;
2953     CHECK_FOR_ERROR
2954   }
2955   | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2956     // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2957     $$ = $1;
2958     ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2959     $$->push_back(E);
2960     CHECK_FOR_ERROR
2961   }
2962   | /*empty*/ { $$ = new ParamList(); };
2963
2964 IndexList       // Used for gep instructions and constant expressions
2965   : /*empty*/ { $$ = new std::vector<Value*>(); }
2966   | IndexList ',' ResolvedVal {
2967     $$ = $1;
2968     $$->push_back($3);
2969     CHECK_FOR_ERROR
2970   }
2971   ;
2972
2973 ConstantIndexList       // Used for insertvalue and extractvalue instructions
2974   : ',' EUINT64VAL {
2975     $$ = new std::vector<unsigned>();
2976     if ((unsigned)$2 != $2)
2977       GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
2978     $$->push_back($2);
2979   }
2980   | ConstantIndexList ',' EUINT64VAL {
2981     $$ = $1;
2982     if ((unsigned)$3 != $3)
2983       GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
2984     $$->push_back($3);
2985     CHECK_FOR_ERROR
2986   }
2987   ;
2988
2989 OptTailCall : TAIL CALL {
2990     $$ = true;
2991     CHECK_FOR_ERROR
2992   }
2993   | CALL {
2994     $$ = false;
2995     CHECK_FOR_ERROR
2996   };
2997
2998 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2999     if (!UpRefs.empty())
3000       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3001     if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() && 
3002         !isa<VectorType>((*$2).get()))
3003       GEN_ERROR(
3004         "Arithmetic operator requires integer, FP, or packed operands");
3005     Value* val1 = getVal(*$2, $3); 
3006     CHECK_FOR_ERROR
3007     Value* val2 = getVal(*$2, $5);
3008     CHECK_FOR_ERROR
3009     $$ = BinaryOperator::Create($1, val1, val2);
3010     if ($$ == 0)
3011       GEN_ERROR("binary operator returned null");
3012     delete $2;
3013   }
3014   | LogicalOps Types ValueRef ',' ValueRef {
3015     if (!UpRefs.empty())
3016       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3017     if (!(*$2)->isInteger()) {
3018       if (!isa<VectorType>($2->get()) ||
3019           !cast<VectorType>($2->get())->getElementType()->isInteger())
3020         GEN_ERROR("Logical operator requires integral operands");
3021     }
3022     Value* tmpVal1 = getVal(*$2, $3);
3023     CHECK_FOR_ERROR
3024     Value* tmpVal2 = getVal(*$2, $5);
3025     CHECK_FOR_ERROR
3026     $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3027     if ($$ == 0)
3028       GEN_ERROR("binary operator returned null");
3029     delete $2;
3030   }
3031   | ICMP IPredicates Types ValueRef ',' ValueRef  {
3032     if (!UpRefs.empty())
3033       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3034     if (isa<VectorType>((*$3).get()))
3035       GEN_ERROR("Vector types not supported by icmp instruction");
3036     Value* tmpVal1 = getVal(*$3, $4);
3037     CHECK_FOR_ERROR
3038     Value* tmpVal2 = getVal(*$3, $6);
3039     CHECK_FOR_ERROR
3040     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3041     if ($$ == 0)
3042       GEN_ERROR("icmp operator returned null");
3043     delete $3;
3044   }
3045   | FCMP FPredicates Types ValueRef ',' ValueRef  {
3046     if (!UpRefs.empty())
3047       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3048     if (isa<VectorType>((*$3).get()))
3049       GEN_ERROR("Vector types not supported by fcmp instruction");
3050     Value* tmpVal1 = getVal(*$3, $4);
3051     CHECK_FOR_ERROR
3052     Value* tmpVal2 = getVal(*$3, $6);
3053     CHECK_FOR_ERROR
3054     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3055     if ($$ == 0)
3056       GEN_ERROR("fcmp operator returned null");
3057     delete $3;
3058   }
3059   | VICMP IPredicates Types ValueRef ',' ValueRef  {
3060     if (!UpRefs.empty())
3061       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3062     if (!isa<VectorType>((*$3).get()))
3063       GEN_ERROR("Scalar types not supported by vicmp instruction");
3064     Value* tmpVal1 = getVal(*$3, $4);
3065     CHECK_FOR_ERROR
3066     Value* tmpVal2 = getVal(*$3, $6);
3067     CHECK_FOR_ERROR
3068     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3069     if ($$ == 0)
3070       GEN_ERROR("icmp operator returned null");
3071     delete $3;
3072   }
3073   | VFCMP FPredicates Types ValueRef ',' ValueRef  {
3074     if (!UpRefs.empty())
3075       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3076     if (!isa<VectorType>((*$3).get()))
3077       GEN_ERROR("Scalar types not supported by vfcmp instruction");
3078     Value* tmpVal1 = getVal(*$3, $4);
3079     CHECK_FOR_ERROR
3080     Value* tmpVal2 = getVal(*$3, $6);
3081     CHECK_FOR_ERROR
3082     $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3083     if ($$ == 0)
3084       GEN_ERROR("fcmp operator returned null");
3085     delete $3;
3086   }
3087   | CastOps ResolvedVal TO Types {
3088     if (!UpRefs.empty())
3089       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3090     Value* Val = $2;
3091     const Type* DestTy = $4->get();
3092     if (!CastInst::castIsValid($1, Val, DestTy))
3093       GEN_ERROR("invalid cast opcode for cast from '" +
3094                 Val->getType()->getDescription() + "' to '" +
3095                 DestTy->getDescription() + "'"); 
3096     $$ = CastInst::Create($1, Val, DestTy);
3097     delete $4;
3098   }
3099   | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3100     if ($2->getType() != Type::Int1Ty)
3101       GEN_ERROR("select condition must be boolean");
3102     if ($4->getType() != $6->getType())
3103       GEN_ERROR("select value types should match");
3104     $$ = SelectInst::Create($2, $4, $6);
3105     CHECK_FOR_ERROR
3106   }
3107   | VAARG ResolvedVal ',' Types {
3108     if (!UpRefs.empty())
3109       GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3110     $$ = new VAArgInst($2, *$4);
3111     delete $4;
3112     CHECK_FOR_ERROR
3113   }
3114   | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3115     if (!ExtractElementInst::isValidOperands($2, $4))
3116       GEN_ERROR("Invalid extractelement operands");
3117     $$ = new ExtractElementInst($2, $4);
3118     CHECK_FOR_ERROR
3119   }
3120   | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3121     if (!InsertElementInst::isValidOperands($2, $4, $6))
3122       GEN_ERROR("Invalid insertelement operands");
3123     $$ = InsertElementInst::Create($2, $4, $6);
3124     CHECK_FOR_ERROR
3125   }
3126   | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3127     if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3128       GEN_ERROR("Invalid shufflevector operands");
3129     $$ = new ShuffleVectorInst($2, $4, $6);
3130     CHECK_FOR_ERROR
3131   }
3132   | PHI_TOK PHIList {
3133     const Type *Ty = $2->front().first->getType();
3134     if (!Ty->isFirstClassType())
3135       GEN_ERROR("PHI node operands must be of first class type");
3136     $$ = PHINode::Create(Ty);
3137     ((PHINode*)$$)->reserveOperandSpace($2->size());
3138     while ($2->begin() != $2->end()) {
3139       if ($2->front().first->getType() != Ty) 
3140         GEN_ERROR("All elements of a PHI node must be of the same type");
3141       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3142       $2->pop_front();
3143     }
3144     delete $2;  // Free the list...
3145     CHECK_FOR_ERROR
3146   }
3147   | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')' 
3148     OptFuncAttrs {
3149
3150     // Handle the short syntax
3151     const PointerType *PFTy = 0;
3152     const FunctionType *Ty = 0;
3153     if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3154         !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3155       // Pull out the types of all of the arguments...
3156       std::vector<const Type*> ParamTypes;
3157       ParamList::iterator I = $6->begin(), E = $6->end();
3158       for (; I != E; ++I) {
3159         const Type *Ty = I->Val->getType();
3160         if (Ty == Type::VoidTy)
3161           GEN_ERROR("Short call syntax cannot be used with varargs");
3162         ParamTypes.push_back(Ty);
3163       }
3164
3165       if (!FunctionType::isValidReturnType(*$3))
3166         GEN_ERROR("Invalid result type for LLVM function");
3167
3168       Ty = FunctionType::get($3->get(), ParamTypes, false);
3169       PFTy = PointerType::getUnqual(Ty);
3170     }
3171
3172     Value *V = getVal(PFTy, $4);   // Get the function we're calling...
3173     CHECK_FOR_ERROR
3174
3175     // Check for call to invalid intrinsic to avoid crashing later.
3176     if (Function *theF = dyn_cast<Function>(V)) {
3177       if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3178           (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3179           !theF->getIntrinsicID(true))
3180         GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3181                   theF->getName() + "'");
3182     }
3183
3184     // Set up the ParamAttrs for the function
3185     SmallVector<ParamAttrsWithIndex, 8> Attrs;
3186     if ($8 != ParamAttr::None)
3187       Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
3188     // Check the arguments 
3189     ValueList Args;
3190     if ($6->empty()) {                                   // Has no arguments?
3191       // Make sure no arguments is a good thing!
3192       if (Ty->getNumParams() != 0)
3193         GEN_ERROR("No arguments passed to a function that "
3194                        "expects arguments");
3195     } else {                                     // Has arguments?
3196       // Loop through FunctionType's arguments and ensure they are specified
3197       // correctly.  Also, gather any parameter attributes.
3198       FunctionType::param_iterator I = Ty->param_begin();
3199       FunctionType::param_iterator E = Ty->param_end();
3200       ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3201       unsigned index = 1;
3202
3203       for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3204         if (ArgI->Val->getType() != *I)
3205           GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3206                          (*I)->getDescription() + "'");
3207         Args.push_back(ArgI->Val);
3208         if (ArgI->Attrs != ParamAttr::None)
3209           Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3210       }
3211       if (Ty->isVarArg()) {
3212         if (I == E)
3213           for (; ArgI != ArgE; ++ArgI, ++index) {
3214             Args.push_back(ArgI->Val); // push the remaining varargs
3215             if (ArgI->Attrs != ParamAttr::None)
3216               Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3217           }
3218       } else if (I != E || ArgI != ArgE)
3219         GEN_ERROR("Invalid number of parameters detected");
3220     }
3221
3222     // Finish off the ParamAttrs and check them
3223     PAListPtr PAL;
3224     if (!Attrs.empty())
3225       PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
3226
3227     // Create the call node
3228     CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3229     CI->setTailCall($1);
3230     CI->setCallingConv($2);
3231     CI->setParamAttrs(PAL);
3232     $$ = CI;
3233     delete $6;
3234     delete $3;
3235     CHECK_FOR_ERROR
3236   }
3237   | MemoryInst {
3238     $$ = $1;
3239     CHECK_FOR_ERROR
3240   };
3241
3242 OptVolatile : VOLATILE {
3243     $$ = true;
3244     CHECK_FOR_ERROR
3245   }
3246   | /* empty */ {
3247     $$ = false;
3248     CHECK_FOR_ERROR
3249   };
3250
3251
3252
3253 MemoryInst : MALLOC Types OptCAlign {
3254     if (!UpRefs.empty())
3255       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3256     $$ = new MallocInst(*$2, 0, $3);
3257     delete $2;
3258     CHECK_FOR_ERROR
3259   }
3260   | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3261     if (!UpRefs.empty())
3262       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3263     if ($4 != Type::Int32Ty)
3264       GEN_ERROR("Malloc array size is not a 32-bit integer!");
3265     Value* tmpVal = getVal($4, $5);
3266     CHECK_FOR_ERROR
3267     $$ = new MallocInst(*$2, tmpVal, $6);
3268     delete $2;
3269   }
3270   | ALLOCA Types OptCAlign {
3271     if (!UpRefs.empty())
3272       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3273     $$ = new AllocaInst(*$2, 0, $3);
3274     delete $2;
3275     CHECK_FOR_ERROR
3276   }
3277   | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3278     if (!UpRefs.empty())
3279       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3280     if ($4 != Type::Int32Ty)
3281       GEN_ERROR("Alloca array size is not a 32-bit integer!");
3282     Value* tmpVal = getVal($4, $5);
3283     CHECK_FOR_ERROR
3284     $$ = new AllocaInst(*$2, tmpVal, $6);
3285     delete $2;
3286   }
3287   | FREE ResolvedVal {
3288     if (!isa<PointerType>($2->getType()))
3289       GEN_ERROR("Trying to free nonpointer type " + 
3290                      $2->getType()->getDescription() + "");
3291     $$ = new FreeInst($2);
3292     CHECK_FOR_ERROR
3293   }
3294
3295   | OptVolatile LOAD Types ValueRef OptCAlign {
3296     if (!UpRefs.empty())
3297       GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3298     if (!isa<PointerType>($3->get()))
3299       GEN_ERROR("Can't load from nonpointer type: " +
3300                      (*$3)->getDescription());
3301     if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3302       GEN_ERROR("Can't load from pointer of non-first-class type: " +
3303                      (*$3)->getDescription());
3304     Value* tmpVal = getVal(*$3, $4);
3305     CHECK_FOR_ERROR
3306     $$ = new LoadInst(tmpVal, "", $1, $5);
3307     delete $3;
3308   }
3309   | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3310     if (!UpRefs.empty())
3311       GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3312     const PointerType *PT = dyn_cast<PointerType>($5->get());
3313     if (!PT)
3314       GEN_ERROR("Can't store to a nonpointer type: " +
3315                      (*$5)->getDescription());
3316     const Type *ElTy = PT->getElementType();
3317     if (ElTy != $3->getType())
3318       GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3319                      "' into space of type '" + ElTy->getDescription() + "'");
3320
3321     Value* tmpVal = getVal(*$5, $6);
3322     CHECK_FOR_ERROR
3323     $$ = new StoreInst($3, tmpVal, $1, $7);
3324     delete $5;
3325   }
3326   | GETRESULT Types ValueRef ',' EUINT64VAL  {
3327     if (!UpRefs.empty())
3328       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3329     if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3330       GEN_ERROR("getresult insn requires an aggregate operand");
3331     if (!ExtractValueInst::getIndexedType(*$2, $5))
3332       GEN_ERROR("Invalid getresult index for type '" +
3333                      (*$2)->getDescription()+ "'");
3334
3335     Value *tmpVal = getVal(*$2, $3);
3336     CHECK_FOR_ERROR
3337     $$ = ExtractValueInst::Create(tmpVal, $5);
3338     delete $2;
3339   }
3340   | GETELEMENTPTR Types ValueRef IndexList {
3341     if (!UpRefs.empty())
3342       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3343     if (!isa<PointerType>($2->get()))
3344       GEN_ERROR("getelementptr insn requires pointer operand");
3345
3346     if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3347       GEN_ERROR("Invalid getelementptr indices for type '" +
3348                      (*$2)->getDescription()+ "'");
3349     Value* tmpVal = getVal(*$2, $3);
3350     CHECK_FOR_ERROR
3351     $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3352     delete $2; 
3353     delete $4;
3354   }
3355   | EXTRACTVALUE Types ValueRef ConstantIndexList {
3356     if (!UpRefs.empty())
3357       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3358     if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3359       GEN_ERROR("extractvalue insn requires an aggregate operand");
3360
3361     if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3362       GEN_ERROR("Invalid extractvalue indices for type '" +
3363                      (*$2)->getDescription()+ "'");
3364     Value* tmpVal = getVal(*$2, $3);
3365     CHECK_FOR_ERROR
3366     $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3367     delete $2; 
3368     delete $4;
3369   }
3370   | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3371     if (!UpRefs.empty())
3372       GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3373     if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3374       GEN_ERROR("extractvalue insn requires an aggregate operand");
3375
3376     if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3377       GEN_ERROR("Invalid insertvalue indices for type '" +
3378                      (*$2)->getDescription()+ "'");
3379     Value* aggVal = getVal(*$2, $3);
3380     Value* tmpVal = getVal(*$5, $6);
3381     CHECK_FOR_ERROR
3382     $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3383     delete $2; 
3384     delete $5;
3385     delete $7;
3386   };
3387
3388
3389 %%
3390
3391 // common code from the two 'RunVMAsmParser' functions
3392 static Module* RunParser(Module * M) {
3393   CurModule.CurrentModule = M;
3394   // Check to make sure the parser succeeded
3395   if (yyparse()) {
3396     if (ParserResult)
3397       delete ParserResult;
3398     return 0;
3399   }
3400
3401   // Emit an error if there are any unresolved types left.
3402   if (!CurModule.LateResolveTypes.empty()) {
3403     const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3404     if (DID.Type == ValID::LocalName) {
3405       GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3406     } else {
3407       GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3408     }
3409     if (ParserResult)
3410       delete ParserResult;
3411     return 0;
3412   }
3413
3414   // Emit an error if there are any unresolved values left.
3415   if (!CurModule.LateResolveValues.empty()) {
3416     Value *V = CurModule.LateResolveValues.back();
3417     std::map<Value*, std::pair<ValID, int> >::iterator I =
3418       CurModule.PlaceHolderInfo.find(V);
3419
3420     if (I != CurModule.PlaceHolderInfo.end()) {
3421       ValID &DID = I->second.first;
3422       if (DID.Type == ValID::LocalName) {
3423         GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3424       } else {
3425         GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3426       }
3427       if (ParserResult)
3428         delete ParserResult;
3429       return 0;
3430     }
3431   }
3432
3433   // Check to make sure that parsing produced a result
3434   if (!ParserResult)
3435     return 0;
3436
3437   // Reset ParserResult variable while saving its value for the result.
3438   Module *Result = ParserResult;
3439   ParserResult = 0;
3440
3441   return Result;
3442 }
3443
3444 void llvm::GenerateError(const std::string &message, int LineNo) {
3445   if (LineNo == -1) LineNo = LLLgetLineNo();
3446   // TODO: column number in exception
3447   if (TheParseError)
3448     TheParseError->setError(LLLgetFilename(), message, LineNo);
3449   TriggerError = 1;
3450 }
3451
3452 int yyerror(const char *ErrorMsg) {
3453   std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3454   std::string errMsg = where + "error: " + std::string(ErrorMsg);
3455   if (yychar != YYEMPTY && yychar != 0) {
3456     errMsg += " while reading token: '";
3457     errMsg += std::string(LLLgetTokenStart(), 
3458                           LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3459   }
3460   GenerateError(errMsg);
3461   return 0;
3462 }