ConstExpr::getelementptr now takes a vector of Constants not Values
[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 // FIXME: ConstExpr::get never return null!
973 ConstExpr: Types CAST ConstVal {
974     ConstantExpr* CPE = ConstantExpr::get($2, $3, $1->get());
975     if (CPE == 0) ThrowException("constant expression builder returned null!");
976     $$ = CPE;
977   }
978   | Types GETELEMENTPTR '(' ConstVal IndexList ')' {
979     vector<Constant*> IdxVec;
980     for (unsigned i = 0, e = $5->size(); i != e; ++i)
981       if (Constant *C = dyn_cast<Constant>((*$5)[i]))
982         IdxVec.push_back(C);
983       else
984         ThrowException("Arguments to getelementptr must be constants!");
985
986     delete $5;
987
988     ConstantExpr* CPE = ConstantExpr::get($2, $4, IdxVec, $1->get());
989     if (CPE == 0) ThrowException("constant expression builder returned null!");
990     $$ = CPE;
991   }
992   | Types UnaryOps ConstVal {
993     ConstantExpr* CPE = ConstantExpr::get($2, $3, $1->get());
994     if (CPE == 0) ThrowException("constant expression builder returned null!");
995     $$ = CPE;
996   }
997   | Types BinaryOps ConstVal ',' ConstVal {
998     ConstantExpr* CPE = ConstantExpr::get($2, $3, $5, $1->get());
999     if (CPE == 0) ThrowException("constant expression builder returned null!");
1000     $$ = CPE;
1001   }
1002   | Types ShiftOps ConstVal ',' ConstVal {
1003     ConstantExpr* CPE = ConstantExpr::get($2, $3, $5, $1->get());
1004     if (CPE == 0) ThrowException("constant expression builder returned null!");
1005     $$ = CPE;
1006   }
1007   ;
1008
1009
1010 ConstVal : SIntType EINT64VAL {     // integral constants
1011     if (!ConstantSInt::isValueValidForType($1, $2))
1012       ThrowException("Constant value doesn't fit in type!");
1013     $$ = ConstantSInt::get($1, $2);
1014   } 
1015   | UIntType EUINT64VAL {           // integral constants
1016     if (!ConstantUInt::isValueValidForType($1, $2))
1017       ThrowException("Constant value doesn't fit in type!");
1018     $$ = ConstantUInt::get($1, $2);
1019   } 
1020   | BOOL TRUE {                     // Boolean constants
1021     $$ = ConstantBool::True;
1022   }
1023   | BOOL FALSE {                    // Boolean constants
1024     $$ = ConstantBool::False;
1025   }
1026   | FPType FPVAL {                   // Float & Double constants
1027     $$ = ConstantFP::get($1, $2);
1028   };
1029
1030 // ConstVector - A list of comma seperated constants.
1031 ConstVector : ConstVector ',' ConstVal {
1032     ($$ = $1)->push_back($3);
1033   }
1034   | ConstVal {
1035     $$ = new vector<Constant*>();
1036     $$->push_back($1);
1037   };
1038
1039
1040 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1041 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1042
1043
1044 //===----------------------------------------------------------------------===//
1045 //                             Rules to match Modules
1046 //===----------------------------------------------------------------------===//
1047
1048 // Module rule: Capture the result of parsing the whole file into a result
1049 // variable...
1050 //
1051 Module : FunctionList {
1052   $$ = ParserResult = $1;
1053   CurModule.ModuleDone();
1054 };
1055
1056 // FunctionList - A list of functions, preceeded by a constant pool.
1057 //
1058 FunctionList : FunctionList Function {
1059     $$ = $1;
1060     assert($2->getParent() == 0 && "Function already in module!");
1061     $1->getFunctionList().push_back($2);
1062     CurMeth.FunctionDone();
1063   } 
1064   | FunctionList FunctionProto {
1065     $$ = $1;
1066   }
1067   | FunctionList IMPLEMENTATION {
1068     $$ = $1;
1069   }
1070   | ConstPool {
1071     $$ = CurModule.CurrentModule;
1072     // Resolve circular types before we parse the body of the module
1073     ResolveTypes(CurModule.LateResolveTypes);
1074   };
1075
1076 // ConstPool - Constants with optional names assigned to them.
1077 ConstPool : ConstPool OptAssign CONST ConstVal { 
1078     if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1079     InsertValue($4);
1080   }
1081   | ConstPool OptAssign TYPE TypesV {  // Types can be defined in the const pool
1082     // Eagerly resolve types.  This is not an optimization, this is a
1083     // requirement that is due to the fact that we could have this:
1084     //
1085     // %list = type { %list * }
1086     // %list = type { %list * }    ; repeated type decl
1087     //
1088     // If types are not resolved eagerly, then the two types will not be
1089     // determined to be the same type!
1090     //
1091     ResolveTypeTo($2, $4->get());
1092
1093     // TODO: FIXME when Type are not const
1094     if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1095       // If this is not a redefinition of a type...
1096       if (!$2) {
1097         InsertType($4->get(),
1098                    inFunctionScope() ? CurMeth.Types : CurModule.Types);
1099       }
1100     }
1101
1102     delete $4;
1103   }
1104   | ConstPool FunctionProto {       // Function prototypes can be in const pool
1105   }
1106   | ConstPool OptAssign OptInternal GlobalType ConstVal {
1107     const Type *Ty = $5->getType();
1108     // Global declarations appear in Constant Pool
1109     Constant *Initializer = $5;
1110     if (Initializer == 0)
1111       ThrowException("Global value initializer is not a constant!");
1112     
1113     GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1114     if (!setValueName(GV, $2)) {   // If not redefining...
1115       CurModule.CurrentModule->getGlobalList().push_back(GV);
1116       int Slot = InsertValue(GV, CurModule.Values);
1117
1118       if (Slot != -1) {
1119         CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1120       } else {
1121         CurModule.DeclareNewGlobalValue(GV, ValID::create(
1122                                                 (char*)GV->getName().c_str()));
1123       }
1124     }
1125   }
1126   | ConstPool OptAssign OptInternal UNINIT GlobalType Types {
1127     const Type *Ty = *$6;
1128     // Global declarations appear in Constant Pool
1129     GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1130     if (!setValueName(GV, $2)) {   // If not redefining...
1131       CurModule.CurrentModule->getGlobalList().push_back(GV);
1132       int Slot = InsertValue(GV, CurModule.Values);
1133
1134       if (Slot != -1) {
1135         CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1136       } else {
1137         assert(GV->hasName() && "Not named and not numbered!?");
1138         CurModule.DeclareNewGlobalValue(GV, ValID::create(
1139                                                 (char*)GV->getName().c_str()));
1140       }
1141     }
1142     delete $6;
1143   }
1144   | /* empty: end of list */ { 
1145   };
1146
1147
1148 //===----------------------------------------------------------------------===//
1149 //                       Rules to match Function Headers
1150 //===----------------------------------------------------------------------===//
1151
1152 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; };
1153
1154 ArgVal : Types OptVAR_ID {
1155   $$ = new pair<Argument*, char*>(new Argument(*$1), $2);
1156   delete $1;  // Delete the type handle..
1157 };
1158
1159 ArgListH : ArgVal ',' ArgListH {
1160     $$ = $3;
1161     $3->push_front(*$1);
1162     delete $1;
1163   }
1164   | ArgVal {
1165     $$ = new list<pair<Argument*,char*> >();
1166     $$->push_front(*$1);
1167     delete $1;
1168   }
1169   | DOTDOTDOT {
1170     $$ = new list<pair<Argument*, char*> >();
1171     $$->push_front(pair<Argument*,char*>(new Argument(Type::VoidTy), 0));
1172   };
1173
1174 ArgList : ArgListH {
1175     $$ = $1;
1176   }
1177   | /* empty */ {
1178     $$ = 0;
1179   };
1180
1181 FuncName : VAR_ID | STRINGCONSTANT;
1182
1183 FunctionHeaderH : OptInternal TypesV FuncName '(' ArgList ')' {
1184   UnEscapeLexed($3);
1185   string FunctionName($3);
1186   
1187   vector<const Type*> ParamTypeList;
1188   if ($5)
1189     for (list<pair<Argument*,char*> >::iterator I = $5->begin();
1190          I != $5->end(); ++I)
1191       ParamTypeList.push_back(I->first->getType());
1192
1193   bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1194   if (isVarArg) ParamTypeList.pop_back();
1195
1196   const FunctionType *MT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1197   const PointerType *PMT = PointerType::get(MT);
1198   delete $2;
1199
1200   Function *M = 0;
1201   if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1202     // Is the function already in symtab?
1203     if (Value *V = ST->lookup(PMT, FunctionName)) {
1204       M = cast<Function>(V);
1205
1206       // Yes it is.  If this is the case, either we need to be a forward decl,
1207       // or it needs to be.
1208       if (!CurMeth.isDeclare && !M->isExternal())
1209         ThrowException("Redefinition of function '" + FunctionName + "'!");
1210
1211       // Make sure that we keep track of the internal marker, even if there was
1212       // a previous "declare".
1213       if ($1)
1214         M->setInternalLinkage(true);
1215
1216       // If we found a preexisting function prototype, remove it from the
1217       // module, so that we don't get spurious conflicts with global & local
1218       // variables.
1219       //
1220       CurModule.CurrentModule->getFunctionList().remove(M);
1221     }
1222   }
1223
1224   if (M == 0) {  // Not already defined?
1225     M = new Function(MT, $1, FunctionName);
1226     InsertValue(M, CurModule.Values);
1227     CurModule.DeclareNewGlobalValue(M, ValID::create($3));
1228   }
1229   free($3);  // Free strdup'd memory!
1230
1231   CurMeth.FunctionStart(M);
1232
1233   // Add all of the arguments we parsed to the function...
1234   if ($5 && !CurMeth.isDeclare) {        // Is null if empty...
1235     for (list<pair<Argument*, char*> >::iterator I = $5->begin();
1236          I != $5->end(); ++I) {
1237       if (setValueName(I->first, I->second)) {  // Insert into symtab...
1238         assert(0 && "No arg redef allowed!");
1239       }
1240       
1241       InsertValue(I->first);
1242       M->getArgumentList().push_back(I->first);
1243     }
1244     delete $5;                     // We're now done with the argument list
1245   } else if ($5) {
1246     // If we are a declaration, we should free the memory for the argument list!
1247     for (list<pair<Argument*, char*> >::iterator I = $5->begin(), E = $5->end();
1248          I != E; ++I) {
1249       if (I->second) free(I->second);   // Free the memory for the name...
1250       delete I->first;                  // Free the unused function argument
1251     }
1252     delete $5;                          // Free the memory for the list itself
1253   }
1254 };
1255
1256 BEGIN : BEGINTOK | '{';                // Allow BEGIN or '{' to start a function
1257
1258 FunctionHeader : FunctionHeaderH BEGIN {
1259   $$ = CurMeth.CurrentFunction;
1260
1261   // Resolve circular types before we parse the body of the function.
1262   ResolveTypes(CurMeth.LateResolveTypes);
1263 };
1264
1265 END : ENDTOK | '}';                    // Allow end of '}' to end a function
1266
1267 Function : BasicBlockList END {
1268   $$ = $1;
1269 };
1270
1271 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1272   $$ = CurMeth.CurrentFunction;
1273   assert($$->getParent() == 0 && "Function already in module!");
1274   CurModule.CurrentModule->getFunctionList().push_back($$);
1275   CurMeth.FunctionDone();
1276 };
1277
1278 //===----------------------------------------------------------------------===//
1279 //                        Rules to match Basic Blocks
1280 //===----------------------------------------------------------------------===//
1281
1282 ConstValueRef : ESINT64VAL {    // A reference to a direct constant
1283     $$ = ValID::create($1);
1284   }
1285   | EUINT64VAL {
1286     $$ = ValID::create($1);
1287   }
1288   | FPVAL {                     // Perhaps it's an FP constant?
1289     $$ = ValID::create($1);
1290   }
1291   | TRUE {
1292     $$ = ValID::create((int64_t)1);
1293   } 
1294   | FALSE {
1295     $$ = ValID::create((int64_t)0);
1296   }
1297   | NULL_TOK {
1298     $$ = ValID::createNull();
1299   }
1300   ;
1301
1302 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1303 // another value.
1304 //
1305 SymbolicValueRef : INTVAL {  // Is it an integer reference...?
1306     $$ = ValID::create($1);
1307   }
1308   | VAR_ID {                 // Is it a named reference...?
1309     $$ = ValID::create($1);
1310   };
1311
1312 // ValueRef - A reference to a definition... either constant or symbolic
1313 ValueRef : SymbolicValueRef | ConstValueRef;
1314
1315
1316 // ResolvedVal - a <type> <value> pair.  This is used only in cases where the
1317 // type immediately preceeds the value reference, and allows complex constant
1318 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1319 ResolvedVal : Types ValueRef {
1320     $$ = getVal(*$1, $2); delete $1;
1321   }
1322   | ConstExpr {
1323     $$ = $1;
1324   };
1325
1326 BasicBlockList : BasicBlockList BasicBlock {
1327     ($$ = $1)->getBasicBlockList().push_back($2);
1328   }
1329   | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks   
1330     ($$ = $1)->getBasicBlockList().push_back($2);
1331   };
1332
1333
1334 // Basic blocks are terminated by branching instructions: 
1335 // br, br/cc, switch, ret
1336 //
1337 BasicBlock : InstructionList OptAssign BBTerminatorInst  {
1338     if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1339     InsertValue($3);
1340
1341     $1->getInstList().push_back($3);
1342     InsertValue($1);
1343     $$ = $1;
1344   }
1345   | LABELSTR InstructionList OptAssign BBTerminatorInst  {
1346     if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1347     InsertValue($4);
1348
1349     $2->getInstList().push_back($4);
1350     if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1351
1352     InsertValue($2);
1353     $$ = $2;
1354   };
1355
1356 InstructionList : InstructionList Inst {
1357     $1->getInstList().push_back($2);
1358     $$ = $1;
1359   }
1360   | /* empty */ {
1361     $$ = new BasicBlock();
1362   };
1363
1364 BBTerminatorInst : RET ResolvedVal {              // Return with a result...
1365     $$ = new ReturnInst($2);
1366   }
1367   | RET VOID {                                       // Return with no result...
1368     $$ = new ReturnInst();
1369   }
1370   | BR LABEL ValueRef {                         // Unconditional Branch...
1371     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1372   }                                                  // Conditional Branch...
1373   | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
1374     $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)), 
1375                         cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1376                         getVal(Type::BoolTy, $3));
1377   }
1378   | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1379     SwitchInst *S = new SwitchInst(getVal($2, $3), 
1380                                    cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1381     $$ = S;
1382
1383     vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1384       E = $8->end();
1385     for (; I != E; ++I)
1386       S->dest_push_back(I->first, I->second);
1387   }
1388   | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal 
1389     EXCEPT ResolvedVal {
1390     const PointerType *PMTy;
1391     const FunctionType *Ty;
1392
1393     if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1394         !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1395       // Pull out the types of all of the arguments...
1396       vector<const Type*> ParamTypes;
1397       if ($5) {
1398         for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1399           ParamTypes.push_back((*I)->getType());
1400       }
1401
1402       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1403       if (isVarArg) ParamTypes.pop_back();
1404
1405       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1406       PMTy = PointerType::get(Ty);
1407     }
1408     delete $2;
1409
1410     Value *V = getVal(PMTy, $3);   // Get the function we're calling...
1411
1412     BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1413     BasicBlock *Except = dyn_cast<BasicBlock>($10);
1414
1415     if (Normal == 0 || Except == 0)
1416       ThrowException("Invoke instruction without label destinations!");
1417
1418     // Create the call node...
1419     if (!$5) {                                   // Has no arguments?
1420       $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1421     } else {                                     // Has arguments?
1422       // Loop through FunctionType's arguments and ensure they are specified
1423       // correctly!
1424       //
1425       FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1426       FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1427       vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1428
1429       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1430         if ((*ArgI)->getType() != *I)
1431           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1432                          (*I)->getDescription() + "'!");
1433
1434       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1435         ThrowException("Invalid number of parameters detected!");
1436
1437       $$ = new InvokeInst(V, Normal, Except, *$5);
1438     }
1439     delete $5;
1440   };
1441
1442
1443
1444 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1445     $$ = $1;
1446     Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1447     if (V == 0)
1448       ThrowException("May only switch on a constant pool value!");
1449
1450     $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1451   }
1452   | IntType ConstValueRef ',' LABEL ValueRef {
1453     $$ = new vector<pair<Constant*, BasicBlock*> >();
1454     Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1455
1456     if (V == 0)
1457       ThrowException("May only switch on a constant pool value!");
1458
1459     $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1460   };
1461
1462 Inst : OptAssign InstVal {
1463   // Is this definition named?? if so, assign the name...
1464   if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1465   InsertValue($2);
1466   $$ = $2;
1467 };
1468
1469 PHIList : Types '[' ValueRef ',' ValueRef ']' {    // Used for PHI nodes
1470     $$ = new list<pair<Value*, BasicBlock*> >();
1471     $$->push_back(make_pair(getVal(*$1, $3), 
1472                             cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1473     delete $1;
1474   }
1475   | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1476     $$ = $1;
1477     $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1478                             cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1479   };
1480
1481
1482 ValueRefList : ResolvedVal {    // Used for call statements, and memory insts...
1483     $$ = new vector<Value*>();
1484     $$->push_back($1);
1485   }
1486   | ValueRefList ',' ResolvedVal {
1487     $$ = $1;
1488     $1->push_back($3);
1489   };
1490
1491 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1492 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1493
1494 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1495     $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1496     if ($$ == 0)
1497       ThrowException("binary operator returned null!");
1498     delete $2;
1499   }
1500   | UnaryOps ResolvedVal {
1501     $$ = UnaryOperator::create($1, $2);
1502     if ($$ == 0)
1503       ThrowException("unary operator returned null!");
1504   }
1505   | ShiftOps ResolvedVal ',' ResolvedVal {
1506     if ($4->getType() != Type::UByteTy)
1507       ThrowException("Shift amount must be ubyte!");
1508     $$ = new ShiftInst($1, $2, $4);
1509   }
1510   | CAST ResolvedVal TO Types {
1511     $$ = new CastInst($2, *$4);
1512     delete $4;
1513   }
1514   | PHI PHIList {
1515     const Type *Ty = $2->front().first->getType();
1516     $$ = new PHINode(Ty);
1517     while ($2->begin() != $2->end()) {
1518       if ($2->front().first->getType() != Ty) 
1519         ThrowException("All elements of a PHI node must be of the same type!");
1520       cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1521       $2->pop_front();
1522     }
1523     delete $2;  // Free the list...
1524   } 
1525   | CALL TypesV ValueRef '(' ValueRefListE ')' {
1526     const PointerType *PMTy;
1527     const FunctionType *Ty;
1528
1529     if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1530         !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1531       // Pull out the types of all of the arguments...
1532       vector<const Type*> ParamTypes;
1533       if ($5) {
1534         for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1535           ParamTypes.push_back((*I)->getType());
1536       }
1537
1538       bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1539       if (isVarArg) ParamTypes.pop_back();
1540
1541       Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1542       PMTy = PointerType::get(Ty);
1543     }
1544     delete $2;
1545
1546     Value *V = getVal(PMTy, $3);   // Get the function we're calling...
1547
1548     // Create the call node...
1549     if (!$5) {                                   // Has no arguments?
1550       $$ = new CallInst(V, vector<Value*>());
1551     } else {                                     // Has arguments?
1552       // Loop through FunctionType's arguments and ensure they are specified
1553       // correctly!
1554       //
1555       FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1556       FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1557       vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1558
1559       for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1560         if ((*ArgI)->getType() != *I)
1561           ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1562                          (*I)->getDescription() + "'!");
1563
1564       if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1565         ThrowException("Invalid number of parameters detected!");
1566
1567       $$ = new CallInst(V, *$5);
1568     }
1569     delete $5;
1570   }
1571   | MemoryInst {
1572     $$ = $1;
1573   };
1574
1575
1576 // IndexList - List of indices for GEP based instructions...
1577 IndexList : ',' ValueRefList { 
1578   $$ = $2; 
1579 } | /* empty */ { 
1580   $$ = new vector<Value*>(); 
1581 };
1582
1583 MemoryInst : MALLOC Types {
1584     $$ = new MallocInst(PointerType::get(*$2));
1585     delete $2;
1586   }
1587   | MALLOC Types ',' UINT ValueRef {
1588     const Type *Ty = PointerType::get(*$2);
1589     $$ = new MallocInst(Ty, getVal($4, $5));
1590     delete $2;
1591   }
1592   | ALLOCA Types {
1593     $$ = new AllocaInst(PointerType::get(*$2));
1594     delete $2;
1595   }
1596   | ALLOCA Types ',' UINT ValueRef {
1597     const Type *Ty = PointerType::get(*$2);
1598     Value *ArrSize = getVal($4, $5);
1599     $$ = new AllocaInst(Ty, ArrSize);
1600     delete $2;
1601   }
1602   | FREE ResolvedVal {
1603     if (!isa<PointerType>($2->getType()))
1604       ThrowException("Trying to free nonpointer type " + 
1605                      $2->getType()->getDescription() + "!");
1606     $$ = new FreeInst($2);
1607   }
1608
1609   | LOAD Types ValueRef IndexList {
1610     if (!isa<PointerType>($2->get()))
1611       ThrowException("Can't load from nonpointer type: " +
1612                      (*$2)->getDescription());
1613     if (LoadInst::getIndexedType(*$2, *$4) == 0)
1614       ThrowException("Invalid indices for load instruction!");
1615
1616     $$ = new LoadInst(getVal(*$2, $3), *$4);
1617     delete $4;   // Free the vector...
1618     delete $2;
1619   }
1620   | STORE ResolvedVal ',' Types ValueRef IndexList {
1621     if (!isa<PointerType>($4->get()))
1622       ThrowException("Can't store to a nonpointer type: " +
1623                      (*$4)->getDescription());
1624     const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1625     if (ElTy == 0)
1626       ThrowException("Can't store into that field list!");
1627     if (ElTy != $2->getType())
1628       ThrowException("Can't store '" + $2->getType()->getDescription() +
1629                      "' into space of type '" + ElTy->getDescription() + "'!");
1630     $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1631     delete $4; delete $6;
1632   }
1633   | GETELEMENTPTR Types ValueRef IndexList {
1634     if (!isa<PointerType>($2->get()))
1635       ThrowException("getelementptr insn requires pointer operand!");
1636     if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1637       ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1638     $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1639     delete $2; delete $4;
1640   };
1641
1642 %%
1643 int yyerror(const char *ErrorMsg) {
1644   string where  = string((CurFilename == "-")? string("<stdin>") : CurFilename)
1645                   + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1646   string errMsg = string(ErrorMsg) + string("\n") + where + " while reading ";
1647   if (yychar == YYEMPTY)
1648     errMsg += "end-of-file.";
1649   else
1650     errMsg += "token: '" + string(llvmAsmtext, llvmAsmleng) + "'";
1651   ThrowException(errMsg);
1652   return 0;
1653 }