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