1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
3 // This file implements the bison parser for LLVM assembly languages files.
5 //===------------------------------------------------------------------------=//
8 // TODO: Parse comments and add them to an internal node... so that they may
9 // be saved in the bytecode format as well as everything else. Very important
10 // for a general IR format.
14 #include "ParserInternals.h"
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Method.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Assembly/Parser.h"
22 #include "llvm/ConstantPool.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iMemory.h"
26 #include <utility> // Get definition of pair class
27 #include <algorithm> // Get definition of find_if
28 #include <stdio.h> // This embarasment is due to our flex lexer...
30 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
31 int yylex(); // declaration" of xxx warnings.
34 static Module *ParserResult;
37 // This contains info used when building the body of a method. It is destroyed
38 // when the method is completed.
40 typedef vector<Value *> ValueList; // Numbered defs
41 static void ResolveDefinitions(vector<ValueList> &LateResolvers);
43 static struct PerModuleInfo {
44 Module *CurrentModule;
45 vector<ValueList> Values; // Module level numbered definitions
46 vector<ValueList> LateResolveValues;
49 // If we could not resolve some blocks at parsing time (forward branches)
50 // resolve the branches now...
51 ResolveDefinitions(LateResolveValues);
53 Values.clear(); // Clear out method local definitions
58 static struct PerMethodInfo {
59 Method *CurrentMethod; // Pointer to current method being created
61 vector<ValueList> Values; // Keep track of numbered definitions
62 vector<ValueList> LateResolveValues;
63 bool isDeclare; // Is this method a forward declararation?
65 inline PerMethodInfo() {
70 inline ~PerMethodInfo() {}
72 inline void MethodStart(Method *M) {
77 // If we could not resolve some blocks at parsing time (forward branches)
78 // resolve the branches now...
79 ResolveDefinitions(LateResolveValues);
81 Values.clear(); // Clear out method local definitions
85 } CurMeth; // Info for the current method...
88 //===----------------------------------------------------------------------===//
89 // Code to handle definitions of all the types
90 //===----------------------------------------------------------------------===//
92 static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
93 if (!D->hasName()) { // Is this a numbered definition?
94 unsigned type = D->getType()->getUniqueID();
95 if (ValueTab.size() <= type)
96 ValueTab.resize(type+1, ValueList());
97 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
98 ValueTab[type].push_back(D);
102 static Value *getVal(const Type *Type, ValID &D,
103 bool DoNotImprovise = false) {
105 case 0: { // Is it a numbered definition?
106 unsigned type = Type->getUniqueID();
107 unsigned Num = (unsigned)D.Num;
109 // Module constants occupy the lowest numbered slots...
110 if (type < CurModule.Values.size()) {
111 if (Num < CurModule.Values[type].size())
112 return CurModule.Values[type][Num];
114 Num -= CurModule.Values[type].size();
117 // Make sure that our type is within bounds
118 if (CurMeth.Values.size() <= type)
121 // Check that the number is within bounds...
122 if (CurMeth.Values[type].size() <= Num)
125 return CurMeth.Values[type][Num];
127 case 1: { // Is it a named definition?
129 SymbolTable *SymTab = 0;
130 if (CurMeth.CurrentMethod)
131 SymTab = CurMeth.CurrentMethod->getSymbolTable();
132 Value *N = SymTab ? SymTab->lookup(Type, Name) : 0;
135 SymTab = CurModule.CurrentModule->getSymbolTable();
137 N = SymTab->lookup(Type, Name);
141 D.destroy(); // Free old strdup'd memory...
145 case 2: // Is it a constant pool reference??
146 case 3: // Is it an unsigned const pool reference?
147 case 4: // Is it a string const pool reference?
148 case 5:{ // Is it a floating point const pool reference?
149 ConstPoolVal *CPV = 0;
151 // Check to make sure that "Type" is an integral type, and that our
152 // value will fit into the specified type...
155 if (Type == Type::BoolTy) { // Special handling for boolean data
156 CPV = new ConstPoolBool(D.ConstPool64 != 0);
158 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64))
159 ThrowException("Symbolic constant pool value '" +
160 itostr(D.ConstPool64) + "' is invalid for type '" +
161 Type->getName() + "'!");
162 CPV = new ConstPoolSInt(Type, D.ConstPool64);
166 if (!ConstPoolUInt::isValueValidForType(Type, D.UConstPool64)) {
167 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64)) {
168 ThrowException("Integral constant pool reference is invalid!");
169 } else { // This is really a signed reference. Transmogrify.
170 CPV = new ConstPoolSInt(Type, D.ConstPool64);
173 CPV = new ConstPoolUInt(Type, D.UConstPool64);
177 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
179 //CPV = new ConstPoolString(D.Name);
180 D.destroy(); // Free the string memory
183 if (!ConstPoolFP::isValueValidForType(Type, D.ConstPoolFP))
184 ThrowException("FP constant invalid for type!!");
186 CPV = new ConstPoolFP(Type, D.ConstPoolFP);
189 assert(CPV && "How did we escape creating a constant??");
191 // Scan through the constant table and see if we already have loaded this
194 ConstantPool &CP = CurMeth.CurrentMethod ?
195 CurMeth.CurrentMethod->getConstantPool() :
196 CurModule.CurrentModule->getConstantPool();
197 ConstPoolVal *C = CP.find(CPV); // Already have this constant?
199 delete CPV; // Didn't need this after all, oh well.
200 return C; // Yup, we already have one, recycle it!
204 // Success, everything is kosher. Lets go!
206 } // End of case 2,3,4
210 // If we reached here, we referenced either a symbol that we don't know about
211 // or an id number that hasn't been read yet. We may be referencing something
212 // forward, so just create an entry to be resolved later and get to it...
214 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
216 // TODO: Attempt to coallecse nodes that are the same with previous ones.
218 switch (Type->getPrimitiveID()) {
219 case Type::LabelTyID: d = new BBPlaceHolder(Type, D); break;
220 case Type::MethodTyID:
221 d = new MethPlaceHolder(Type, D);
222 InsertValue(d, CurModule.LateResolveValues);
224 //case Type::ClassTyID: d = new ClassPlaceHolder(Type, D); break;
225 default: d = new DefPlaceHolder(Type, D); break;
228 assert(d != 0 && "How did we not make something?");
229 InsertValue(d, CurMeth.LateResolveValues);
234 //===----------------------------------------------------------------------===//
235 // Code to handle forward references in instructions
236 //===----------------------------------------------------------------------===//
238 // This code handles the late binding needed with statements that reference
239 // values not defined yet... for example, a forward branch, or the PHI node for
242 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
243 // and back patchs after we are done.
246 // ResolveDefinitions - If we could not resolve some defs at parsing
247 // time (forward branches, phi functions for loops, etc...) resolve the
250 static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
251 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
252 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
253 while (!LateResolvers[ty].empty()) {
254 Value *V = LateResolvers[ty].back();
255 LateResolvers[ty].pop_back();
256 ValID &DID = getValIDFromPlaceHolder(V);
258 Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
260 if (TheRealValue == 0 && DID.Type == 1)
261 ThrowException("Reference to an invalid definition: '" +DID.getName() +
262 "' of type '" + V->getType()->getName() + "'");
263 else if (TheRealValue == 0)
264 ThrowException("Reference to an invalid definition: #" +itostr(DID.Num)+
265 " of type '" + V->getType()->getName() + "'");
267 V->replaceAllUsesWith(TheRealValue);
268 assert(V->use_empty());
273 LateResolvers.clear();
276 // addConstValToConstantPool - This code is used to insert a constant into the
277 // current constant pool. This is designed to make maximal (but not more than
278 // possible) reuse (merging) of constants in the constant pool. This means that
279 // multiple references to %4, for example will all get merged.
281 static ConstPoolVal *addConstValToConstantPool(ConstPoolVal *C) {
282 vector<ValueList> &ValTab = CurMeth.CurrentMethod ?
283 CurMeth.Values : CurModule.Values;
284 ConstantPool &CP = CurMeth.CurrentMethod ?
285 CurMeth.CurrentMethod->getConstantPool() :
286 CurModule.CurrentModule->getConstantPool();
288 if (ConstPoolVal *CPV = CP.find(C)) {
289 // Constant already in constant pool. Try to merge the two constants
290 if (CPV->hasName() && !C->hasName()) {
291 // Merge the two values, we inherit the existing CPV's name.
292 // InsertValue requires that the value have no name to insert correctly
293 // (because we want to fill the slot this constant would have filled)
295 string Name = CPV->getName();
297 InsertValue(CPV, ValTab);
301 } else if (!CPV->hasName() && C->hasName()) {
302 // If we have a name on this value and there isn't one in the const
303 // pool val already, propogate it.
305 CPV->setName(C->getName());
306 delete C; // Sorry, you're toast
308 } else if (CPV->hasName() && C->hasName()) {
309 // Both values have distinct names. We cannot merge them.
311 InsertValue(C, ValTab);
313 } else if (!CPV->hasName() && !C->hasName()) {
314 // Neither value has a name, trivially merge them.
315 InsertValue(CPV, ValTab);
320 assert(0 && "Not reached!");
322 } else { // No duplication of value.
324 InsertValue(C, ValTab);
332 inline EqualsType(const Type *t) { T = t; }
333 inline bool operator()(const ConstPoolVal *CPV) const {
334 return static_cast<const ConstPoolType*>(CPV)->getValue() == T;
339 // checkNewType - We have to be careful to add all types referenced by the
340 // program to the constant pool of the method or module. Because of this, we
341 // often want to check to make sure that types used are in the constant pool,
342 // and add them if they aren't. That's what this function does.
344 static const Type *checkNewType(const Type *Ty) {
345 ConstantPool &CP = CurMeth.CurrentMethod ?
346 CurMeth.CurrentMethod->getConstantPool() :
347 CurModule.CurrentModule->getConstantPool();
349 // TODO: This should use ConstantPool::ensureTypeAvailable
351 // Get the type type plane...
352 ConstantPool::PlaneType &P = CP.getPlane(Type::TypeTy);
353 ConstantPool::PlaneType::const_iterator PI = find_if(P.begin(), P.end(),
356 vector<ValueList> &ValTab = CurMeth.CurrentMethod ?
357 CurMeth.Values : CurModule.Values;
358 ConstPoolVal *CPT = new ConstPoolType(Ty);
360 InsertValue(CPT, ValTab);
366 //===----------------------------------------------------------------------===//
367 // RunVMAsmParser - Define an interface to this parser
368 //===----------------------------------------------------------------------===//
370 Module *RunVMAsmParser(const string &Filename, FILE *F) {
372 CurFilename = Filename;
373 llvmAsmlineno = 1; // Reset the current line number...
375 CurModule.CurrentModule = new Module(); // Allocate a new module to read
376 yyparse(); // Parse the file.
377 Module *Result = ParserResult;
378 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
389 MethodArgument *MethArgVal;
390 BasicBlock *BasicBlockVal;
391 TerminatorInst *TermInstVal;
392 Instruction *InstVal;
393 ConstPoolVal *ConstVal;
396 list<MethodArgument*> *MethodArgList;
397 list<Value*> *ValueList;
398 list<const Type*> *TypeList;
399 list<pair<Value*, BasicBlock*> > *PHIList; // Represent the RHS of PHI node
400 list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
401 vector<ConstPoolVal*> *ConstVector;
409 char *StrVal; // This memory is allocated by strdup!
410 ValID ValIDVal; // May contain memory allocated by strdup
412 Instruction::UnaryOps UnaryOpVal;
413 Instruction::BinaryOps BinaryOpVal;
414 Instruction::TermOps TermOpVal;
415 Instruction::MemoryOps MemOpVal;
416 Instruction::OtherOps OtherOpVal;
419 %type <ModuleVal> Module MethodList
420 %type <MethodVal> Method MethodProto MethodHeader BasicBlockList
421 %type <BasicBlockVal> BasicBlock InstructionList
422 %type <TermInstVal> BBTerminatorInst
423 %type <InstVal> Inst InstVal MemoryInst
424 %type <ConstVal> ConstVal
425 %type <ConstVector> ConstVector UByteList
426 %type <MethodArgList> ArgList ArgListH
427 %type <MethArgVal> ArgVal
428 %type <PHIList> PHIList
429 %type <ValueList> ValueRefList ValueRefListE // For call param lists
430 %type <TypeList> TypeList
431 %type <JumpTable> JumpTable
433 %type <ValIDVal> ValueRef ConstValueRef // Reference to a definition or BB
435 // Tokens and types for handling constant integer values
437 // ESINT64VAL - A negative number within long long range
438 %token <SInt64Val> ESINT64VAL
440 // EUINT64VAL - A positive number within uns. long long range
441 %token <UInt64Val> EUINT64VAL
442 %type <SInt64Val> EINT64VAL
444 %token <SIntVal> SINTVAL // Signed 32 bit ints...
445 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
446 %type <SIntVal> INTVAL
447 %token <FPVal> FPVAL // Float or Double constant
450 %type <TypeVal> Types TypesV SIntType UIntType IntType FPType
451 %token <TypeVal> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
452 %token <TypeVal> FLOAT DOUBLE STRING TYPE LABEL
454 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
455 %type <StrVal> OptVAR_ID OptAssign
458 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE TO
460 // Basic Block Terminating Operators
461 %token <TermOpVal> RET BR SWITCH
464 %type <UnaryOpVal> UnaryOps // all the unary operators
465 %token <UnaryOpVal> NOT
468 %type <BinaryOpVal> BinaryOps // all the binary operators
469 %token <BinaryOpVal> ADD SUB MUL DIV REM
470 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
472 // Memory Instructions
473 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
476 %type <OtherOpVal> ShiftOps
477 %token <OtherOpVal> PHI CALL CAST SHL SHR
482 // Handle constant integer size restriction and conversion...
487 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
488 ThrowException("Value too large for type!");
493 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
494 EINT64VAL : EUINT64VAL {
495 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
496 ThrowException("Value too large for type!");
500 // Types includes all predefined types... except void, because you can't do
501 // anything with it except for certain specific things...
503 // User defined types are added later...
505 Types : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
506 Types : LONG | ULONG | FLOAT | DOUBLE | STRING | TYPE | LABEL
508 // TypesV includes all of 'Types', but it also includes the void type.
509 TypesV : Types | VOID
511 // Operations that are notably excluded from this list include:
512 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
515 BinaryOps : ADD | SUB | MUL | DIV | REM
516 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
519 // These are some types that allow classification if we only want a particular
520 // thing... for example, only a signed, unsigned, or integral type.
521 SIntType : LONG | INT | SHORT | SBYTE
522 UIntType : ULONG | UINT | USHORT | UBYTE
523 IntType : SIntType | UIntType
524 FPType : FLOAT | DOUBLE
526 // OptAssign - Value producing statements have an optional assignment component
527 OptAssign : VAR_ID '=' {
534 // ConstVal - The various declarations that go into the constant pool. This
535 // includes all forward declarations of types, constants, and functions.
537 ConstVal : SIntType EINT64VAL { // integral constants
538 if (!ConstPoolSInt::isValueValidForType($1, $2))
539 ThrowException("Constant value doesn't fit in type!");
540 $$ = new ConstPoolSInt($1, $2);
542 | UIntType EUINT64VAL { // integral constants
543 if (!ConstPoolUInt::isValueValidForType($1, $2))
544 ThrowException("Constant value doesn't fit in type!");
545 $$ = new ConstPoolUInt($1, $2);
547 | BOOL TRUE { // Boolean constants
548 $$ = new ConstPoolBool(true);
550 | BOOL FALSE { // Boolean constants
551 $$ = new ConstPoolBool(false);
553 | FPType FPVAL { // Float & Double constants
554 $$ = new ConstPoolFP($1, $2);
556 | STRING STRINGCONSTANT { // String constants
557 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
559 //$$ = new ConstPoolString($2);
562 | TYPE Types { // Type constants
563 $$ = new ConstPoolType($2);
565 | '[' Types ']' '[' ConstVector ']' { // Nonempty array constant
566 // Verify all elements are correct type!
567 const ArrayType *AT = ArrayType::getArrayType($2);
568 for (unsigned i = 0; i < $5->size(); i++) {
569 if ($2 != (*$5)[i]->getType())
570 ThrowException("Element #" + utostr(i) + " is not of type '" +
571 $2->getName() + "' as required!\nIt is of type '" +
572 (*$5)[i]->getType()->getName() + "'.");
575 $$ = new ConstPoolArray(AT, *$5);
578 | '[' Types ']' '[' ']' { // Empty array constant
579 vector<ConstPoolVal*> Empty;
580 $$ = new ConstPoolArray(ArrayType::getArrayType($2), Empty);
582 | '[' EUINT64VAL 'x' Types ']' '[' ConstVector ']' {
583 // Verify all elements are correct type!
584 const ArrayType *AT = ArrayType::getArrayType($4, (int)$2);
585 if ($2 != $7->size())
586 ThrowException("Type mismatch: constant sized array initialized with " +
587 utostr($7->size()) + " arguments, but has size of " +
588 itostr((int)$2) + "!");
590 for (unsigned i = 0; i < $7->size(); i++) {
591 if ($4 != (*$7)[i]->getType())
592 ThrowException("Element #" + utostr(i) + " is not of type '" +
593 $4->getName() + "' as required!\nIt is of type '" +
594 (*$7)[i]->getType()->getName() + "'.");
597 $$ = new ConstPoolArray(AT, *$7);
600 | '[' EUINT64VAL 'x' Types ']' '[' ']' {
602 ThrowException("Type mismatch: constant sized array initialized with 0"
603 " arguments, but has size of " + itostr((int)$2) + "!");
604 vector<ConstPoolVal*> Empty;
605 $$ = new ConstPoolArray(ArrayType::getArrayType($4, 0), Empty);
607 | '{' TypeList '}' '{' ConstVector '}' {
608 StructType::ElementTypes Types($2->begin(), $2->end());
611 const StructType *St = StructType::getStructType(Types);
612 $$ = new ConstPoolStruct(St, *$5);
616 const StructType *St =
617 StructType::getStructType(StructType::ElementTypes());
618 vector<ConstPoolVal*> Empty;
619 $$ = new ConstPoolStruct(St, Empty);
622 | Types '*' ConstVal {
628 // ConstVector - A list of comma seperated constants.
629 ConstVector : ConstVector ',' ConstVal {
630 ($$ = $1)->push_back(addConstValToConstantPool($3));
633 $$ = new vector<ConstPoolVal*>();
634 $$->push_back(addConstValToConstantPool($1));
637 //ExternMethodDecl : EXTERNAL TypesV '(' TypeList ')' {
641 // ConstPool - Constants with optional names assigned to them.
642 ConstPool : ConstPool OptAssign ConstVal {
648 addConstValToConstantPool($3);
651 | ConstPool OptAssign GlobalDecl { // Global declarations appear in CP
656 //CurModule.CurrentModule->
659 | /* empty: end of list */ {
663 //===----------------------------------------------------------------------===//
664 // Rules to match Modules
665 //===----------------------------------------------------------------------===//
667 // Module rule: Capture the result of parsing the whole file into a result
670 Module : MethodList {
671 $$ = ParserResult = $1;
672 CurModule.ModuleDone();
675 // MethodList - A list of methods, preceeded by a constant pool.
677 MethodList : MethodList Method {
679 if (!$2->getParent())
680 $1->getMethodList().push_back($2);
681 CurMeth.MethodDone();
683 | MethodList MethodProto {
685 if (!$2->getParent())
686 $1->getMethodList().push_back($2);
687 CurMeth.MethodDone();
689 | ConstPool IMPLEMENTATION {
690 $$ = CurModule.CurrentModule;
694 //===----------------------------------------------------------------------===//
695 // Rules to match Method Headers
696 //===----------------------------------------------------------------------===//
698 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
700 ArgVal : Types OptVAR_ID {
701 $$ = new MethodArgument($1);
702 if ($2) { // Was the argument named?
704 free($2); // The string was strdup'd, so free it now.
708 ArgListH : ArgVal ',' ArgListH {
713 $$ = new list<MethodArgument*>();
724 MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
725 MethodType::ParamTypes ParamTypeList;
727 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
728 ParamTypeList.push_back((*I)->getType());
730 const MethodType *MT = MethodType::getMethodType($1, ParamTypeList);
733 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
734 if (Value *V = ST->lookup(MT, $2)) { // Method already in symtab?
735 M = V->castMethodAsserting();
737 // Yes it is. If this is the case, either we need to be a forward decl,
738 // or it needs to be.
739 if (!CurMeth.isDeclare && !M->isExternal())
740 ThrowException("Redefinition of method '" + string($2) + "'!");
744 if (M == 0) { // Not already defined?
745 M = new Method(MT, $2);
746 InsertValue(M, CurModule.Values);
749 free($2); // Free strdup'd memory!
751 CurMeth.MethodStart(M);
753 // Add all of the arguments we parsed to the method...
754 if ($4 && !CurMeth.isDeclare) { // Is null if empty...
755 Method::ArgumentListType &ArgList = M->getArgumentList();
757 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
759 ArgList.push_back(*I);
761 delete $4; // We're now done with the argument list
765 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
766 $$ = CurMeth.CurrentMethod;
769 Method : BasicBlockList END {
773 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
774 $$ = CurMeth.CurrentMethod;
777 //===----------------------------------------------------------------------===//
778 // Rules to match Basic Blocks
779 //===----------------------------------------------------------------------===//
781 ConstValueRef : ESINT64VAL { // A reference to a direct constant
782 $$ = ValID::create($1);
785 $$ = ValID::create($1);
787 | FPVAL { // Perhaps it's an FP constant?
788 $$ = ValID::create($1);
791 $$ = ValID::create((int64_t)1);
794 $$ = ValID::create((int64_t)0);
796 | STRINGCONSTANT { // Quoted strings work too... especially for methods
797 $$ = ValID::create_conststr($1);
800 // ValueRef - A reference to a definition...
801 ValueRef : INTVAL { // Is it an integer reference...?
802 $$ = ValID::create($1);
804 | VAR_ID { // Is it a named reference...?
805 $$ = ValID::create($1);
811 // The user may refer to a user defined type by its typeplane... check for this
815 Value *D = getVal(Type::TypeTy, $1, true);
816 if (D == 0) ThrowException("Invalid user defined type: " + $1.getName());
818 // User defined type not in const pool!
819 ConstPoolType *CPT = (ConstPoolType*)D->castConstantAsserting();
820 $$ = CPT->getValue();
822 | TypesV '(' TypeList ')' { // Method derived type?
823 MethodType::ParamTypes Params($3->begin(), $3->end());
825 $$ = checkNewType(MethodType::getMethodType($1, Params));
827 | TypesV '(' ')' { // Method derived type?
828 MethodType::ParamTypes Params; // Empty list
829 $$ = checkNewType(MethodType::getMethodType($1, Params));
832 $$ = checkNewType(ArrayType::getArrayType($2));
834 | '[' EUINT64VAL 'x' Types ']' {
835 $$ = checkNewType(ArrayType::getArrayType($4, (int)$2));
838 StructType::ElementTypes Elements($2->begin(), $2->end());
840 $$ = checkNewType(StructType::getStructType(Elements));
843 $$ = checkNewType(StructType::getStructType(StructType::ElementTypes()));
846 $$ = checkNewType(PointerType::getPointerType($1));
851 $$ = new list<const Type*>();
854 | TypeList ',' Types {
855 ($$=$1)->push_back($3);
859 BasicBlockList : BasicBlockList BasicBlock {
860 $1->getBasicBlocks().push_back($2);
863 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
864 $$ = $1; // in them...
865 $1->getBasicBlocks().push_back($2);
869 // Basic blocks are terminated by branching instructions:
870 // br, br/cc, switch, ret
872 BasicBlock : InstructionList BBTerminatorInst {
873 $1->getInstList().push_back($2);
877 | LABELSTR InstructionList BBTerminatorInst {
878 $2->getInstList().push_back($3);
880 free($1); // Free the strdup'd memory...
886 InstructionList : InstructionList Inst {
887 $1->getInstList().push_back($2);
891 $$ = new BasicBlock();
894 BBTerminatorInst : RET Types ValueRef { // Return with a result...
895 $$ = new ReturnInst(getVal($2, $3));
897 | RET VOID { // Return with no result...
898 $$ = new ReturnInst();
900 | BR LABEL ValueRef { // Unconditional Branch...
901 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $3));
902 } // Conditional Branch...
903 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
904 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $6),
905 (BasicBlock*)getVal(Type::LabelTy, $9),
906 getVal(Type::BoolTy, $3));
908 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
909 SwitchInst *S = new SwitchInst(getVal($2, $3),
910 (BasicBlock*)getVal(Type::LabelTy, $6));
913 list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(),
915 for (; I != end; ++I)
916 S->dest_push_back(I->first, I->second);
919 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
921 ConstPoolVal *V = (ConstPoolVal*)getVal($2, $3, true);
923 ThrowException("May only switch on a constant pool value!");
925 $$->push_back(make_pair(V, (BasicBlock*)getVal($5, $6)));
927 | IntType ConstValueRef ',' LABEL ValueRef {
928 $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
929 ConstPoolVal *V = (ConstPoolVal*)getVal($1, $2, true);
932 ThrowException("May only switch on a constant pool value!");
934 $$->push_back(make_pair(V, (BasicBlock*)getVal($4, $5)));
937 Inst : OptAssign InstVal {
938 if ($1) // Is this definition named??
939 $2->setName($1); // if so, assign the name...
945 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
946 $$ = new list<pair<Value*, BasicBlock*> >();
947 $$->push_back(make_pair(getVal($1, $3),
948 (BasicBlock*)getVal(Type::LabelTy, $5)));
950 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
952 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
953 (BasicBlock*)getVal(Type::LabelTy, $6)));
957 ValueRefList : Types ValueRef { // Used for call statements...
958 $$ = new list<Value*>();
959 $$->push_back(getVal($1, $2));
961 | ValueRefList ',' Types ValueRef {
963 $1->push_back(getVal($3, $4));
966 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
967 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
969 InstVal : BinaryOps Types ValueRef ',' ValueRef {
970 $$ = BinaryOperator::create($1, getVal($2, $3), getVal($2, $5));
972 ThrowException("binary operator returned null!");
974 | UnaryOps Types ValueRef {
975 $$ = UnaryOperator::create($1, getVal($2, $3));
977 ThrowException("unary operator returned null!");
979 | ShiftOps Types ValueRef ',' Types ValueRef {
980 if ($5 != Type::UByteTy) ThrowException("Shift amount must be ubyte!");
981 $$ = new ShiftInst($1, getVal($2, $3), getVal($5, $6));
983 | CAST Types ValueRef TO Types {
984 $$ = new CastInst(getVal($2, $3), $5);
987 const Type *Ty = $2->front().first->getType();
988 $$ = new PHINode(Ty);
989 while ($2->begin() != $2->end()) {
990 if ($2->front().first->getType() != Ty)
991 ThrowException("All elements of a PHI node must be of the same type!");
992 ((PHINode*)$$)->addIncoming($2->front().first, $2->front().second);
995 delete $2; // Free the list...
997 | CALL Types ValueRef '(' ValueRefListE ')' {
998 if (!$2->isMethodType())
999 ThrowException("Can only call methods: invalid type '" +
1000 $2->getName() + "'!");
1002 const MethodType *Ty = (const MethodType*)$2;
1004 Value *V = getVal(Ty, $3);
1005 if (!V->isMethod() || V->getType() != Ty)
1006 ThrowException("Cannot call: " + $3.getName() + "!");
1008 // Create or access a new type that corresponds to the function call...
1009 vector<Value *> Params;
1012 // Pull out just the arguments...
1013 Params.insert(Params.begin(), $5->begin(), $5->end());
1016 // Loop through MethodType's arguments and ensure they are specified
1019 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1021 for (i = 0; i < Params.size() && I != Ty->getParamTypes().end(); ++i,++I){
1022 if (Params[i]->getType() != *I)
1023 ThrowException("Parameter " + utostr(i) + " is not of type '" +
1024 (*I)->getName() + "'!");
1027 if (i != Params.size() || I != Ty->getParamTypes().end())
1028 ThrowException("Invalid number of parameters detected!");
1031 // Create the call node...
1032 $$ = new CallInst((Method*)V, Params);
1038 // UByteList - List of ubyte values for load and store instructions
1039 UByteList : ',' ConstVector {
1042 $$ = new vector<ConstPoolVal*>();
1045 MemoryInst : MALLOC Types {
1046 $$ = new MallocInst(checkNewType(PointerType::getPointerType($2)));
1048 | MALLOC Types ',' UINT ValueRef {
1049 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
1050 ThrowException("Trying to allocate " + $2->getName() +
1051 " as unsized array!");
1052 const Type *Ty = checkNewType(PointerType::getPointerType($2));
1053 $$ = new MallocInst(Ty, getVal($4, $5));
1056 $$ = new AllocaInst(checkNewType(PointerType::getPointerType($2)));
1058 | ALLOCA Types ',' UINT ValueRef {
1059 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
1060 ThrowException("Trying to allocate " + $2->getName() +
1061 " as unsized array!");
1062 const Type *Ty = checkNewType(PointerType::getPointerType($2));
1063 Value *ArrSize = getVal($4, $5);
1064 $$ = new AllocaInst(Ty, ArrSize);
1066 | FREE Types ValueRef {
1067 if (!$2->isPointerType())
1068 ThrowException("Trying to free nonpointer type " + $2->getName() + "!");
1069 $$ = new FreeInst(getVal($2, $3));
1072 | LOAD Types ValueRef UByteList {
1073 if (!$2->isPointerType())
1074 ThrowException("Can't load from nonpointer type: " + $2->getName());
1075 if (LoadInst::getIndexedType($2, *$4) == 0)
1076 ThrowException("Invalid indices for load instruction!");
1078 $$ = new LoadInst(getVal($2, $3), *$4);
1079 delete $4; // Free the vector...
1081 | STORE Types ValueRef ',' Types ValueRef UByteList {
1082 if (!$5->isPointerType())
1083 ThrowException("Can't store to a nonpointer type: " + $5->getName());
1084 const Type *ElTy = StoreInst::getIndexedType($5, *$7);
1086 ThrowException("Can't store into that field list!");
1088 ThrowException("Can't store '" + $2->getName() + "' into space of type '"+
1089 ElTy->getName() + "'!");
1090 $$ = new StoreInst(getVal($2, $3), getVal($5, $6), *$7);
1093 | GETELEMENTPTR Types ValueRef UByteList {
1094 if (!$2->isPointerType())
1095 ThrowException("getelementptr insn requires pointer operand!");
1096 if (!GetElementPtrInst::getIndexedType($2, *$4, true))
1097 ThrowException("Can't get element ptr '" + $2->getName() + "'!");
1098 $$ = new GetElementPtrInst(getVal($2, $3), *$4);
1100 checkNewType($$->getType());
1104 int yyerror(const char *ErrorMsg) {
1105 ThrowException(string("Parse error: ") + ErrorMsg);