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