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