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