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