43c69f3a08ad4b28d8b90bc947c29ba4313b81bc
[oota-llvm.git] / lib / AsmParser / llvmAsmParser.y
1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
2 //
3 //  This file implements the bison parser for LLVM assembly languages files.
4 //
5 //===------------------------------------------------------------------------=//
6
7 //
8 // TODO: Parse comments and add them to an internal node... so that they may
9 // be saved in the bytecode format as well as everything else.  Very important
10 // for a general IR format.
11 //
12
13 %{
14 #include "ParserInternals.h"
15 #include "llvm/Assembly/Parser.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Method.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/iMemory.h"
24 #include "llvm/Support/STLExtras.h"
25 #include "llvm/Support/DepthFirstIterator.h"
26 #include <list>
27 #include <utility>            // Get definition of pair class
28 #include <algorithm>
29 #include <stdio.h>            // This embarasment is due to our flex lexer...
30
31 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit 
32 int yylex();                       // declaration" of xxx warnings.
33 int yyparse();
34
35 static Module *ParserResult;
36 string CurFilename;
37
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
40 //
41 //#define DEBUG_UPREFS 1
42 #ifdef DEBUG_UPREFS
43 #define UR_OUT(X) cerr << X
44 #else
45 #define UR_OUT(X)
46 #endif
47
48 // This contains info used when building the body of a method.  It is destroyed
49 // when the method is completed.
50 //
51 typedef vector<Value *> ValueList;           // Numbered defs
52 static void ResolveDefinitions(vector<ValueList> &LateResolvers);
53 static void ResolveTypes      (vector<PATypeHolder<Type> > &LateResolveTypes);
54
55 static struct PerModuleInfo {
56   Module *CurrentModule;
57   vector<ValueList>    Values;     // Module level numbered definitions
58   vector<ValueList>    LateResolveValues;
59   vector<PATypeHolder<Type> > Types, LateResolveTypes;
60
61   void ModuleDone() {
62     // If we could not resolve some methods at method compilation time (calls to
63     // methods before they are defined), resolve them now...  Types are resolved
64     // when the constant pool has been completely parsed.
65     //
66     ResolveDefinitions(LateResolveValues);
67
68     Values.clear();         // Clear out method local definitions
69     Types.clear();
70     CurrentModule = 0;
71   }
72 } CurModule;
73
74 static struct PerMethodInfo {
75   Method *CurrentMethod;         // Pointer to current method being created
76
77   vector<ValueList> Values;      // Keep track of numbered definitions
78   vector<ValueList> LateResolveValues;
79   vector<PATypeHolder<Type> > Types, LateResolveTypes;
80   bool isDeclare;                // Is this method a forward declararation?
81
82   inline PerMethodInfo() {
83     CurrentMethod = 0;
84     isDeclare = false;
85   }
86
87   inline ~PerMethodInfo() {}
88
89   inline void MethodStart(Method *M) {
90     CurrentMethod = M;
91   }
92
93   void MethodDone() {
94     // If we could not resolve some blocks at parsing time (forward branches)
95     // resolve the branches now...
96     ResolveDefinitions(LateResolveValues);
97
98     Values.clear();         // Clear out method local definitions
99     Types.clear();
100     CurrentMethod = 0;
101     isDeclare = false;
102   }
103 } CurMeth;  // Info for the current method...
104
105
106 //===----------------------------------------------------------------------===//
107 //               Code to handle definitions of all the types
108 //===----------------------------------------------------------------------===//
109
110 static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values){
111   if (!D->hasName()) {             // Is this a numbered definition?
112     unsigned type = D->getType()->getUniqueID();
113     if (ValueTab.size() <= type)
114       ValueTab.resize(type+1, ValueList());
115     //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
116     ValueTab[type].push_back(D);
117   }
118 }
119
120 // TODO: FIXME when Type are not const
121 static void InsertType(const Type *Ty, vector<PATypeHolder<Type> > &Types) {
122   Types.push_back(Ty);
123 }
124
125 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
126   switch (D.Type) {
127   case 0: {                 // Is it a numbered definition?
128     unsigned Num = (unsigned)D.Num;
129
130     // Module constants occupy the lowest numbered slots...
131     if (Num < CurModule.Types.size()) 
132       return CurModule.Types[Num];
133
134     Num -= CurModule.Types.size();
135
136     // Check that the number is within bounds...
137     if (Num <= CurMeth.Types.size())
138       return CurMeth.Types[Num];
139   }
140   case 1: {                // Is it a named definition?
141     string Name(D.Name);
142     SymbolTable *SymTab = 0;
143     if (CurMeth.CurrentMethod) 
144       SymTab = CurMeth.CurrentMethod->getSymbolTable();
145     Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
146
147     if (N == 0) {
148       // Symbol table doesn't automatically chain yet... because the method
149       // hasn't been added to the module...
150       //
151       SymTab = CurModule.CurrentModule->getSymbolTable();
152       if (SymTab)
153         N = SymTab->lookup(Type::TypeTy, Name);
154       if (N == 0) break;
155     }
156
157     D.destroy();  // Free old strdup'd memory...
158     return cast<const Type>(N);
159   }
160   default:
161     ThrowException("Invalid symbol type reference!");
162   }
163
164   // If we reached here, we referenced either a symbol that we don't know about
165   // or an id number that hasn't been read yet.  We may be referencing something
166   // forward, so just create an entry to be resolved later and get to it...
167   //
168   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
169
170   vector<PATypeHolder<Type> > *LateResolver = CurMeth.CurrentMethod ? 
171     &CurMeth.LateResolveTypes : &CurModule.LateResolveTypes;
172
173   Type *Typ = new TypePlaceHolder(Type::TypeTy, D);
174   InsertType(Typ, *LateResolver);
175   return Typ;
176 }
177
178 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
179   SymbolTable *SymTab = 
180     CurMeth.CurrentMethod ? CurMeth.CurrentMethod->getSymbolTable() : 0;
181   Value *N = SymTab ? SymTab->lookup(Ty, Name) : 0;
182
183   if (N == 0) {
184     // Symbol table doesn't automatically chain yet... because the method
185     // hasn't been added to the module...
186     //
187     SymTab = CurModule.CurrentModule->getSymbolTable();
188     if (SymTab)
189       N = SymTab->lookup(Ty, Name);
190   }
191
192   return N;
193 }
194
195 static Value *getVal(const Type *Ty, const ValID &D, 
196                      bool DoNotImprovise = false) {
197   assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
198
199   switch (D.Type) {
200   case ValID::NumberVal: {                 // Is it a numbered definition?
201     unsigned type = Ty->getUniqueID();
202     unsigned Num = (unsigned)D.Num;
203
204     // Module constants occupy the lowest numbered slots...
205     if (type < CurModule.Values.size()) {
206       if (Num < CurModule.Values[type].size()) 
207         return CurModule.Values[type][Num];
208
209       Num -= CurModule.Values[type].size();
210     }
211
212     // Make sure that our type is within bounds
213     if (CurMeth.Values.size() <= type)
214       break;
215
216     // Check that the number is within bounds...
217     if (CurMeth.Values[type].size() <= Num)
218       break;
219   
220     return CurMeth.Values[type][Num];
221   }
222   case ValID::NameVal: {                // Is it a named definition?
223     string Name(D.Name);
224     Value *N = lookupInSymbolTable(Ty, Name);
225     if (N == 0) break;
226
227     D.destroy();  // Free old strdup'd memory...
228     return N;
229   }
230
231   case ValID::ConstSIntVal:     // Is it a constant pool reference??
232   case ValID::ConstUIntVal:     // Is it an unsigned const pool reference?
233   case ValID::ConstStringVal:   // Is it a string const pool reference?
234   case ValID::ConstFPVal:       // Is it a floating point const pool reference?
235   case ValID::ConstNullVal: {   // Is it a null value?
236     ConstPoolVal *CPV = 0;
237
238     // Check to make sure that "Ty" is an integral type, and that our 
239     // value will fit into the specified type...
240     switch (D.Type) {
241     case ValID::ConstSIntVal:
242       if (Ty == Type::BoolTy) {  // Special handling for boolean data
243         CPV = ConstPoolBool::get(D.ConstPool64 != 0);
244       } else {
245         if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64))
246           ThrowException("Symbolic constant pool value '" +
247                          itostr(D.ConstPool64) + "' is invalid for type '" + 
248                          Ty->getName() + "'!");
249         CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
250       }
251       break;
252     case ValID::ConstUIntVal:
253       if (!ConstPoolUInt::isValueValidForType(Ty, D.UConstPool64)) {
254         if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64)) {
255           ThrowException("Integral constant pool reference is invalid!");
256         } else {     // This is really a signed reference.  Transmogrify.
257           CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
258         }
259       } else {
260         CPV = ConstPoolUInt::get(Ty, D.UConstPool64);
261       }
262       break;
263     case ValID::ConstStringVal:
264       cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
265       abort();
266       break;
267     case ValID::ConstFPVal:
268       if (!ConstPoolFP::isValueValidForType(Ty, D.ConstPoolFP))
269         ThrowException("FP constant invalid for type!!");
270       CPV = ConstPoolFP::get(Ty, D.ConstPoolFP);
271       break;
272     case ValID::ConstNullVal:
273       if (!Ty->isPointerType())
274         ThrowException("Cannot create a a non pointer null!");
275       CPV = ConstPoolPointer::getNullPointer(cast<PointerType>(Ty));
276       break;
277     default:
278       assert(0 && "Unhandled case!");
279     }
280     assert(CPV && "How did we escape creating a constant??");
281     return CPV;
282   }   // End of case 2,3,4
283   default:
284     assert(0 && "Unhandled case!");
285   }   // End of switch
286
287
288   // If we reached here, we referenced either a symbol that we don't know about
289   // or an id number that hasn't been read yet.  We may be referencing something
290   // forward, so just create an entry to be resolved later and get to it...
291   //
292   if (DoNotImprovise) return 0;  // Do we just want a null to be returned?
293
294   Value *d = 0;
295   vector<ValueList> *LateResolver =  (CurMeth.CurrentMethod) ? 
296     &CurMeth.LateResolveValues : &CurModule.LateResolveValues;
297
298   if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
299     if (const MethodType *MTy = dyn_cast<MethodType>(PTy->getValueType()))
300       Ty = MTy;       // Convert pointer to method to method type
301
302   switch (Ty->getPrimitiveID()) {
303   case Type::LabelTyID:  d = new   BBPlaceHolder(Ty, D); break;
304   case Type::MethodTyID: d = new MethPlaceHolder(Ty, D); 
305                          LateResolver = &CurModule.LateResolveValues; break;
306   default:               d = new ValuePlaceHolder(Ty, D); break;
307   }
308
309   assert(d != 0 && "How did we not make something?");
310   InsertValue(d, *LateResolver);
311   return d;
312 }
313
314
315 //===----------------------------------------------------------------------===//
316 //              Code to handle forward references in instructions
317 //===----------------------------------------------------------------------===//
318 //
319 // This code handles the late binding needed with statements that reference
320 // values not defined yet... for example, a forward branch, or the PHI node for
321 // a loop body.
322 //
323 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
324 // and back patchs after we are done.
325 //
326
327 // ResolveDefinitions - If we could not resolve some defs at parsing 
328 // time (forward branches, phi functions for loops, etc...) resolve the 
329 // defs now...
330 //
331 static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
332   // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
333   for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
334     while (!LateResolvers[ty].empty()) {
335       Value *V = LateResolvers[ty].back();
336       LateResolvers[ty].pop_back();
337       ValID &DID = getValIDFromPlaceHolder(V);
338
339       Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
340
341       if (TheRealValue == 0) {
342         if (DID.Type == 1)
343           ThrowException("Reference to an invalid definition: '" +DID.getName()+
344                          "' of type '" + V->getType()->getDescription() + "'",
345                          getLineNumFromPlaceHolder(V));
346         else
347           ThrowException("Reference to an invalid definition: #" +
348                          itostr(DID.Num) + " of type '" + 
349                          V->getType()->getDescription() + "'",
350                          getLineNumFromPlaceHolder(V));
351       }
352
353       assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
354
355       V->replaceAllUsesWith(TheRealValue);
356       delete V;
357     }
358   }
359
360   LateResolvers.clear();
361 }
362
363 // ResolveType - Take a specified unresolved type and resolve it.  If there is
364 // nothing to resolve it to yet, return true.  Otherwise resolve it and return
365 // false.
366 //
367 static bool ResolveType(PATypeHolder<Type> &T) {
368   const Type *Ty = T;
369   ValID &DID = getValIDFromPlaceHolder(Ty);
370
371   const Type *TheRealType = getTypeVal(DID, true);
372   if (TheRealType == 0) return true;
373
374   // Refine the opaque type we had to the new type we are getting.
375   cast<DerivedType>(Ty)->refineAbstractTypeTo(TheRealType);
376   return false;
377 }
378
379
380 // ResolveTypes - This goes through the forward referenced type table and makes
381 // sure that all type references are complete.  This code is executed after the
382 // constant pool of a method or module is completely parsed.
383 //
384 static void ResolveTypes(vector<PATypeHolder<Type> > &LateResolveTypes) {
385   while (!LateResolveTypes.empty()) {
386     if (ResolveType(LateResolveTypes.back())) {
387       const Type *Ty = LateResolveTypes.back();
388       ValID &DID = getValIDFromPlaceHolder(Ty);
389
390       if (DID.Type == ValID::NameVal)
391         ThrowException("Reference to an invalid type: '" +DID.getName(),
392                        getLineNumFromPlaceHolder(Ty));
393       else
394         ThrowException("Reference to an invalid type: #" + itostr(DID.Num),
395                        getLineNumFromPlaceHolder(Ty));
396     }
397
398     // No need to delete type, refine does that for us.
399     LateResolveTypes.pop_back();
400   }
401 }
402
403
404 // ResolveSomeTypes - This goes through the forward referenced type table and
405 // completes references that are now done.  This is so that types are
406 // immediately resolved to be as concrete as possible.  This does not cause
407 // thrown exceptions if not everything is resolved.
408 //
409 static void ResolveSomeTypes(vector<PATypeHolder<Type> > &LateResolveTypes) {
410   for (unsigned i = 0; i < LateResolveTypes.size(); ) {
411     if (ResolveType(LateResolveTypes[i]))
412       ++i;                                                // Type didn't resolve
413     else
414       LateResolveTypes.erase(LateResolveTypes.begin()+i); // Type resolved!
415   }
416 }
417
418
419 // setValueName - Set the specified value to the name given.  The name may be
420 // null potentially, in which case this is a noop.  The string passed in is
421 // assumed to be a malloc'd string buffer, and is freed by this function.
422 //
423 static void setValueName(Value *V, char *NameStr) {
424   if (NameStr == 0) return;
425   string Name(NameStr);           // Copy string
426   free(NameStr);                  // Free old string
427
428   SymbolTable *ST = CurMeth.CurrentMethod ? 
429     CurMeth.CurrentMethod->getSymbolTableSure() : 
430     CurModule.CurrentModule->getSymbolTableSure();
431
432   Value *Existing = ST->lookup(V->getType(), Name);
433   if (Existing) {    // Inserting a name that is already defined???
434     // There is only one case where this is allowed: when we are refining an
435     // opaque type.  In this case, Existing will be an opaque type.
436     if (const Type *Ty = dyn_cast<const Type>(Existing)) {
437       if (OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
438         // We ARE replacing an opaque type!
439         OpTy->refineAbstractTypeTo(cast<Type>(V));
440         return;
441       }
442     }
443
444     // Otherwise, we are a simple redefinition of a value, check to see if it
445     // is defined the same as the old one...
446     if (const Type *Ty = dyn_cast<const Type>(Existing)) {
447       if (Ty == cast<const Type>(V)) return;  // Yes, it's equal.
448       cerr << "Type: " << Ty->getDescription() << " != "
449            << cast<const Type>(V)->getDescription() << "!\n";
450     } else {
451       
452     }
453     ThrowException("Redefinition of value name '" + Name + "' in the '" +
454                    V->getType()->getDescription() + "' type plane!");
455   }
456
457   V->setName(Name, ST);
458 }
459
460
461 //===----------------------------------------------------------------------===//
462 // Code for handling upreferences in type names...
463 //
464
465 // TypeContains - Returns true if Ty contains E in it.
466 //
467 static bool TypeContains(const Type *Ty, const Type *E) {
468   return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
469 }
470
471
472 static vector<pair<unsigned, OpaqueType *> > UpRefs;
473
474 static PATypeHolder<Type> HandleUpRefs(const Type *ty) {
475   PATypeHolder<Type> Ty(ty);
476   UR_OUT(UpRefs.size() << " upreferences active!\n");
477   for (unsigned i = 0; i < UpRefs.size(); ) {
478     UR_OUT("TypeContains(" << Ty->getDescription() << ", " 
479            << UpRefs[i].second->getDescription() << ") = " 
480            << TypeContains(Ty, UpRefs[i].second) << endl);
481     if (TypeContains(Ty, UpRefs[i].second)) {
482       unsigned Level = --UpRefs[i].first;   // Decrement level of upreference
483       UR_OUT("Uplevel Ref Level = " << Level << endl);
484       if (Level == 0) {                     // Upreference should be resolved! 
485         UR_OUT("About to resolve upreference!\n";
486                string OldName = UpRefs[i].second->getDescription());
487         UpRefs[i].second->refineAbstractTypeTo(Ty);
488         UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list...
489         UR_OUT("Type '" << OldName << "' refined upreference to: "
490                << (const void*)Ty << ", " << Ty->getDescription() << endl);
491         continue;
492       }
493     }
494
495     ++i;                                  // Otherwise, no resolve, move on...
496   }
497   // FIXME: TODO: this should return the updated type
498   return Ty;
499 }
500
501 template <class TypeTy>
502 inline static void TypeDone(PATypeHolder<TypeTy> *Ty) {
503   if (UpRefs.size())
504     ThrowException("Invalid upreference in type: " + (*Ty)->getDescription());
505 }
506
507 // newTH - Allocate a new type holder for the specified type
508 template <class TypeTy>
509 inline static PATypeHolder<TypeTy> *newTH(const TypeTy *Ty) {
510   return new PATypeHolder<TypeTy>(Ty);
511 }
512 template <class TypeTy>
513 inline static PATypeHolder<TypeTy> *newTH(const PATypeHolder<TypeTy> &TH) {
514   return new PATypeHolder<TypeTy>(TH);
515 }
516
517
518 //===----------------------------------------------------------------------===//
519 //            RunVMAsmParser - Define an interface to this parser
520 //===----------------------------------------------------------------------===//
521 //
522 Module *RunVMAsmParser(const string &Filename, FILE *F) {
523   llvmAsmin = F;
524   CurFilename = Filename;
525   llvmAsmlineno = 1;      // Reset the current line number...
526
527   CurModule.CurrentModule = new Module();  // Allocate a new module to read
528   yyparse();       // Parse the file.
529   Module *Result = ParserResult;
530   llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
531   ParserResult = 0;
532
533   return Result;
534 }
535
536 %}
537
538 %union {
539   Module                           *ModuleVal;
540   Method                           *MethodVal;
541   MethodArgument                   *MethArgVal;
542   BasicBlock                       *BasicBlockVal;
543   TerminatorInst                   *TermInstVal;
544   Instruction                      *InstVal;
545   ConstPoolVal                     *ConstVal;
546
547   const Type                       *PrimType;
548   PATypeHolder<Type>               *TypeVal;
549   Value                            *ValueVal;
550
551   list<MethodArgument*>            *MethodArgList;
552   list<Value*>                     *ValueList;
553   list<PATypeHolder<Type> >        *TypeList;
554   list<pair<Value*, BasicBlock*> > *PHIList;   // Represent the RHS of PHI node
555   list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
556   vector<ConstPoolVal*>            *ConstVector;
557
558   int64_t                           SInt64Val;
559   uint64_t                          UInt64Val;
560   int                               SIntVal;
561   unsigned                          UIntVal;
562   double                            FPVal;
563   bool                              BoolVal;
564
565   char                             *StrVal;   // This memory is strdup'd!
566   ValID                             ValIDVal; // strdup'd memory maybe!
567
568   Instruction::UnaryOps             UnaryOpVal;
569   Instruction::BinaryOps            BinaryOpVal;
570   Instruction::TermOps              TermOpVal;
571   Instruction::MemoryOps            MemOpVal;
572   Instruction::OtherOps             OtherOpVal;
573 }
574
575 %type <ModuleVal>     Module MethodList
576 %type <MethodVal>     Method MethodProto MethodHeader BasicBlockList
577 %type <BasicBlockVal> BasicBlock InstructionList
578 %type <TermInstVal>   BBTerminatorInst
579 %type <InstVal>       Inst InstVal MemoryInst
580 %type <ConstVal>      ConstVal
581 %type <ConstVector>   ConstVector UByteList
582 %type <MethodArgList> ArgList ArgListH
583 %type <MethArgVal>    ArgVal
584 %type <PHIList>       PHIList
585 %type <ValueList>     ValueRefList ValueRefListE  // For call param lists
586 %type <TypeList>      TypeListI ArgTypeListI
587 %type <JumpTable>     JumpTable
588 %type <BoolVal>       GlobalType                  // GLOBAL or CONSTANT?
589
590 %type <ValIDVal>      ValueRef ConstValueRef // Reference to a definition or BB
591 %type <ValueVal>      ResolvedVal            // <type> <valref> pair
592 // Tokens and types for handling constant integer values
593 //
594 // ESINT64VAL - A negative number within long long range
595 %token <SInt64Val> ESINT64VAL
596
597 // EUINT64VAL - A positive number within uns. long long range
598 %token <UInt64Val> EUINT64VAL
599 %type  <SInt64Val> EINT64VAL
600
601 %token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
602 %token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
603 %type   <SIntVal>   INTVAL
604 %token  <FPVal>     FPVAL     // Float or Double constant
605
606 // Built in types...
607 %type  <TypeVal> Types TypesV UpRTypes UpRTypesV
608 %type  <PrimType> SIntType UIntType IntType FPType PrimType   // Classifications
609 %token <TypeVal>  OPAQUE
610 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
611 %token <PrimType> FLOAT DOUBLE TYPE LABEL
612
613 %token <StrVal>     VAR_ID LABELSTR STRINGCONSTANT
614 %type  <StrVal>  OptVAR_ID OptAssign
615
616
617 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
618 %token TO DOTDOTDOT STRING NULL_TOK CONST
619
620 // Basic Block Terminating Operators 
621 %token <TermOpVal> RET BR SWITCH
622
623 // Unary Operators 
624 %type  <UnaryOpVal> UnaryOps  // all the unary operators
625 %token <UnaryOpVal> NOT
626
627 // Binary Operators 
628 %type  <BinaryOpVal> BinaryOps  // all the binary operators
629 %token <BinaryOpVal> ADD SUB MUL DIV REM
630 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE  // Binary Comarators
631
632 // Memory Instructions
633 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
634
635 // Other Operators
636 %type  <OtherOpVal> ShiftOps
637 %token <OtherOpVal> PHI CALL CAST SHL SHR
638
639 %start Module
640 %%
641
642 // Handle constant integer size restriction and conversion...
643 //
644
645 INTVAL : SINTVAL
646 INTVAL : UINTVAL {
647   if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
648     ThrowException("Value too large for type!");
649   $$ = (int32_t)$1;
650 }
651
652
653 EINT64VAL : ESINT64VAL       // These have same type and can't cause problems...
654 EINT64VAL : EUINT64VAL {
655   if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
656     ThrowException("Value too large for type!");
657   $$ = (int64_t)$1;
658 }
659
660 // Operations that are notably excluded from this list include: 
661 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
662 //
663 UnaryOps  : NOT
664 BinaryOps : ADD | SUB | MUL | DIV | REM
665 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
666 ShiftOps  : SHL | SHR
667
668 // These are some types that allow classification if we only want a particular 
669 // thing... for example, only a signed, unsigned, or integral type.
670 SIntType :  LONG |  INT |  SHORT | SBYTE
671 UIntType : ULONG | UINT | USHORT | UBYTE
672 IntType  : SIntType | UIntType
673 FPType   : FLOAT | DOUBLE
674
675 // OptAssign - Value producing statements have an optional assignment component
676 OptAssign : VAR_ID '=' {
677     $$ = $1;
678   }
679   | /*empty*/ { 
680     $$ = 0; 
681   }
682
683
684 //===----------------------------------------------------------------------===//
685 // Types includes all predefined types... except void, because it can only be
686 // used in specific contexts (method returning void for example).  To have
687 // access to it, a user must explicitly use TypesV.
688 //
689
690 // TypesV includes all of 'Types', but it also includes the void type.
691 TypesV    : Types    | VOID { $$ = newTH($1); }
692 UpRTypesV : UpRTypes | VOID { $$ = newTH($1); }
693
694 Types     : UpRTypes {
695     TypeDone($$ = $1);
696   }
697
698
699 // Derived types are added later...
700 //
701 PrimType : BOOL | SBYTE | UBYTE | SHORT  | USHORT | INT   | UINT 
702 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE   | LABEL
703 UpRTypes : OPAQUE | PrimType { $$ = newTH($1); }
704 UpRTypes : ValueRef {                    // Named types are also simple types...
705   $$ = newTH(getTypeVal($1));
706 }
707
708 // Include derived types in the Types production.
709 //
710 UpRTypes : '\\' EUINT64VAL {                   // Type UpReference
711     if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
712     OpaqueType *OT = OpaqueType::get();        // Use temporary placeholder
713     UpRefs.push_back(make_pair((unsigned)$2, OT));  // Add to vector...
714     $$ = newTH<Type>(OT);
715     UR_OUT("New Upreference!\n");
716   }
717   | UpRTypesV '(' ArgTypeListI ')' {           // Method derived type?
718     vector<const Type*> Params;
719     mapto($3->begin(), $3->end(), back_inserter(Params), 
720           mem_fun_ref(&PATypeHandle<Type>::get));
721     $$ = newTH(HandleUpRefs(MethodType::get(*$1, Params)));
722     delete $3;      // Delete the argument list
723     delete $1;      // Delete the old type handle
724   }
725   | '[' UpRTypesV ']' {                        // Unsized array type?
726     $$ = newTH<Type>(HandleUpRefs(ArrayType::get(*$2)));
727     delete $2;
728   }
729   | '[' EUINT64VAL 'x' UpRTypes ']' {          // Sized array type?
730     $$ = newTH<Type>(HandleUpRefs(ArrayType::get(*$4, (int)$2)));
731     delete $4;
732   }
733   | '{' TypeListI '}' {                        // Structure type?
734     vector<const Type*> Elements;
735     mapto($2->begin(), $2->end(), back_inserter(Elements), 
736         mem_fun_ref(&PATypeHandle<Type>::get));
737
738     $$ = newTH<Type>(HandleUpRefs(StructType::get(Elements)));
739     delete $2;
740   }
741   | '{' '}' {                                  // Empty structure type?
742     $$ = newTH<Type>(StructType::get(vector<const Type*>()));
743   }
744   | UpRTypes '*' {                             // Pointer type?
745     $$ = newTH<Type>(HandleUpRefs(PointerType::get(*$1)));
746     delete $1;
747   }
748
749 // TypeList - Used for struct declarations and as a basis for method type 
750 // declaration type lists
751 //
752 TypeListI : UpRTypes {
753     $$ = new list<PATypeHolder<Type> >();
754     $$->push_back(*$1); delete $1;
755   }
756   | TypeListI ',' UpRTypes {
757     ($$=$1)->push_back(*$3); delete $3;
758   }
759
760 // ArgTypeList - List of types for a method type declaration...
761 ArgTypeListI : TypeListI
762   | TypeListI ',' DOTDOTDOT {
763     ($$=$1)->push_back(Type::VoidTy);
764   }
765   | DOTDOTDOT {
766     ($$ = new list<PATypeHolder<Type> >())->push_back(Type::VoidTy);
767   }
768   | /*empty*/ {
769     $$ = new list<PATypeHolder<Type> >();
770   }
771
772
773 // ConstVal - The various declarations that go into the constant pool.  This
774 // includes all forward declarations of types, constants, and functions.
775 //
776 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
777     const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
778     if (ATy == 0)
779       ThrowException("Cannot make array constant with type: '" + 
780                      (*$1)->getDescription() + "'!");
781     const Type *ETy = ATy->getElementType();
782     int NumElements = ATy->getNumElements();
783
784     // Verify that we have the correct size...
785     if (NumElements != -1 && NumElements != (int)$3->size())
786       ThrowException("Type mismatch: constant sized array initialized with " +
787                      utostr($3->size()) +  " arguments, but has size of " + 
788                      itostr(NumElements) + "!");
789
790     // Verify all elements are correct type!
791     for (unsigned i = 0; i < $3->size(); i++) {
792       if (ETy != (*$3)[i]->getType())
793         ThrowException("Element #" + utostr(i) + " is not of type '" + 
794                        ETy->getName() + "' as required!\nIt is of type '" +
795                        (*$3)[i]->getType()->getName() + "'.");
796     }
797
798     $$ = ConstPoolArray::get(ATy, *$3);
799     delete $1; delete $3;
800   }
801   | Types '[' ']' {
802     const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
803     if (ATy == 0)
804       ThrowException("Cannot make array constant with type: '" + 
805                      (*$1)->getDescription() + "'!");
806
807     int NumElements = ATy->getNumElements();
808     if (NumElements != -1 && NumElements != 0) 
809       ThrowException("Type mismatch: constant sized array initialized with 0"
810                      " arguments, but has size of " + itostr(NumElements) +"!");
811     $$ = ConstPoolArray::get(ATy, vector<ConstPoolVal*>());
812     delete $1;
813   }
814   | Types 'c' STRINGCONSTANT {
815     const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
816     if (ATy == 0)
817       ThrowException("Cannot make array constant with type: '" + 
818                      (*$1)->getDescription() + "'!");
819
820     int NumElements = ATy->getNumElements();
821     const Type *ETy = ATy->getElementType();
822     char *EndStr = UnEscapeLexed($3, true);
823     if (NumElements != -1 && NumElements != (EndStr-$3))
824       ThrowException("Can't build string constant of size " + 
825                      itostr((int)(EndStr-$3)) +
826                      " when array has size " + itostr(NumElements) + "!");
827     vector<ConstPoolVal*> Vals;
828     if (ETy == Type::SByteTy) {
829       for (char *C = $3; C != EndStr; ++C)
830         Vals.push_back(ConstPoolSInt::get(ETy, *C));
831     } else if (ETy == Type::UByteTy) {
832       for (char *C = $3; C != EndStr; ++C)
833         Vals.push_back(ConstPoolUInt::get(ETy, *C));
834     } else {
835       free($3);
836       ThrowException("Cannot build string arrays of non byte sized elements!");
837     }
838     free($3);
839     $$ = ConstPoolArray::get(ATy, Vals);
840     delete $1;
841   }
842   | Types '{' ConstVector '}' {
843     const StructType *STy = dyn_cast<const StructType>($1->get());
844     if (STy == 0)
845       ThrowException("Cannot make struct constant with type: '" + 
846                      (*$1)->getDescription() + "'!");
847     // FIXME: TODO: Check to see that the constants are compatible with the type
848     // initializer!
849     $$ = ConstPoolStruct::get(STy, *$3);
850     delete $1; delete $3;
851   }
852   | Types NULL_TOK {
853     const PointerType *PTy = dyn_cast<const PointerType>($1->get());
854     if (PTy == 0)
855       ThrowException("Cannot make null pointer constant with type: '" + 
856                      (*$1)->getDescription() + "'!");
857
858     $$ = ConstPoolPointer::getNullPointer(PTy);
859     delete $1;
860   }
861   | Types VAR_ID {
862     string Name($2); free($2);  // Change to a responsible mem manager
863     const PointerType *Ty = dyn_cast<const PointerType>($1->get());
864     if (Ty == 0)
865       ThrowException("Global const reference must be a pointer type!");
866
867     Value *N = lookupInSymbolTable(Ty, Name);
868     if (N == 0)
869       ThrowException("Global pointer reference '%" + Name +
870                      "' must be defined before use!");    
871
872     // TODO FIXME: This should also allow methods... when common baseclass
873     // exists
874     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(N)) {
875       $$ = ConstPoolPointerReference::get(GV);
876     } else {
877       ThrowException("'%" + Name + "' is not a global value reference!");
878     }
879
880     delete $1;
881   }
882
883
884 ConstVal : SIntType EINT64VAL {     // integral constants
885     if (!ConstPoolSInt::isValueValidForType($1, $2))
886       ThrowException("Constant value doesn't fit in type!");
887     $$ = ConstPoolSInt::get($1, $2);
888   } 
889   | UIntType EUINT64VAL {           // integral constants
890     if (!ConstPoolUInt::isValueValidForType($1, $2))
891       ThrowException("Constant value doesn't fit in type!");
892     $$ = ConstPoolUInt::get($1, $2);
893   } 
894   | BOOL TRUE {                     // Boolean constants
895     $$ = ConstPoolBool::True;
896   }
897   | BOOL FALSE {                    // Boolean constants
898     $$ = ConstPoolBool::False;
899   }
900   | FPType FPVAL {                   // Float & Double constants
901     $$ = ConstPoolFP::get($1, $2);
902   }
903
904 // ConstVector - A list of comma seperated constants.
905 ConstVector : ConstVector ',' ConstVal {
906     ($$ = $1)->push_back($3);
907   }
908   | ConstVal {
909     $$ = new vector<ConstPoolVal*>();
910     $$->push_back($1);
911   }
912
913
914 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
915 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
916
917
918 // ConstPool - Constants with optional names assigned to them.
919 ConstPool : ConstPool OptAssign CONST ConstVal { 
920     setValueName($4, $2);
921     InsertValue($4);
922   }
923   | ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
924     // TODO: FIXME when Type are not const
925     setValueName(const_cast<Type*>($4->get()), $2);
926
927     if (!$2) {
928       InsertType($4->get(),
929                  CurMeth.CurrentMethod ? CurMeth.Types : CurModule.Types);
930     }
931     delete $4;
932
933     ResolveSomeTypes(CurMeth.CurrentMethod ? CurMeth.LateResolveTypes :
934                      CurModule.LateResolveTypes);
935   }
936   | ConstPool MethodProto {            // Method prototypes can be in const pool
937   }
938   | ConstPool OptAssign GlobalType ConstVal {
939     const Type *Ty = $4->getType();
940     // Global declarations appear in Constant Pool
941     ConstPoolVal *Initializer = $4;
942     if (Initializer == 0)
943       ThrowException("Global value initializer is not a constant!");
944          
945     GlobalVariable *GV = new GlobalVariable(Ty, $3, Initializer);
946     setValueName(GV, $2);
947
948     CurModule.CurrentModule->getGlobalList().push_back(GV);
949     InsertValue(GV, CurModule.Values);
950   }
951   | ConstPool OptAssign UNINIT GlobalType Types {
952     const Type *Ty = *$5;
953     // Global declarations appear in Constant Pool
954     if (isa<ArrayType>(Ty) && cast<ArrayType>(Ty)->isUnsized()) {
955       ThrowException("Type '" + Ty->getDescription() +
956                      "' is not a sized type!");
957     }
958
959     GlobalVariable *GV = new GlobalVariable(Ty, $4);
960     setValueName(GV, $2);
961
962     CurModule.CurrentModule->getGlobalList().push_back(GV);
963     InsertValue(GV, CurModule.Values);
964   }
965   | /* empty: end of list */ { 
966   }
967
968
969 //===----------------------------------------------------------------------===//
970 //                             Rules to match Modules
971 //===----------------------------------------------------------------------===//
972
973 // Module rule: Capture the result of parsing the whole file into a result
974 // variable...
975 //
976 Module : MethodList {
977   $$ = ParserResult = $1;
978   CurModule.ModuleDone();
979 }
980
981 // MethodList - A list of methods, preceeded by a constant pool.
982 //
983 MethodList : MethodList Method {
984     $$ = $1;
985     if (!$2->getParent())
986       $1->getMethodList().push_back($2);
987     CurMeth.MethodDone();
988   } 
989   | MethodList MethodProto {
990     $$ = $1;
991   }
992   | ConstPool IMPLEMENTATION {
993     $$ = CurModule.CurrentModule;
994     // Resolve circular types before we parse the body of the module
995     ResolveTypes(CurModule.LateResolveTypes);
996   }
997
998
999 //===----------------------------------------------------------------------===//
1000 //                       Rules to match Method Headers
1001 //===----------------------------------------------------------------------===//
1002
1003 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
1004
1005 ArgVal : Types OptVAR_ID {
1006   $$ = new MethodArgument(*$1); delete $1;
1007   setValueName($$, $2);
1008 }
1009
1010 ArgListH : ArgVal ',' ArgListH {
1011     $$ = $3;
1012     $3->push_front($1);
1013   }
1014   | ArgVal {
1015     $$ = new list<MethodArgument*>();
1016     $$->push_front($1);
1017   }
1018   | DOTDOTDOT {
1019     $$ = new list<MethodArgument*>();
1020     $$->push_back(new MethodArgument(Type::VoidTy));
1021   }
1022
1023 ArgList : ArgListH {
1024     $$ = $1;
1025   }
1026   | /* empty */ {
1027     $$ = 0;
1028   }
1029
1030 MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
1031   UnEscapeLexed($2);
1032   vector<const Type*> ParamTypeList;
1033   if ($4)
1034     for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
1035       ParamTypeList.push_back((*I)->getType());
1036
1037   const MethodType  *MT  = MethodType::get(*$1, ParamTypeList);
1038   const PointerType *PMT = PointerType::get(MT);
1039   delete $1;
1040
1041   Method *M = 0;
1042   if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1043     if (Value *V = ST->lookup(PMT, $2)) {  // Method already in symtab?
1044       M = cast<Method>(V);
1045
1046       // Yes it is.  If this is the case, either we need to be a forward decl,
1047       // or it needs to be.
1048       if (!CurMeth.isDeclare && !M->isExternal())
1049         ThrowException("Redefinition of method '" + string($2) + "'!");      
1050     }
1051   }
1052
1053   if (M == 0) {  // Not already defined?
1054     M = new Method(MT, $2);
1055     InsertValue(M, CurModule.Values);
1056   }
1057
1058   free($2);  // Free strdup'd memory!
1059
1060   CurMeth.MethodStart(M);
1061
1062   // Add all of the arguments we parsed to the method...
1063   if ($4 && !CurMeth.isDeclare) {        // Is null if empty...
1064     Method::ArgumentListType &ArgList = M->getArgumentList();
1065
1066     for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
1067       InsertValue(*I);
1068       ArgList.push_back(*I);
1069     }
1070     delete $4;                     // We're now done with the argument list
1071   }
1072 }
1073
1074 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
1075   $$ = CurMeth.CurrentMethod;
1076
1077   // Resolve circular types before we parse the body of the method.
1078   ResolveTypes(CurMeth.LateResolveTypes);
1079 }
1080
1081 Method : BasicBlockList END {
1082   $$ = $1;
1083 }
1084
1085 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
1086   $$ = CurMeth.CurrentMethod;
1087   if (!$$->getParent())
1088     CurModule.CurrentModule->getMethodList().push_back($$);
1089   CurMeth.MethodDone();
1090 }
1091
1092 //===----------------------------------------------------------------------===//
1093 //                        Rules to match Basic Blocks
1094 //===----------------------------------------------------------------------===//
1095
1096 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1097     $$ = ValID::create($1);
1098   }
1099   | EUINT64VAL {
1100     $$ = ValID::create($1);
1101   }
1102   | FPVAL {                     // Perhaps it's an FP constant?
1103     $$ = ValID::create($1);
1104   }
1105   | TRUE {
1106     $$ = ValID::create((int64_t)1);
1107   } 
1108   | FALSE {
1109     $$ = ValID::create((int64_t)0);
1110   }
1111   | NULL_TOK {
1112     $$ = ValID::createNull();
1113   }
1114
1115 /*
1116   | STRINGCONSTANT {        // Quoted strings work too... especially for methods
1117     $$ = ValID::create_conststr($1);
1118   }
1119 */
1120
1121 // ValueRef - A reference to a definition... 
1122 ValueRef : INTVAL {           // Is it an integer reference...?
1123     $$ = ValID::create($1);
1124   }
1125   | VAR_ID {                 // Is it a named reference...?
1126     $$ = ValID::create($1);
1127   }
1128   | ConstValueRef {
1129     $$ = $1;
1130   }
1131
1132 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1133 // type immediately preceeds the value reference, and allows complex constant
1134 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1135 ResolvedVal : Types ValueRef {
1136     $$ = getVal(*$1, $2); delete $1;
1137   }
1138
1139
1140 BasicBlockList : BasicBlockList BasicBlock {
1141     $1->getBasicBlocks().push_back($2);
1142     $$ = $1;
1143   }
1144   | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks   
1145     $$ = $1;                  // in them...
1146     $1->getBasicBlocks().push_back($2);
1147   }
1148
1149
1150 // Basic blocks are terminated by branching instructions: 
1151 // br, br/cc, switch, ret
1152 //
1153 BasicBlock : InstructionList BBTerminatorInst  {
1154     $1->getInstList().push_back($2);
1155     InsertValue($1);
1156     $$ = $1;
1157   }
1158   | LABELSTR InstructionList BBTerminatorInst  {
1159     $2->getInstList().push_back($3);
1160     setValueName($2, $1);
1161
1162     InsertValue($2);
1163     $$ = $2;
1164   }
1165
1166 InstructionList : InstructionList Inst {
1167     $1->getInstList().push_back($2);
1168     $$ = $1;
1169   }
1170   | /* empty */ {
1171     $$ = new BasicBlock();
1172   }
1173
1174 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1175     $$ = new ReturnInst($2);
1176   }
1177   | RET VOID {                                       // Return with no result...
1178     $$ = new ReturnInst();
1179   }
1180   | BR LABEL ValueRef {                         // Unconditional Branch...
1181     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1182   }                                                  // Conditional Branch...
1183   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1184     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)), 
1185                         cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1186                         getVal(Type::BoolTy, $3));
1187   }
1188   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1189     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1190                                    cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1191     $$ = S;
1192
1193     list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(), 
1194                                                       end = $8->end();
1195     for (; I != end; ++I)
1196       S->dest_push_back(I->first, I->second);
1197   }
1198
1199 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1200     $$ = $1;
1201     ConstPoolVal *V = cast<ConstPoolVal>(getVal($2, $3, true));
1202     if (V == 0)
1203       ThrowException("May only switch on a constant pool value!");
1204
1205     $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1206   }
1207   | IntType ConstValueRef ',' LABEL ValueRef {
1208     $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
1209     ConstPoolVal *V = cast<ConstPoolVal>(getVal($1, $2, true));
1210
1211     if (V == 0)
1212       ThrowException("May only switch on a constant pool value!");
1213
1214     $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1215   }
1216
1217 Inst : OptAssign InstVal {
1218   setValueName($2, $1);  // Is this definition named?? if so, assign the name...
1219
1220   InsertValue($2);
1221   $$ = $2;
1222 }
1223
1224 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1225     $$ = new list<pair<Value*, BasicBlock*> >();
1226     $$->push_back(make_pair(getVal(*$1, $3), 
1227                             cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1228     delete $1;
1229   }
1230   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1231     $$ = $1;
1232     $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1233                             cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1234   }
1235
1236
1237 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1238     $$ = new list<Value*>();
1239     $$->push_back($1);
1240   }
1241   | ValueRefList ',' ResolvedVal {
1242     $$ = $1;
1243     $1->push_back($3);
1244   }
1245
1246 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1247 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1248
1249 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1250     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1251     if ($$ == 0)
1252       ThrowException("binary operator returned null!");
1253     delete $2;
1254   }
1255   | UnaryOps ResolvedVal {
1256     $$ = UnaryOperator::create($1, $2);
1257     if ($$ == 0)
1258       ThrowException("unary operator returned null!");
1259   }
1260   | ShiftOps ResolvedVal ',' ResolvedVal {
1261     if ($4->getType() != Type::UByteTy)
1262       ThrowException("Shift amount must be ubyte!");
1263     $$ = new ShiftInst($1, $2, $4);
1264   }
1265   | CAST ResolvedVal TO Types {
1266     $$ = new CastInst($2, *$4);
1267     delete $4;
1268   }
1269   | PHI PHIList {
1270     const Type *Ty = $2->front().first->getType();
1271     $$ = new PHINode(Ty);
1272     while ($2->begin() != $2->end()) {
1273       if ($2->front().first->getType() != Ty) 
1274         ThrowException("All elements of a PHI node must be of the same type!");
1275       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1276       $2->pop_front();
1277     }
1278     delete $2;  // Free the list...
1279   } 
1280   | CALL TypesV ValueRef '(' ValueRefListE ')' {
1281     const PointerType *PMTy;
1282     const MethodType *Ty;
1283
1284     if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1285         !(Ty = dyn_cast<MethodType>(PMTy->getValueType()))) {
1286       // Pull out the types of all of the arguments...
1287       vector<const Type*> ParamTypes;
1288       if ($5) {
1289         for (list<Value*>::iterator I = $5->begin(), E = $5->end(); I != E; ++I)
1290           ParamTypes.push_back((*I)->getType());
1291       }
1292       Ty = MethodType::get($2->get(), ParamTypes);
1293       PMTy = PointerType::get(Ty);
1294     }
1295     delete $2;
1296
1297     Value *V = getVal(PMTy, $3);   // Get the method we're calling...
1298
1299     // Create the call node...
1300     if (!$5) {                                   // Has no arguments?
1301       $$ = new CallInst(cast<Method>(V), vector<Value*>());
1302     } else {                                     // Has arguments?
1303       // Loop through MethodType's arguments and ensure they are specified
1304       // correctly!
1305       //
1306       MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1307       MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1308       list<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1309
1310       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1311         if ((*ArgI)->getType() != *I)
1312           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1313                          (*I)->getName() + "'!");
1314
1315       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1316         ThrowException("Invalid number of parameters detected!");
1317
1318       $$ = new CallInst(cast<Method>(V),
1319                         vector<Value*>($5->begin(), $5->end()));
1320     }
1321     delete $5;
1322   }
1323   | MemoryInst {
1324     $$ = $1;
1325   }
1326
1327 // UByteList - List of ubyte values for load and store instructions
1328 UByteList : ',' ConstVector { 
1329   $$ = $2; 
1330 } | /* empty */ { 
1331   $$ = new vector<ConstPoolVal*>(); 
1332 }
1333
1334 MemoryInst : MALLOC Types {
1335     $$ = new MallocInst(PointerType::get(*$2));
1336     delete $2;
1337   }
1338   | MALLOC Types ',' UINT ValueRef {
1339     if (!(*$2)->isArrayType() || cast<const ArrayType>($2->get())->isSized())
1340       ThrowException("Trying to allocate " + (*$2)->getName() + 
1341                      " as unsized array!");
1342     const Type *Ty = PointerType::get(*$2);
1343     $$ = new MallocInst(Ty, getVal($4, $5));
1344     delete $2;
1345   }
1346   | ALLOCA Types {
1347     $$ = new AllocaInst(PointerType::get(*$2));
1348     delete $2;
1349   }
1350   | ALLOCA Types ',' UINT ValueRef {
1351     if (!(*$2)->isArrayType() || cast<const ArrayType>($2->get())->isSized())
1352       ThrowException("Trying to allocate " + (*$2)->getName() + 
1353                      " as unsized array!");
1354     const Type *Ty = PointerType::get(*$2);
1355     Value *ArrSize = getVal($4, $5);
1356     $$ = new AllocaInst(Ty, ArrSize);
1357     delete $2;
1358   }
1359   | FREE ResolvedVal {
1360     if (!$2->getType()->isPointerType())
1361       ThrowException("Trying to free nonpointer type " + 
1362                      $2->getType()->getName() + "!");
1363     $$ = new FreeInst($2);
1364   }
1365
1366   | LOAD Types ValueRef UByteList {
1367     if (!(*$2)->isPointerType())
1368       ThrowException("Can't load from nonpointer type: " + (*$2)->getName());
1369     if (LoadInst::getIndexedType(*$2, *$4) == 0)
1370       ThrowException("Invalid indices for load instruction!");
1371
1372     $$ = new LoadInst(getVal(*$2, $3), *$4);
1373     delete $4;   // Free the vector...
1374     delete $2;
1375   }
1376   | STORE ResolvedVal ',' Types ValueRef UByteList {
1377     if (!(*$4)->isPointerType())
1378       ThrowException("Can't store to a nonpointer type: " + (*$4)->getName());
1379     const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1380     if (ElTy == 0)
1381       ThrowException("Can't store into that field list!");
1382     if (ElTy != $2->getType())
1383       ThrowException("Can't store '" + $2->getType()->getName() +
1384                      "' into space of type '" + ElTy->getName() + "'!");
1385     $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1386     delete $4; delete $6;
1387   }
1388   | GETELEMENTPTR Types ValueRef UByteList {
1389     if (!(*$2)->isPointerType())
1390       ThrowException("getelementptr insn requires pointer operand!");
1391     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1392       ThrowException("Can't get element ptr '" + (*$2)->getName() + "'!");
1393     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1394     delete $2; delete $4;
1395   }
1396
1397 %%
1398 int yyerror(const char *ErrorMsg) {
1399   ThrowException(string("Parse error: ") + ErrorMsg);
1400   return 0;
1401 }