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