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