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