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