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