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