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