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