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