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