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