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