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