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