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