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