1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
3 // This file implements the bison parser for LLVM assembly languages files.
5 //===------------------------------------------------------------------------=//
8 #include "ParserInternals.h"
9 #include "llvm/SymbolTable.h"
10 #include "llvm/Module.h"
11 #include "llvm/GlobalVariable.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/Argument.h"
16 #include "Support/STLExtras.h"
17 #include "Support/DepthFirstIterator.h"
19 #include <utility> // Get definition of pair class
31 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
32 int yylex(); // declaration" of xxx warnings.
35 static Module *ParserResult;
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
41 //#define DEBUG_UPREFS 1
43 #define UR_OUT(X) cerr << X
48 // This contains info used when building the body of a method. It is destroyed
49 // when the method is completed.
51 typedef vector<Value *> ValueList; // Numbered defs
52 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
53 vector<ValueList> *FutureLateResolvers = 0);
55 static struct PerModuleInfo {
56 Module *CurrentModule;
57 vector<ValueList> Values; // Module level numbered definitions
58 vector<ValueList> LateResolveValues;
59 vector<PATypeHolder> Types;
60 map<ValID, PATypeHolder> LateResolveTypes;
62 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
63 // references to global values. Global values may be referenced before they
64 // are defined, and if so, the temporary object that they represent is held
65 // here. This is used for forward references of ConstantPointerRefs.
67 typedef map<pair<const PointerType *, ValID>, GlobalVariable*> GlobalRefsType;
68 GlobalRefsType GlobalRefs;
71 // If we could not resolve some methods at method compilation time (calls to
72 // methods before they are defined), resolve them now... Types are resolved
73 // when the constant pool has been completely parsed.
75 ResolveDefinitions(LateResolveValues);
77 // Check to make sure that all global value forward references have been
80 if (!GlobalRefs.empty()) {
81 string UndefinedReferences = "Unresolved global references exist:\n";
83 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
85 UndefinedReferences += " " + I->first.first->getDescription() + " " +
86 I->first.second.getName() + "\n";
88 ThrowException(UndefinedReferences);
91 Values.clear(); // Clear out method local definitions
97 // DeclareNewGlobalValue - Called every type a new GV has been defined. This
98 // is used to remove things from the forward declaration map, resolving them
99 // to the correct thing as needed.
101 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
102 // Check to see if there is a forward reference to this global variable...
103 // if there is, eliminate it and patch the reference to use the new def'n.
104 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), D));
106 if (I != GlobalRefs.end()) {
107 GlobalVariable *OldGV = I->second; // Get the placeholder...
108 I->first.second.destroy(); // Free string memory if neccesary
110 // Loop over all of the uses of the GlobalValue. The only thing they are
111 // allowed to be at this point is ConstantPointerRef's.
112 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
113 while (!OldGV->use_empty()) {
114 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
115 ConstantPointerRef *CPPR = cast<ConstantPointerRef>(U);
116 assert(CPPR->getValue() == OldGV && "Something isn't happy");
118 // Change the const pool reference to point to the real global variable
119 // now. This should drop a use from the OldGV.
120 CPPR->mutateReference(GV);
123 // Remove GV from the module...
124 CurrentModule->getGlobalList().remove(OldGV);
125 delete OldGV; // Delete the old placeholder
127 // Remove the map entry for the global now that it has been created...
134 static struct PerFunctionInfo {
135 Function *CurrentFunction; // Pointer to current method being created
137 vector<ValueList> Values; // Keep track of numbered definitions
138 vector<ValueList> LateResolveValues;
139 vector<PATypeHolder> Types;
140 map<ValID, PATypeHolder> LateResolveTypes;
141 bool isDeclare; // Is this method a forward declararation?
143 inline PerFunctionInfo() {
148 inline ~PerFunctionInfo() {}
150 inline void FunctionStart(Function *M) {
154 void FunctionDone() {
155 // If we could not resolve some blocks at parsing time (forward branches)
156 // resolve the branches now...
157 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
159 Values.clear(); // Clear out method local definitions
164 } CurMeth; // Info for the current method...
166 static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
169 //===----------------------------------------------------------------------===//
170 // Code to handle definitions of all the types
171 //===----------------------------------------------------------------------===//
173 static int InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
174 if (D->hasName()) return -1; // Is this a numbered definition?
176 // Yes, insert the value into the value table...
177 unsigned type = D->getType()->getUniqueID();
178 if (ValueTab.size() <= type)
179 ValueTab.resize(type+1, ValueList());
180 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
181 ValueTab[type].push_back(D);
182 return ValueTab[type].size()-1;
185 // TODO: FIXME when Type are not const
186 static void InsertType(const Type *Ty, vector<PATypeHolder> &Types) {
190 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
192 case 0: { // Is it a numbered definition?
193 unsigned Num = (unsigned)D.Num;
195 // Module constants occupy the lowest numbered slots...
196 if (Num < CurModule.Types.size())
197 return CurModule.Types[Num];
199 Num -= CurModule.Types.size();
201 // Check that the number is within bounds...
202 if (Num <= CurMeth.Types.size())
203 return CurMeth.Types[Num];
206 case 1: { // Is it a named definition?
208 SymbolTable *SymTab = 0;
209 if (inFunctionScope()) SymTab = CurMeth.CurrentFunction->getSymbolTable();
210 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
213 // Symbol table doesn't automatically chain yet... because the method
214 // hasn't been added to the module...
216 SymTab = CurModule.CurrentModule->getSymbolTable();
218 N = SymTab->lookup(Type::TypeTy, Name);
222 D.destroy(); // Free old strdup'd memory...
223 return cast<const Type>(N);
226 ThrowException("Invalid symbol type reference!");
229 // If we reached here, we referenced either a symbol that we don't know about
230 // or an id number that hasn't been read yet. We may be referencing something
231 // forward, so just create an entry to be resolved later and get to it...
233 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
235 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
236 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
238 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
239 if (I != LateResolver.end()) {
243 Type *Typ = OpaqueType::get();
244 LateResolver.insert(make_pair(D, Typ));
248 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
249 SymbolTable *SymTab =
250 inFunctionScope() ? CurMeth.CurrentFunction->getSymbolTable() : 0;
251 return SymTab ? SymTab->lookup(Ty, Name) : 0;
254 // getValNonImprovising - Look up the value specified by the provided type and
255 // the provided ValID. If the value exists and has already been defined, return
256 // it. Otherwise return null.
258 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
259 if (isa<FunctionType>(Ty))
260 ThrowException("Functions are not values and "
261 "must be referenced as pointers");
264 case ValID::NumberVal: { // Is it a numbered definition?
265 unsigned type = Ty->getUniqueID();
266 unsigned Num = (unsigned)D.Num;
268 // Module constants occupy the lowest numbered slots...
269 if (type < CurModule.Values.size()) {
270 if (Num < CurModule.Values[type].size())
271 return CurModule.Values[type][Num];
273 Num -= CurModule.Values[type].size();
276 // Make sure that our type is within bounds
277 if (CurMeth.Values.size() <= type) return 0;
279 // Check that the number is within bounds...
280 if (CurMeth.Values[type].size() <= Num) return 0;
282 return CurMeth.Values[type][Num];
285 case ValID::NameVal: { // Is it a named definition?
286 Value *N = lookupInSymbolTable(Ty, string(D.Name));
287 if (N == 0) return 0;
289 D.destroy(); // Free old strdup'd memory...
293 // Check to make sure that "Ty" is an integral type, and that our
294 // value will fit into the specified type...
295 case ValID::ConstSIntVal: // Is it a constant pool reference??
296 if (Ty == Type::BoolTy) { // Special handling for boolean data
297 return ConstantBool::get(D.ConstPool64 != 0);
299 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
300 ThrowException("Symbolic constant pool value '" +
301 itostr(D.ConstPool64) + "' is invalid for type '" +
302 Ty->getDescription() + "'!");
303 return ConstantSInt::get(Ty, D.ConstPool64);
306 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
307 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
308 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
309 ThrowException("Integral constant pool reference is invalid!");
310 } else { // This is really a signed reference. Transmogrify.
311 return ConstantSInt::get(Ty, D.ConstPool64);
314 return ConstantUInt::get(Ty, D.UConstPool64);
317 case ValID::ConstFPVal: // Is it a floating point const pool reference?
318 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
319 ThrowException("FP constant invalid for type!!");
320 return ConstantFP::get(Ty, D.ConstPoolFP);
322 case ValID::ConstNullVal: // Is it a null value?
323 if (!Ty->isPointerType())
324 ThrowException("Cannot create a a non pointer null!");
325 return ConstantPointerNull::get(cast<PointerType>(Ty));
328 assert(0 && "Unhandled case!");
332 assert(0 && "Unhandled case!");
337 // getVal - This function is identical to getValNonImprovising, except that if a
338 // value is not already defined, it "improvises" by creating a placeholder var
339 // that looks and acts just like the requested variable. When the value is
340 // defined later, all uses of the placeholder variable are replaced with the
343 static Value *getVal(const Type *Ty, const ValID &D) {
344 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
346 // See if the value has already been defined...
347 Value *V = getValNonImprovising(Ty, D);
350 // If we reached here, we referenced either a symbol that we don't know about
351 // or an id number that hasn't been read yet. We may be referencing something
352 // forward, so just create an entry to be resolved later and get to it...
355 switch (Ty->getPrimitiveID()) {
356 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
357 default: d = new ValuePlaceHolder(Ty, D); break;
360 assert(d != 0 && "How did we not make something?");
361 if (inFunctionScope())
362 InsertValue(d, CurMeth.LateResolveValues);
364 InsertValue(d, CurModule.LateResolveValues);
369 //===----------------------------------------------------------------------===//
370 // Code to handle forward references in instructions
371 //===----------------------------------------------------------------------===//
373 // This code handles the late binding needed with statements that reference
374 // values not defined yet... for example, a forward branch, or the PHI node for
377 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
378 // and back patchs after we are done.
381 // ResolveDefinitions - If we could not resolve some defs at parsing
382 // time (forward branches, phi functions for loops, etc...) resolve the
385 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
386 vector<ValueList> *FutureLateResolvers = 0) {
387 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
388 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
389 while (!LateResolvers[ty].empty()) {
390 Value *V = LateResolvers[ty].back();
391 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
393 LateResolvers[ty].pop_back();
394 ValID &DID = getValIDFromPlaceHolder(V);
396 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
398 V->replaceAllUsesWith(TheRealValue);
400 } else if (FutureLateResolvers) {
401 // Functions have their unresolved items forwarded to the module late
403 InsertValue(V, *FutureLateResolvers);
406 ThrowException("Reference to an invalid definition: '" +DID.getName()+
407 "' of type '" + V->getType()->getDescription() + "'",
408 getLineNumFromPlaceHolder(V));
410 ThrowException("Reference to an invalid definition: #" +
411 itostr(DID.Num) + " of type '" +
412 V->getType()->getDescription() + "'",
413 getLineNumFromPlaceHolder(V));
418 LateResolvers.clear();
421 // ResolveTypeTo - A brand new type was just declared. This means that (if
422 // name is not null) things referencing Name can be resolved. Otherwise, things
423 // refering to the number can be resolved. Do this now.
425 static void ResolveTypeTo(char *Name, const Type *ToTy) {
426 vector<PATypeHolder> &Types = inFunctionScope() ?
427 CurMeth.Types : CurModule.Types;
430 if (Name) D = ValID::create(Name);
431 else D = ValID::create((int)Types.size());
433 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
434 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
436 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
437 if (I != LateResolver.end()) {
438 cast<DerivedType>(I->second.get())->refineAbstractTypeTo(ToTy);
439 LateResolver.erase(I);
443 // ResolveTypes - At this point, all types should be resolved. Any that aren't
446 static void ResolveTypes(map<ValID, PATypeHolder> &LateResolveTypes) {
447 if (!LateResolveTypes.empty()) {
448 const ValID &DID = LateResolveTypes.begin()->first;
450 if (DID.Type == ValID::NameVal)
451 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
453 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
458 // setValueName - Set the specified value to the name given. The name may be
459 // null potentially, in which case this is a noop. The string passed in is
460 // assumed to be a malloc'd string buffer, and is freed by this function.
462 // This function returns true if the value has already been defined, but is
463 // allowed to be redefined in the specified context. If the name is a new name
464 // for the typeplane, false is returned.
466 static bool setValueName(Value *V, char *NameStr) {
467 if (NameStr == 0) return false;
469 string Name(NameStr); // Copy string
470 free(NameStr); // Free old string
472 if (V->getType() == Type::VoidTy)
473 ThrowException("Can't assign name '" + Name +
474 "' to a null valued instruction!");
476 SymbolTable *ST = inFunctionScope() ?
477 CurMeth.CurrentFunction->getSymbolTableSure() :
478 CurModule.CurrentModule->getSymbolTableSure();
480 Value *Existing = ST->lookup(V->getType(), Name);
481 if (Existing) { // Inserting a name that is already defined???
482 // There is only one case where this is allowed: when we are refining an
483 // opaque type. In this case, Existing will be an opaque type.
484 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
485 if (OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
486 // We ARE replacing an opaque type!
487 OpTy->refineAbstractTypeTo(cast<Type>(V));
492 // Otherwise, we are a simple redefinition of a value, check to see if it
493 // is defined the same as the old one...
494 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
495 if (Ty == cast<const Type>(V)) return true; // Yes, it's equal.
496 // cerr << "Type: " << Ty->getDescription() << " != "
497 // << cast<const Type>(V)->getDescription() << "!\n";
498 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
499 // We are allowed to redefine a global variable in two circumstances:
500 // 1. If at least one of the globals is uninitialized or
501 // 2. If both initializers have the same value.
503 // This can only be done if the const'ness of the vars is the same.
505 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
506 if (EGV->isConstant() == GV->isConstant() &&
507 (!EGV->hasInitializer() || !GV->hasInitializer() ||
508 EGV->getInitializer() == GV->getInitializer())) {
510 // Make sure the existing global version gets the initializer!
511 if (GV->hasInitializer() && !EGV->hasInitializer())
512 EGV->setInitializer(GV->getInitializer());
514 delete GV; // Destroy the duplicate!
515 return true; // They are equivalent!
519 ThrowException("Redefinition of value named '" + Name + "' in the '" +
520 V->getType()->getDescription() + "' type plane!");
523 V->setName(Name, ST);
528 //===----------------------------------------------------------------------===//
529 // Code for handling upreferences in type names...
532 // TypeContains - Returns true if Ty contains E in it.
534 static bool TypeContains(const Type *Ty, const Type *E) {
535 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
539 static vector<pair<unsigned, OpaqueType *> > UpRefs;
541 static PATypeHolder HandleUpRefs(const Type *ty) {
543 UR_OUT("Type '" << ty->getDescription() <<
544 "' newly formed. Resolving upreferences.\n" <<
545 UpRefs.size() << " upreferences active!\n");
546 for (unsigned i = 0; i < UpRefs.size(); ) {
547 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
548 << UpRefs[i].second->getDescription() << ") = "
549 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
550 if (TypeContains(Ty, UpRefs[i].second)) {
551 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
552 UR_OUT(" Uplevel Ref Level = " << Level << endl);
553 if (Level == 0) { // Upreference should be resolved!
554 UR_OUT(" * Resolving upreference for "
555 << UpRefs[i].second->getDescription() << endl;
556 string OldName = UpRefs[i].second->getDescription());
557 UpRefs[i].second->refineAbstractTypeTo(Ty);
558 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
559 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
560 << (const void*)Ty << ", " << Ty->getDescription() << endl);
565 ++i; // Otherwise, no resolve, move on...
567 // FIXME: TODO: this should return the updated type
572 //===----------------------------------------------------------------------===//
573 // RunVMAsmParser - Define an interface to this parser
574 //===----------------------------------------------------------------------===//
576 Module *RunVMAsmParser(const string &Filename, FILE *F) {
578 CurFilename = Filename;
579 llvmAsmlineno = 1; // Reset the current line number...
581 CurModule.CurrentModule = new Module(); // Allocate a new module to read
582 yyparse(); // Parse the file.
583 Module *Result = ParserResult;
584 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
594 Function *FunctionVal;
595 std::pair<Argument*, char*> *ArgVal;
596 BasicBlock *BasicBlockVal;
597 TerminatorInst *TermInstVal;
598 Instruction *InstVal;
601 const Type *PrimType;
602 PATypeHolder *TypeVal;
605 std::list<std::pair<Argument*,char*> > *ArgList;
606 std::vector<Value*> *ValueList;
607 std::list<PATypeHolder> *TypeList;
608 std::list<std::pair<Value*,
609 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
610 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
611 std::vector<Constant*> *ConstVector;
620 char *StrVal; // This memory is strdup'd!
621 ValID ValIDVal; // strdup'd memory maybe!
623 Instruction::UnaryOps UnaryOpVal;
624 Instruction::BinaryOps BinaryOpVal;
625 Instruction::TermOps TermOpVal;
626 Instruction::MemoryOps MemOpVal;
627 Instruction::OtherOps OtherOpVal;
630 %type <ModuleVal> Module FunctionList
631 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
632 %type <BasicBlockVal> BasicBlock InstructionList
633 %type <TermInstVal> BBTerminatorInst
634 %type <InstVal> Inst InstVal MemoryInst
635 %type <ConstVal> ConstVal
636 %type <ConstVector> ConstVector
637 %type <ArgList> ArgList ArgListH
638 %type <ArgVal> ArgVal
639 %type <PHIList> PHIList
640 %type <ValueList> ValueRefList ValueRefListE // For call param lists
641 %type <ValueList> IndexList // For GEP derived indices
642 %type <TypeList> TypeListI ArgTypeListI
643 %type <JumpTable> JumpTable
644 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
646 // ValueRef - Unresolved reference to a definition or BB
647 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
648 %type <ValueVal> ResolvedVal // <type> <valref> pair
649 // Tokens and types for handling constant integer values
651 // ESINT64VAL - A negative number within long long range
652 %token <SInt64Val> ESINT64VAL
654 // EUINT64VAL - A positive number within uns. long long range
655 %token <UInt64Val> EUINT64VAL
656 %type <SInt64Val> EINT64VAL
658 %token <SIntVal> SINTVAL // Signed 32 bit ints...
659 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
660 %type <SIntVal> INTVAL
661 %token <FPVal> FPVAL // Float or Double constant
664 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
665 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
666 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
667 %token <PrimType> FLOAT DOUBLE TYPE LABEL
669 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
670 %type <StrVal> OptVAR_ID OptAssign
673 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
674 %token TO EXCEPT DOTDOTDOT STRING NULL_TOK CONST INTERNAL OPAQUE
676 // Basic Block Terminating Operators
677 %token <TermOpVal> RET BR SWITCH
680 %type <UnaryOpVal> UnaryOps // all the unary operators
681 %token <UnaryOpVal> NOT
684 %type <BinaryOpVal> BinaryOps // all the binary operators
685 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
686 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
688 // Memory Instructions
689 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
692 %type <OtherOpVal> ShiftOps
693 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
698 // Handle constant integer size restriction and conversion...
703 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
704 ThrowException("Value too large for type!");
709 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
710 EINT64VAL : EUINT64VAL {
711 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
712 ThrowException("Value too large for type!");
716 // Operations that are notably excluded from this list include:
717 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
720 BinaryOps : ADD | SUB | MUL | DIV | REM | AND | OR | XOR
721 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
724 // These are some types that allow classification if we only want a particular
725 // thing... for example, only a signed, unsigned, or integral type.
726 SIntType : LONG | INT | SHORT | SBYTE
727 UIntType : ULONG | UINT | USHORT | UBYTE
728 IntType : SIntType | UIntType
729 FPType : FLOAT | DOUBLE
731 // OptAssign - Value producing statements have an optional assignment component
732 OptAssign : VAR_ID '=' {
739 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; }
741 //===----------------------------------------------------------------------===//
742 // Types includes all predefined types... except void, because it can only be
743 // used in specific contexts (method returning void for example). To have
744 // access to it, a user must explicitly use TypesV.
747 // TypesV includes all of 'Types', but it also includes the void type.
748 TypesV : Types | VOID { $$ = new PATypeHolder($1); }
749 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); }
753 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
758 // Derived types are added later...
760 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
761 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
763 $$ = new PATypeHolder(OpaqueType::get());
766 $$ = new PATypeHolder($1);
768 UpRTypes : ValueRef { // Named types are also simple types...
769 $$ = new PATypeHolder(getTypeVal($1));
772 // Include derived types in the Types production.
774 UpRTypes : '\\' EUINT64VAL { // Type UpReference
775 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
776 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
777 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
778 $$ = new PATypeHolder(OT);
779 UR_OUT("New Upreference!\n");
781 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
782 vector<const Type*> Params;
783 mapto($3->begin(), $3->end(), std::back_inserter(Params),
784 std::mem_fun_ref(&PATypeHandle<Type>::get));
785 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
786 if (isVarArg) Params.pop_back();
788 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
789 delete $3; // Delete the argument list
790 delete $1; // Delete the old type handle
792 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
793 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
796 | '{' TypeListI '}' { // Structure type?
797 vector<const Type*> Elements;
798 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
799 std::mem_fun_ref(&PATypeHandle<Type>::get));
801 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
804 | '{' '}' { // Empty structure type?
805 $$ = new PATypeHolder(StructType::get(vector<const Type*>()));
807 | UpRTypes '*' { // Pointer type?
808 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
812 // TypeList - Used for struct declarations and as a basis for method type
813 // declaration type lists
815 TypeListI : UpRTypes {
816 $$ = new list<PATypeHolder>();
817 $$->push_back(*$1); delete $1;
819 | TypeListI ',' UpRTypes {
820 ($$=$1)->push_back(*$3); delete $3;
823 // ArgTypeList - List of types for a method type declaration...
824 ArgTypeListI : TypeListI
825 | TypeListI ',' DOTDOTDOT {
826 ($$=$1)->push_back(Type::VoidTy);
829 ($$ = new list<PATypeHolder>())->push_back(Type::VoidTy);
832 $$ = new list<PATypeHolder>();
836 // ConstVal - The various declarations that go into the constant pool. This
837 // includes all forward declarations of types, constants, and functions.
839 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
840 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
842 ThrowException("Cannot make array constant with type: '" +
843 (*$1)->getDescription() + "'!");
844 const Type *ETy = ATy->getElementType();
845 int NumElements = ATy->getNumElements();
847 // Verify that we have the correct size...
848 if (NumElements != -1 && NumElements != (int)$3->size())
849 ThrowException("Type mismatch: constant sized array initialized with " +
850 utostr($3->size()) + " arguments, but has size of " +
851 itostr(NumElements) + "!");
853 // Verify all elements are correct type!
854 for (unsigned i = 0; i < $3->size(); i++) {
855 if (ETy != (*$3)[i]->getType())
856 ThrowException("Element #" + utostr(i) + " is not of type '" +
857 ETy->getDescription() +"' as required!\nIt is of type '"+
858 (*$3)[i]->getType()->getDescription() + "'.");
861 $$ = ConstantArray::get(ATy, *$3);
862 delete $1; delete $3;
865 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
867 ThrowException("Cannot make array constant with type: '" +
868 (*$1)->getDescription() + "'!");
870 int NumElements = ATy->getNumElements();
871 if (NumElements != -1 && NumElements != 0)
872 ThrowException("Type mismatch: constant sized array initialized with 0"
873 " arguments, but has size of " + itostr(NumElements) +"!");
874 $$ = ConstantArray::get(ATy, vector<Constant*>());
877 | Types 'c' STRINGCONSTANT {
878 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
880 ThrowException("Cannot make array constant with type: '" +
881 (*$1)->getDescription() + "'!");
883 int NumElements = ATy->getNumElements();
884 const Type *ETy = ATy->getElementType();
885 char *EndStr = UnEscapeLexed($3, true);
886 if (NumElements != -1 && NumElements != (EndStr-$3))
887 ThrowException("Can't build string constant of size " +
888 itostr((int)(EndStr-$3)) +
889 " when array has size " + itostr(NumElements) + "!");
890 vector<Constant*> Vals;
891 if (ETy == Type::SByteTy) {
892 for (char *C = $3; C != EndStr; ++C)
893 Vals.push_back(ConstantSInt::get(ETy, *C));
894 } else if (ETy == Type::UByteTy) {
895 for (char *C = $3; C != EndStr; ++C)
896 Vals.push_back(ConstantUInt::get(ETy, *C));
899 ThrowException("Cannot build string arrays of non byte sized elements!");
902 $$ = ConstantArray::get(ATy, Vals);
905 | Types '{' ConstVector '}' {
906 const StructType *STy = dyn_cast<const StructType>($1->get());
908 ThrowException("Cannot make struct constant with type: '" +
909 (*$1)->getDescription() + "'!");
910 // FIXME: TODO: Check to see that the constants are compatible with the type
912 $$ = ConstantStruct::get(STy, *$3);
913 delete $1; delete $3;
916 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
918 ThrowException("Cannot make null pointer constant with type: '" +
919 (*$1)->getDescription() + "'!");
921 $$ = ConstantPointerNull::get(PTy);
924 | Types SymbolicValueRef {
925 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
927 ThrowException("Global const reference must be a pointer type!");
929 Value *V = getValNonImprovising(Ty, $2);
931 // If this is an initializer for a constant pointer, which is referencing a
932 // (currently) undefined variable, create a stub now that shall be replaced
933 // in the future with the right type of variable.
936 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
937 const PointerType *PT = cast<PointerType>(Ty);
939 // First check to see if the forward references value is already created!
940 PerModuleInfo::GlobalRefsType::iterator I =
941 CurModule.GlobalRefs.find(make_pair(PT, $2));
943 if (I != CurModule.GlobalRefs.end()) {
944 V = I->second; // Placeholder already exists, use it...
946 // TODO: Include line number info by creating a subclass of
947 // TODO: GlobalVariable here that includes the said information!
949 // Create a placeholder for the global variable reference...
950 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
952 // Keep track of the fact that we have a forward ref to recycle it
953 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
955 // Must temporarily push this value into the module table...
956 CurModule.CurrentModule->getGlobalList().push_back(GV);
961 GlobalValue *GV = cast<GlobalValue>(V);
962 $$ = ConstantPointerRef::get(GV);
963 delete $1; // Free the type handle
967 ConstVal : SIntType EINT64VAL { // integral constants
968 if (!ConstantSInt::isValueValidForType($1, $2))
969 ThrowException("Constant value doesn't fit in type!");
970 $$ = ConstantSInt::get($1, $2);
972 | UIntType EUINT64VAL { // integral constants
973 if (!ConstantUInt::isValueValidForType($1, $2))
974 ThrowException("Constant value doesn't fit in type!");
975 $$ = ConstantUInt::get($1, $2);
977 | BOOL TRUE { // Boolean constants
978 $$ = ConstantBool::True;
980 | BOOL FALSE { // Boolean constants
981 $$ = ConstantBool::False;
983 | FPType FPVAL { // Float & Double constants
984 $$ = ConstantFP::get($1, $2);
987 // ConstVector - A list of comma seperated constants.
988 ConstVector : ConstVector ',' ConstVal {
989 ($$ = $1)->push_back($3);
992 $$ = new vector<Constant*>();
997 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
998 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
1001 //===----------------------------------------------------------------------===//
1002 // Rules to match Modules
1003 //===----------------------------------------------------------------------===//
1005 // Module rule: Capture the result of parsing the whole file into a result
1008 Module : FunctionList {
1009 $$ = ParserResult = $1;
1010 CurModule.ModuleDone();
1013 // FunctionList - A list of methods, preceeded by a constant pool.
1015 FunctionList : FunctionList Function {
1017 assert($2->getParent() == 0 && "Function already in module!");
1018 $1->getFunctionList().push_back($2);
1019 CurMeth.FunctionDone();
1021 | FunctionList FunctionProto {
1024 | FunctionList IMPLEMENTATION {
1028 $$ = CurModule.CurrentModule;
1029 // Resolve circular types before we parse the body of the module
1030 ResolveTypes(CurModule.LateResolveTypes);
1033 // ConstPool - Constants with optional names assigned to them.
1034 ConstPool : ConstPool OptAssign CONST ConstVal {
1035 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1038 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1039 // Eagerly resolve types. This is not an optimization, this is a
1040 // requirement that is due to the fact that we could have this:
1042 // %list = type { %list * }
1043 // %list = type { %list * } ; repeated type decl
1045 // If types are not resolved eagerly, then the two types will not be
1046 // determined to be the same type!
1048 ResolveTypeTo($2, $4->get());
1050 // TODO: FIXME when Type are not const
1051 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1052 // If this is not a redefinition of a type...
1054 InsertType($4->get(),
1055 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1061 | ConstPool FunctionProto { // Function prototypes can be in const pool
1063 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1064 const Type *Ty = $5->getType();
1065 // Global declarations appear in Constant Pool
1066 Constant *Initializer = $5;
1067 if (Initializer == 0)
1068 ThrowException("Global value initializer is not a constant!");
1070 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1071 if (!setValueName(GV, $2)) { // If not redefining...
1072 CurModule.CurrentModule->getGlobalList().push_back(GV);
1073 int Slot = InsertValue(GV, CurModule.Values);
1076 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1078 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1079 (char*)GV->getName().c_str()));
1083 | ConstPool OptAssign OptInternal UNINIT GlobalType Types {
1084 const Type *Ty = *$6;
1085 // Global declarations appear in Constant Pool
1086 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1087 if (!setValueName(GV, $2)) { // If not redefining...
1088 CurModule.CurrentModule->getGlobalList().push_back(GV);
1089 int Slot = InsertValue(GV, CurModule.Values);
1092 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1094 assert(GV->hasName() && "Not named and not numbered!?");
1095 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1096 (char*)GV->getName().c_str()));
1101 | /* empty: end of list */ {
1105 //===----------------------------------------------------------------------===//
1106 // Rules to match Function Headers
1107 //===----------------------------------------------------------------------===//
1109 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
1111 ArgVal : Types OptVAR_ID {
1112 $$ = new pair<Argument*, char*>(new Argument(*$1), $2);
1113 delete $1; // Delete the type handle..
1116 ArgListH : ArgVal ',' ArgListH {
1118 $3->push_front(*$1);
1122 $$ = new list<pair<Argument*,char*> >();
1123 $$->push_front(*$1);
1127 $$ = new list<pair<Argument*, char*> >();
1128 $$->push_front(pair<Argument*,char*>(new Argument(Type::VoidTy), 0));
1131 ArgList : ArgListH {
1138 FunctionHeaderH : OptInternal TypesV STRINGCONSTANT '(' ArgList ')' {
1140 string FunctionName($3);
1142 vector<const Type*> ParamTypeList;
1144 for (list<pair<Argument*,char*> >::iterator I = $5->begin();
1145 I != $5->end(); ++I)
1146 ParamTypeList.push_back(I->first->getType());
1148 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1149 if (isVarArg) ParamTypeList.pop_back();
1151 const FunctionType *MT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1152 const PointerType *PMT = PointerType::get(MT);
1156 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1157 // Is the function already in symtab?
1158 if (Value *V = ST->lookup(PMT, FunctionName)) {
1159 M = cast<Function>(V);
1161 // Yes it is. If this is the case, either we need to be a forward decl,
1162 // or it needs to be.
1163 if (!CurMeth.isDeclare && !M->isExternal())
1164 ThrowException("Redefinition of method '" + FunctionName + "'!");
1166 // If we found a preexisting method prototype, remove it from the module,
1167 // so that we don't get spurious conflicts with global & local variables.
1169 CurModule.CurrentModule->getFunctionList().remove(M);
1173 if (M == 0) { // Not already defined?
1174 M = new Function(MT, $1, FunctionName);
1175 InsertValue(M, CurModule.Values);
1176 CurModule.DeclareNewGlobalValue(M, ValID::create($3));
1178 free($3); // Free strdup'd memory!
1180 CurMeth.FunctionStart(M);
1182 // Add all of the arguments we parsed to the method...
1183 if ($5 && !CurMeth.isDeclare) { // Is null if empty...
1184 Function::ArgumentListType &ArgList = M->getArgumentList();
1186 for (list<pair<Argument*, char*> >::iterator I = $5->begin();
1187 I != $5->end(); ++I) {
1188 if (setValueName(I->first, I->second)) { // Insert into symtab...
1189 assert(0 && "No arg redef allowed!");
1192 InsertValue(I->first);
1193 ArgList.push_back(I->first);
1195 delete $5; // We're now done with the argument list
1197 // If we are a declaration, we should free the memory for the argument list!
1198 for (list<pair<Argument*, char*> >::iterator I = $5->begin(), E = $5->end();
1200 if (I->second) free(I->second); // Free the memory for the name...
1201 delete I->first; // Free the unused function argument
1203 delete $5; // Free the memory for the list itself
1207 FunctionHeader : FunctionHeaderH ConstPool BEGINTOK {
1208 $$ = CurMeth.CurrentFunction;
1210 // Resolve circular types before we parse the body of the method.
1211 ResolveTypes(CurMeth.LateResolveTypes);
1214 Function : BasicBlockList END {
1218 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1219 $$ = CurMeth.CurrentFunction;
1220 assert($$->getParent() == 0 && "Function already in module!");
1221 CurModule.CurrentModule->getFunctionList().push_back($$);
1222 CurMeth.FunctionDone();
1225 //===----------------------------------------------------------------------===//
1226 // Rules to match Basic Blocks
1227 //===----------------------------------------------------------------------===//
1229 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1230 $$ = ValID::create($1);
1233 $$ = ValID::create($1);
1235 | FPVAL { // Perhaps it's an FP constant?
1236 $$ = ValID::create($1);
1239 $$ = ValID::create((int64_t)1);
1242 $$ = ValID::create((int64_t)0);
1245 $$ = ValID::createNull();
1249 | STRINGCONSTANT { // Quoted strings work too... especially for methods
1250 $$ = ValID::create_conststr($1);
1254 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1257 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1258 $$ = ValID::create($1);
1260 | VAR_ID { // Is it a named reference...?
1261 $$ = ValID::create($1);
1264 // ValueRef - A reference to a definition... either constant or symbolic
1265 ValueRef : SymbolicValueRef | ConstValueRef
1268 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1269 // type immediately preceeds the value reference, and allows complex constant
1270 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1271 ResolvedVal : Types ValueRef {
1272 $$ = getVal(*$1, $2); delete $1;
1276 BasicBlockList : BasicBlockList BasicBlock {
1277 ($$ = $1)->getBasicBlocks().push_back($2);
1279 | FunctionHeader BasicBlock { // Do not allow methods with 0 basic blocks
1280 ($$ = $1)->getBasicBlocks().push_back($2);
1284 // Basic blocks are terminated by branching instructions:
1285 // br, br/cc, switch, ret
1287 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1288 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1291 $1->getInstList().push_back($3);
1295 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1296 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1299 $2->getInstList().push_back($4);
1300 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1306 InstructionList : InstructionList Inst {
1307 $1->getInstList().push_back($2);
1311 $$ = new BasicBlock();
1314 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1315 $$ = new ReturnInst($2);
1317 | RET VOID { // Return with no result...
1318 $$ = new ReturnInst();
1320 | BR LABEL ValueRef { // Unconditional Branch...
1321 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1322 } // Conditional Branch...
1323 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1324 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1325 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1326 getVal(Type::BoolTy, $3));
1328 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1329 SwitchInst *S = new SwitchInst(getVal($2, $3),
1330 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1333 vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1336 S->dest_push_back(I->first, I->second);
1338 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1339 EXCEPT ResolvedVal {
1340 const PointerType *PMTy;
1341 const FunctionType *Ty;
1343 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1344 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1345 // Pull out the types of all of the arguments...
1346 vector<const Type*> ParamTypes;
1348 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1349 ParamTypes.push_back((*I)->getType());
1352 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1353 if (isVarArg) ParamTypes.pop_back();
1355 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1356 PMTy = PointerType::get(Ty);
1360 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1362 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1363 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1365 if (Normal == 0 || Except == 0)
1366 ThrowException("Invoke instruction without label destinations!");
1368 // Create the call node...
1369 if (!$5) { // Has no arguments?
1370 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1371 } else { // Has arguments?
1372 // Loop through FunctionType's arguments and ensure they are specified
1375 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1376 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1377 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1379 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1380 if ((*ArgI)->getType() != *I)
1381 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1382 (*I)->getDescription() + "'!");
1384 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1385 ThrowException("Invalid number of parameters detected!");
1387 $$ = new InvokeInst(V, Normal, Except, *$5);
1394 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1396 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1398 ThrowException("May only switch on a constant pool value!");
1400 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1402 | IntType ConstValueRef ',' LABEL ValueRef {
1403 $$ = new vector<pair<Constant*, BasicBlock*> >();
1404 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1407 ThrowException("May only switch on a constant pool value!");
1409 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1412 Inst : OptAssign InstVal {
1413 // Is this definition named?? if so, assign the name...
1414 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1419 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1420 $$ = new list<pair<Value*, BasicBlock*> >();
1421 $$->push_back(make_pair(getVal(*$1, $3),
1422 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1425 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1427 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1428 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1432 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1433 $$ = new vector<Value*>();
1436 | ValueRefList ',' ResolvedVal {
1441 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1442 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1444 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1445 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1447 ThrowException("binary operator returned null!");
1450 | UnaryOps ResolvedVal {
1451 $$ = UnaryOperator::create($1, $2);
1453 ThrowException("unary operator returned null!");
1455 | ShiftOps ResolvedVal ',' ResolvedVal {
1456 if ($4->getType() != Type::UByteTy)
1457 ThrowException("Shift amount must be ubyte!");
1458 $$ = new ShiftInst($1, $2, $4);
1460 | CAST ResolvedVal TO Types {
1461 $$ = new CastInst($2, *$4);
1465 const Type *Ty = $2->front().first->getType();
1466 $$ = new PHINode(Ty);
1467 while ($2->begin() != $2->end()) {
1468 if ($2->front().first->getType() != Ty)
1469 ThrowException("All elements of a PHI node must be of the same type!");
1470 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1473 delete $2; // Free the list...
1475 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1476 const PointerType *PMTy;
1477 const FunctionType *Ty;
1479 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1480 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1481 // Pull out the types of all of the arguments...
1482 vector<const Type*> ParamTypes;
1484 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1485 ParamTypes.push_back((*I)->getType());
1488 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1489 if (isVarArg) ParamTypes.pop_back();
1491 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1492 PMTy = PointerType::get(Ty);
1496 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1498 // Create the call node...
1499 if (!$5) { // Has no arguments?
1500 $$ = new CallInst(V, vector<Value*>());
1501 } else { // Has arguments?
1502 // Loop through FunctionType's arguments and ensure they are specified
1505 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1506 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1507 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1509 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1510 if ((*ArgI)->getType() != *I)
1511 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1512 (*I)->getDescription() + "'!");
1514 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1515 ThrowException("Invalid number of parameters detected!");
1517 $$ = new CallInst(V, *$5);
1526 // IndexList - List of indices for GEP based instructions...
1527 IndexList : ',' ValueRefList {
1530 $$ = new vector<Value*>();
1533 MemoryInst : MALLOC Types {
1534 $$ = new MallocInst(PointerType::get(*$2));
1537 | MALLOC Types ',' UINT ValueRef {
1538 const Type *Ty = PointerType::get(*$2);
1539 $$ = new MallocInst(Ty, getVal($4, $5));
1543 $$ = new AllocaInst(PointerType::get(*$2));
1546 | ALLOCA Types ',' UINT ValueRef {
1547 const Type *Ty = PointerType::get(*$2);
1548 Value *ArrSize = getVal($4, $5);
1549 $$ = new AllocaInst(Ty, ArrSize);
1552 | FREE ResolvedVal {
1553 if (!$2->getType()->isPointerType())
1554 ThrowException("Trying to free nonpointer type " +
1555 $2->getType()->getDescription() + "!");
1556 $$ = new FreeInst($2);
1559 | LOAD Types ValueRef IndexList {
1560 if (!(*$2)->isPointerType())
1561 ThrowException("Can't load from nonpointer type: " +
1562 (*$2)->getDescription());
1563 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1564 ThrowException("Invalid indices for load instruction!");
1566 $$ = new LoadInst(getVal(*$2, $3), *$4);
1567 delete $4; // Free the vector...
1570 | STORE ResolvedVal ',' Types ValueRef IndexList {
1571 if (!(*$4)->isPointerType())
1572 ThrowException("Can't store to a nonpointer type: " +
1573 (*$4)->getDescription());
1574 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1576 ThrowException("Can't store into that field list!");
1577 if (ElTy != $2->getType())
1578 ThrowException("Can't store '" + $2->getType()->getDescription() +
1579 "' into space of type '" + ElTy->getDescription() + "'!");
1580 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1581 delete $4; delete $6;
1583 | GETELEMENTPTR Types ValueRef IndexList {
1584 if (!(*$2)->isPointerType())
1585 ThrowException("getelementptr insn requires pointer operand!");
1586 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1587 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1588 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1589 delete $2; delete $4;
1593 int yyerror(const char *ErrorMsg) {
1594 ThrowException(string("Parse error: ") + ErrorMsg);