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