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