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/Assembly/Parser.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Method.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/iMemory.h"
24 #include "llvm/Support/STLExtras.h"
25 #include "llvm/Support/DepthFirstIterator.h"
27 #include <utility> // Get definition of pair class
29 #include <stdio.h> // This embarasment is due to our flex lexer...
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 static void ResolveTypes (vector<PATypeHolder<Type> > &LateResolveTypes);
55 static struct PerModuleInfo {
56 Module *CurrentModule;
57 vector<ValueList> Values; // Module level numbered definitions
58 vector<ValueList> LateResolveValues;
59 vector<PATypeHolder<Type> > Types, LateResolveTypes;
62 // If we could not resolve some methods at method compilation time (calls to
63 // methods before they are defined), resolve them now... Types are resolved
64 // when the constant pool has been completely parsed.
66 ResolveDefinitions(LateResolveValues);
68 Values.clear(); // Clear out method local definitions
74 static struct PerMethodInfo {
75 Method *CurrentMethod; // Pointer to current method being created
77 vector<ValueList> Values; // Keep track of numbered definitions
78 vector<ValueList> LateResolveValues;
79 vector<PATypeHolder<Type> > Types, LateResolveTypes;
80 bool isDeclare; // Is this method a forward declararation?
82 inline PerMethodInfo() {
87 inline ~PerMethodInfo() {}
89 inline void MethodStart(Method *M) {
94 // If we could not resolve some blocks at parsing time (forward branches)
95 // resolve the branches now...
96 ResolveDefinitions(LateResolveValues);
98 Values.clear(); // Clear out method local definitions
103 } CurMeth; // Info for the current method...
106 //===----------------------------------------------------------------------===//
107 // Code to handle definitions of all the types
108 //===----------------------------------------------------------------------===//
110 static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values){
111 if (!D->hasName()) { // Is this a numbered definition?
112 unsigned type = D->getType()->getUniqueID();
113 if (ValueTab.size() <= type)
114 ValueTab.resize(type+1, ValueList());
115 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
116 ValueTab[type].push_back(D);
120 // TODO: FIXME when Type are not const
121 static void InsertType(const Type *Ty, vector<PATypeHolder<Type> > &Types) {
125 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
127 case 0: { // Is it a numbered definition?
128 unsigned Num = (unsigned)D.Num;
130 // Module constants occupy the lowest numbered slots...
131 if (Num < CurModule.Types.size())
132 return CurModule.Types[Num];
134 Num -= CurModule.Types.size();
136 // Check that the number is within bounds...
137 if (Num <= CurMeth.Types.size())
138 return CurMeth.Types[Num];
140 case 1: { // Is it a named definition?
142 SymbolTable *SymTab = 0;
143 if (CurMeth.CurrentMethod)
144 SymTab = CurMeth.CurrentMethod->getSymbolTable();
145 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
148 // Symbol table doesn't automatically chain yet... because the method
149 // hasn't been added to the module...
151 SymTab = CurModule.CurrentModule->getSymbolTable();
153 N = SymTab->lookup(Type::TypeTy, Name);
157 D.destroy(); // Free old strdup'd memory...
158 return N->castTypeAsserting();
161 ThrowException("Invalid symbol type reference!");
164 // If we reached here, we referenced either a symbol that we don't know about
165 // or an id number that hasn't been read yet. We may be referencing something
166 // forward, so just create an entry to be resolved later and get to it...
168 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
170 vector<PATypeHolder<Type> > *LateResolver = CurMeth.CurrentMethod ?
171 &CurMeth.LateResolveTypes : &CurModule.LateResolveTypes;
173 Type *Typ = new TypePlaceHolder(Type::TypeTy, D);
174 InsertType(Typ, *LateResolver);
178 static Value *getVal(const Type *Ty, const ValID &D,
179 bool DoNotImprovise = false) {
180 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
183 case 0: { // Is it a numbered definition?
184 unsigned type = Ty->getUniqueID();
185 unsigned Num = (unsigned)D.Num;
187 // Module constants occupy the lowest numbered slots...
188 if (type < CurModule.Values.size()) {
189 if (Num < CurModule.Values[type].size())
190 return CurModule.Values[type][Num];
192 Num -= CurModule.Values[type].size();
195 // Make sure that our type is within bounds
196 if (CurMeth.Values.size() <= type)
199 // Check that the number is within bounds...
200 if (CurMeth.Values[type].size() <= Num)
203 return CurMeth.Values[type][Num];
205 case 1: { // Is it a named definition?
207 SymbolTable *SymTab = 0;
208 if (CurMeth.CurrentMethod)
209 SymTab = CurMeth.CurrentMethod->getSymbolTable();
210 Value *N = SymTab ? SymTab->lookup(Ty, 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(Ty, Name);
222 D.destroy(); // Free old strdup'd memory...
226 case 2: // Is it a constant pool reference??
227 case 3: // Is it an unsigned const pool reference?
228 case 4: // Is it a string const pool reference?
229 case 5:{ // Is it a floating point const pool reference?
230 ConstPoolVal *CPV = 0;
232 // Check to make sure that "Ty" is an integral type, and that our
233 // value will fit into the specified type...
236 if (Ty == Type::BoolTy) { // Special handling for boolean data
237 CPV = ConstPoolBool::get(D.ConstPool64 != 0);
239 if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64))
240 ThrowException("Symbolic constant pool value '" +
241 itostr(D.ConstPool64) + "' is invalid for type '" +
242 Ty->getName() + "'!");
243 CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
247 if (!ConstPoolUInt::isValueValidForType(Ty, D.UConstPool64)) {
248 if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64)) {
249 ThrowException("Integral constant pool reference is invalid!");
250 } else { // This is really a signed reference. Transmogrify.
251 CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
254 CPV = ConstPoolUInt::get(Ty, D.UConstPool64);
258 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
262 if (!ConstPoolFP::isValueValidForType(Ty, D.ConstPoolFP))
263 ThrowException("FP constant invalid for type!!");
265 CPV = ConstPoolFP::get(Ty, D.ConstPoolFP);
268 assert(CPV && "How did we escape creating a constant??");
270 } // End of case 2,3,4
272 assert(0 && "Unhandled case!");
276 // If we reached here, we referenced either a symbol that we don't know about
277 // or an id number that hasn't been read yet. We may be referencing something
278 // forward, so just create an entry to be resolved later and get to it...
280 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
283 vector<ValueList> *LateResolver = (CurMeth.CurrentMethod) ?
284 &CurMeth.LateResolveValues : &CurModule.LateResolveValues;
286 switch (Ty->getPrimitiveID()) {
287 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
288 case Type::MethodTyID: d = new MethPlaceHolder(Ty, D);
289 LateResolver = &CurModule.LateResolveValues; break;
290 default: d = new ValuePlaceHolder(Ty, D); break;
293 assert(d != 0 && "How did we not make something?");
294 InsertValue(d, *LateResolver);
299 //===----------------------------------------------------------------------===//
300 // Code to handle forward references in instructions
301 //===----------------------------------------------------------------------===//
303 // This code handles the late binding needed with statements that reference
304 // values not defined yet... for example, a forward branch, or the PHI node for
307 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
308 // and back patchs after we are done.
311 // ResolveDefinitions - If we could not resolve some defs at parsing
312 // time (forward branches, phi functions for loops, etc...) resolve the
315 static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
316 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
317 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
318 while (!LateResolvers[ty].empty()) {
319 Value *V = LateResolvers[ty].back();
320 LateResolvers[ty].pop_back();
321 ValID &DID = getValIDFromPlaceHolder(V);
323 Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
325 if (TheRealValue == 0) {
327 ThrowException("Reference to an invalid definition: '" +DID.getName()+
328 "' of type '" + V->getType()->getDescription() + "'",
329 getLineNumFromPlaceHolder(V));
331 ThrowException("Reference to an invalid definition: #" +
332 itostr(DID.Num) + " of type '" +
333 V->getType()->getDescription() + "'",
334 getLineNumFromPlaceHolder(V));
337 assert(!V->isType() && "Types should be in LateResolveTypes!");
339 V->replaceAllUsesWith(TheRealValue);
344 LateResolvers.clear();
348 // ResolveTypes - This goes through the forward referenced type table and makes
349 // sure that all type references are complete. This code is executed after the
350 // constant pool of a method or module is completely parsed.
352 static void ResolveTypes(vector<PATypeHolder<Type> > &LateResolveTypes) {
353 while (!LateResolveTypes.empty()) {
354 const Type *Ty = LateResolveTypes.back();
355 ValID &DID = getValIDFromPlaceHolder(Ty);
357 const Type *TheRealType = getTypeVal(DID, true);
358 if (TheRealType == 0) {
360 ThrowException("Reference to an invalid type: '" +DID.getName(),
361 getLineNumFromPlaceHolder(Ty));
363 ThrowException("Reference to an invalid type: #" + itostr(DID.Num),
364 getLineNumFromPlaceHolder(Ty));
367 // FIXME: When types are not const
368 DerivedType *DTy = const_cast<DerivedType*>(Ty->castDerivedTypeAsserting());
370 // Refine the opaque type we had to the new type we are getting.
371 DTy->refineAbstractTypeTo(TheRealType);
373 // No need to delete type, refine does that for us.
374 LateResolveTypes.pop_back();
378 // setValueName - Set the specified value to the name given. The name may be
379 // null potentially, in which case this is a noop. The string passed in is
380 // assumed to be a malloc'd string buffer, and is freed by this function.
382 static void setValueName(Value *V, char *NameStr) {
383 if (NameStr == 0) return;
384 string Name(NameStr); // Copy string
385 free(NameStr); // Free old string
387 SymbolTable *ST = CurMeth.CurrentMethod ?
388 CurMeth.CurrentMethod->getSymbolTableSure() :
389 CurModule.CurrentModule->getSymbolTableSure();
391 Value *Existing = ST->lookup(V->getType(), Name);
392 if (Existing) { // Inserting a name that is already defined???
393 // There is only one case where this is allowed: when we are refining an
394 // opaque type. In this case, Existing will be an opaque type.
395 if (const Type *Ty = Existing->castType())
396 if (Ty->isOpaqueType()) {
397 // We ARE replacing an opaque type!
399 // TODO: FIXME when types are not const!
400 const_cast<DerivedType*>(Ty->castDerivedTypeAsserting())->refineAbstractTypeTo(V->castTypeAsserting());
404 // Otherwise, we are a simple redefinition of a value, baaad
405 ThrowException("Redefinition of value name '" + Name + "' in the '" +
406 V->getType()->getDescription() + "' type plane!");
409 V->setName(Name, ST);
413 //===----------------------------------------------------------------------===//
414 // Code for handling upreferences in type names...
417 // TypeContains - Returns true if Ty contains E in it.
419 static bool TypeContains(const Type *Ty, const Type *E) {
420 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
424 static vector<pair<unsigned, OpaqueType *> > UpRefs;
426 static PATypeHolder<Type> HandleUpRefs(const Type *ty) {
427 PATypeHolder<Type> Ty(ty);
428 UR_OUT(UpRefs.size() << " upreferences active!\n");
429 for (unsigned i = 0; i < UpRefs.size(); ) {
430 UR_OUT("TypeContains(" << Ty->getDescription() << ", "
431 << UpRefs[i].second->getDescription() << ") = "
432 << TypeContains(Ty, UpRefs[i].second) << endl);
433 if (TypeContains(Ty, UpRefs[i].second)) {
434 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
435 UR_OUT("Uplevel Ref Level = " << Level << endl);
436 if (Level == 0) { // Upreference should be resolved!
437 UR_OUT("About to resolve upreference!\n";
438 string OldName = UpRefs[i].second->getDescription());
439 UpRefs[i].second->refineAbstractTypeTo(Ty);
440 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
441 UR_OUT("Type '" << OldName << "' refined upreference to: "
442 << (const void*)Ty << ", " << Ty->getDescription() << endl);
447 ++i; // Otherwise, no resolve, move on...
449 // FIXME: TODO: this should return the updated type
453 template <class TypeTy>
454 inline static void TypeDone(PATypeHolder<TypeTy> *Ty) {
456 ThrowException("Invalid upreference in type: " + (*Ty)->getDescription());
459 // newTH - Allocate a new type holder for the specified type
460 template <class TypeTy>
461 inline static PATypeHolder<TypeTy> *newTH(const TypeTy *Ty) {
462 return new PATypeHolder<TypeTy>(Ty);
464 template <class TypeTy>
465 inline static PATypeHolder<TypeTy> *newTH(const PATypeHolder<TypeTy> &TH) {
466 return new PATypeHolder<TypeTy>(TH);
470 // newTHC - Allocate a new type holder for the specified type that can be
471 // casted to a new Type type.
472 template <class TypeTy, class OldTy>
473 inline static PATypeHolder<TypeTy> *newTHC(const PATypeHolder<OldTy> &Old) {
474 return new PATypeHolder<TypeTy>((const TypeTy*)Old.get());
478 //===----------------------------------------------------------------------===//
479 // RunVMAsmParser - Define an interface to this parser
480 //===----------------------------------------------------------------------===//
482 Module *RunVMAsmParser(const string &Filename, FILE *F) {
484 CurFilename = Filename;
485 llvmAsmlineno = 1; // Reset the current line number...
487 CurModule.CurrentModule = new Module(); // Allocate a new module to read
488 yyparse(); // Parse the file.
489 Module *Result = ParserResult;
490 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
501 MethodArgument *MethArgVal;
502 BasicBlock *BasicBlockVal;
503 TerminatorInst *TermInstVal;
504 Instruction *InstVal;
505 ConstPoolVal *ConstVal;
507 const Type *PrimType;
508 PATypeHolder<Type> *TypeVal;
509 PATypeHolder<ArrayType> *ArrayTypeTy;
510 PATypeHolder<StructType> *StructTypeTy;
513 list<MethodArgument*> *MethodArgList;
514 list<Value*> *ValueList;
515 list<PATypeHolder<Type> > *TypeList;
516 list<pair<Value*, BasicBlock*> > *PHIList; // Represent the RHS of PHI node
517 list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
518 vector<ConstPoolVal*> *ConstVector;
527 char *StrVal; // This memory is strdup'd!
528 ValID ValIDVal; // strdup'd memory maybe!
530 Instruction::UnaryOps UnaryOpVal;
531 Instruction::BinaryOps BinaryOpVal;
532 Instruction::TermOps TermOpVal;
533 Instruction::MemoryOps MemOpVal;
534 Instruction::OtherOps OtherOpVal;
537 %type <ModuleVal> Module MethodList
538 %type <MethodVal> Method MethodProto MethodHeader BasicBlockList
539 %type <BasicBlockVal> BasicBlock InstructionList
540 %type <TermInstVal> BBTerminatorInst
541 %type <InstVal> Inst InstVal MemoryInst
542 %type <ConstVal> ConstVal ExtendedConstVal
543 %type <ConstVector> ConstVector UByteList
544 %type <MethodArgList> ArgList ArgListH
545 %type <MethArgVal> ArgVal
546 %type <PHIList> PHIList
547 %type <ValueList> ValueRefList ValueRefListE // For call param lists
548 %type <TypeList> TypeListI ArgTypeListI
549 %type <JumpTable> JumpTable
550 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
552 %type <ValIDVal> ValueRef ConstValueRef // Reference to a definition or BB
553 %type <ValueVal> ResolvedVal // <type> <valref> pair
554 // Tokens and types for handling constant integer values
556 // ESINT64VAL - A negative number within long long range
557 %token <SInt64Val> ESINT64VAL
559 // EUINT64VAL - A positive number within uns. long long range
560 %token <UInt64Val> EUINT64VAL
561 %type <SInt64Val> EINT64VAL
563 %token <SIntVal> SINTVAL // Signed 32 bit ints...
564 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
565 %type <SIntVal> INTVAL
566 %token <FPVal> FPVAL // Float or Double constant
569 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
570 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
571 %token <TypeVal> OPAQUE
572 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
573 %token <PrimType> FLOAT DOUBLE TYPE LABEL
574 %type <ArrayTypeTy> ArrayType ArrayTypeI
575 %type <StructTypeTy> StructType StructTypeI
577 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
578 %type <StrVal> OptVAR_ID OptAssign
581 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
582 %token TO DOTDOTDOT STRING
584 // Basic Block Terminating Operators
585 %token <TermOpVal> RET BR SWITCH
588 %type <UnaryOpVal> UnaryOps // all the unary operators
589 %token <UnaryOpVal> NOT
592 %type <BinaryOpVal> BinaryOps // all the binary operators
593 %token <BinaryOpVal> ADD SUB MUL DIV REM
594 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
596 // Memory Instructions
597 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
600 %type <OtherOpVal> ShiftOps
601 %token <OtherOpVal> PHI CALL CAST SHL SHR
606 // Handle constant integer size restriction and conversion...
611 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
612 ThrowException("Value too large for type!");
617 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
618 EINT64VAL : EUINT64VAL {
619 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
620 ThrowException("Value too large for type!");
624 // Operations that are notably excluded from this list include:
625 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
628 BinaryOps : ADD | SUB | MUL | DIV | REM
629 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
632 // These are some types that allow classification if we only want a particular
633 // thing... for example, only a signed, unsigned, or integral type.
634 SIntType : LONG | INT | SHORT | SBYTE
635 UIntType : ULONG | UINT | USHORT | UBYTE
636 IntType : SIntType | UIntType
637 FPType : FLOAT | DOUBLE
639 // OptAssign - Value producing statements have an optional assignment component
640 OptAssign : VAR_ID '=' {
648 //===----------------------------------------------------------------------===//
649 // Types includes all predefined types... except void, because it can only be
650 // used in specific contexts (method returning void for example). To have
651 // access to it, a user must explicitly use TypesV.
654 // TypesV includes all of 'Types', but it also includes the void type.
655 TypesV : Types | VOID { $$ = newTH($1); }
656 UpRTypesV : UpRTypes | VOID { $$ = newTH($1); }
663 // Derived types are added later...
665 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
666 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
667 UpRTypes : OPAQUE | PrimType { $$ = newTH($1); }
668 UpRTypes : ValueRef { // Named types are also simple types...
669 $$ = newTH(getTypeVal($1));
672 // ArrayTypeI - Internal version of ArrayType that can have incomplete uprefs
674 ArrayTypeI : '[' UpRTypesV ']' { // Unsized array type?
675 $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$2)));
678 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
679 $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$4, (int)$2)));
683 StructTypeI : '{' TypeListI '}' { // Structure type?
684 vector<const Type*> Elements;
685 mapto($2->begin(), $2->end(), back_inserter(Elements),
686 mem_fun_ref(&PATypeHandle<Type>::get));
688 $$ = newTHC<StructType>(HandleUpRefs(StructType::get(Elements)));
691 | '{' '}' { // Empty structure type?
692 $$ = newTH(StructType::get(vector<const Type*>()));
696 // Include derived types in the Types production.
698 UpRTypes : '\\' EUINT64VAL { // Type UpReference
699 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
700 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
701 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
702 $$ = newTH<Type>(OT);
703 UR_OUT("New Upreference!\n");
705 | UpRTypesV '(' ArgTypeListI ')' { // Method derived type?
706 vector<const Type*> Params;
707 mapto($3->begin(), $3->end(), back_inserter(Params),
708 mem_fun_ref(&PATypeHandle<Type>::get));
709 $$ = newTH(HandleUpRefs(MethodType::get(*$1, Params)));
710 delete $3; // Delete the argument list
711 delete $1; // Delete the old type handle
713 | ArrayTypeI { // [Un]sized array type?
714 $$ = newTHC<Type>(*$1); delete $1;
716 | StructTypeI { // Structure type?
717 $$ = newTHC<Type>(*$1); delete $1;
719 | UpRTypes '*' { // Pointer type?
720 $$ = newTH(HandleUpRefs(PointerType::get(*$1)));
721 delete $1; // Delete the type handle
724 // Define some helpful top level types that do not allow UpReferences to escape
726 ArrayType : ArrayTypeI { TypeDone($$ = $1); }
727 StructType : StructTypeI { TypeDone($$ = $1); }
731 // TypeList - Used for struct declarations and as a basis for method type
732 // declaration type lists
734 TypeListI : UpRTypes {
735 $$ = new list<PATypeHolder<Type> >();
736 $$->push_back(*$1); delete $1;
738 | TypeListI ',' UpRTypes {
739 ($$=$1)->push_back(*$3); delete $3;
742 // ArgTypeList - List of types for a method type declaration...
743 ArgTypeListI : TypeListI
744 | TypeListI ',' DOTDOTDOT {
745 ($$=$1)->push_back(Type::VoidTy);
748 ($$ = new list<PATypeHolder<Type> >())->push_back(Type::VoidTy);
751 $$ = new list<PATypeHolder<Type> >();
755 // ConstVal - The various declarations that go into the constant pool. This
756 // includes all forward declarations of types, constants, and functions.
758 // This is broken into two sections: ExtendedConstVal and ConstVal
760 ExtendedConstVal: ArrayType '[' ConstVector ']' { // Nonempty unsized arr
761 const ArrayType *ATy = *$1;
762 const Type *ETy = ATy->getElementType();
763 int NumElements = ATy->getNumElements();
765 // Verify that we have the correct size...
766 if (NumElements != -1 && NumElements != (int)$3->size())
767 ThrowException("Type mismatch: constant sized array initialized with " +
768 utostr($3->size()) + " arguments, but has size of " +
769 itostr(NumElements) + "!");
771 // Verify all elements are correct type!
772 for (unsigned i = 0; i < $3->size(); i++) {
773 if (ETy != (*$3)[i]->getType())
774 ThrowException("Element #" + utostr(i) + " is not of type '" +
775 ETy->getName() + "' as required!\nIt is of type '" +
776 (*$3)[i]->getType()->getName() + "'.");
779 $$ = ConstPoolArray::get(ATy, *$3);
780 delete $1; delete $3;
782 | ArrayType '[' ']' {
783 int NumElements = (*$1)->getNumElements();
784 if (NumElements != -1 && NumElements != 0)
785 ThrowException("Type mismatch: constant sized array initialized with 0"
786 " arguments, but has size of " + itostr(NumElements) +"!");
787 $$ = ConstPoolArray::get((*$1), vector<ConstPoolVal*>());
790 | ArrayType 'c' STRINGCONSTANT {
791 const ArrayType *ATy = *$1;
792 int NumElements = ATy->getNumElements();
793 const Type *ETy = ATy->getElementType();
794 char *EndStr = UnEscapeLexed($3, true);
795 if (NumElements != -1 && NumElements != (EndStr-$3))
796 ThrowException("Can't build string constant of size " +
797 itostr((int)(EndStr-$3)) +
798 " when array has size " + itostr(NumElements) + "!");
799 vector<ConstPoolVal*> Vals;
800 if (ETy == Type::SByteTy) {
801 for (char *C = $3; C != EndStr; ++C)
802 Vals.push_back(ConstPoolSInt::get(ETy, *C));
803 } else if (ETy == Type::UByteTy) {
804 for (char *C = $3; C != EndStr; ++C)
805 Vals.push_back(ConstPoolUInt::get(ETy, *C));
808 ThrowException("Cannot build string arrays of non byte sized elements!");
811 $$ = ConstPoolArray::get(ATy, Vals);
814 | StructType '{' ConstVector '}' {
815 // FIXME: TODO: Check to see that the constants are compatible with the type
817 $$ = ConstPoolStruct::get(*$1, *$3);
818 delete $1; delete $3;
821 | Types '*' ConstVal {
827 ConstVal : ExtendedConstVal {
830 | SIntType EINT64VAL { // integral constants
831 if (!ConstPoolSInt::isValueValidForType($1, $2))
832 ThrowException("Constant value doesn't fit in type!");
833 $$ = ConstPoolSInt::get($1, $2);
835 | UIntType EUINT64VAL { // integral constants
836 if (!ConstPoolUInt::isValueValidForType($1, $2))
837 ThrowException("Constant value doesn't fit in type!");
838 $$ = ConstPoolUInt::get($1, $2);
840 | BOOL TRUE { // Boolean constants
841 $$ = ConstPoolBool::True;
843 | BOOL FALSE { // Boolean constants
844 $$ = ConstPoolBool::False;
846 | FPType FPVAL { // Float & Double constants
847 $$ = ConstPoolFP::get($1, $2);
850 // ConstVector - A list of comma seperated constants.
851 ConstVector : ConstVector ',' ConstVal {
852 ($$ = $1)->push_back($3);
855 $$ = new vector<ConstPoolVal*>();
860 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
861 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
864 // ConstPool - Constants with optional names assigned to them.
865 ConstPool : ConstPool OptAssign ConstVal {
866 setValueName($3, $2);
869 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
870 // TODO: FIXME when Type are not const
871 setValueName(const_cast<Type*>($4->get()), $2);
874 InsertType($4->get(),
875 CurMeth.CurrentMethod ? CurMeth.Types : CurModule.Types);
879 | ConstPool MethodProto { // Method prototypes can be in const pool
881 | ConstPool OptAssign GlobalType ResolvedVal {
882 const Type *Ty = $4->getType();
883 // Global declarations appear in Constant Pool
884 ConstPoolVal *Initializer = $4->castConstant();
885 if (Initializer == 0)
886 ThrowException("Global value initializer is not a constant!");
888 GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $3,
890 setValueName(GV, $2);
892 CurModule.CurrentModule->getGlobalList().push_back(GV);
893 InsertValue(GV, CurModule.Values);
895 | ConstPool OptAssign UNINIT GlobalType Types {
896 const Type *Ty = *$5;
897 // Global declarations appear in Constant Pool
898 if (Ty->isArrayType() && Ty->castArrayType()->isUnsized()) {
899 ThrowException("Type '" + Ty->getDescription() +
900 "' is not a sized type!");
903 GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $4);
904 setValueName(GV, $2);
906 CurModule.CurrentModule->getGlobalList().push_back(GV);
907 InsertValue(GV, CurModule.Values);
909 | /* empty: end of list */ {
913 //===----------------------------------------------------------------------===//
914 // Rules to match Modules
915 //===----------------------------------------------------------------------===//
917 // Module rule: Capture the result of parsing the whole file into a result
920 Module : MethodList {
921 $$ = ParserResult = $1;
922 CurModule.ModuleDone();
925 // MethodList - A list of methods, preceeded by a constant pool.
927 MethodList : MethodList Method {
929 if (!$2->getParent())
930 $1->getMethodList().push_back($2);
931 CurMeth.MethodDone();
933 | MethodList MethodProto {
936 | ConstPool IMPLEMENTATION {
937 $$ = CurModule.CurrentModule;
938 // Resolve circular types before we parse the body of the module
939 ResolveTypes(CurModule.LateResolveTypes);
943 //===----------------------------------------------------------------------===//
944 // Rules to match Method Headers
945 //===----------------------------------------------------------------------===//
947 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
949 ArgVal : Types OptVAR_ID {
950 $$ = new MethodArgument(*$1); delete $1;
951 setValueName($$, $2);
954 ArgListH : ArgVal ',' ArgListH {
959 $$ = new list<MethodArgument*>();
963 $$ = new list<MethodArgument*>();
964 $$->push_back(new MethodArgument(Type::VoidTy));
974 MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
976 vector<const Type*> ParamTypeList;
978 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
979 ParamTypeList.push_back((*I)->getType());
981 const MethodType *MT = MethodType::get(*$1, ParamTypeList);
985 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
986 if (Value *V = ST->lookup(MT, $2)) { // Method already in symtab?
987 M = V->castMethodAsserting();
989 // Yes it is. If this is the case, either we need to be a forward decl,
990 // or it needs to be.
991 if (!CurMeth.isDeclare && !M->isExternal())
992 ThrowException("Redefinition of method '" + string($2) + "'!");
996 if (M == 0) { // Not already defined?
997 M = new Method(MT, $2);
998 InsertValue(M, CurModule.Values);
1001 free($2); // Free strdup'd memory!
1003 CurMeth.MethodStart(M);
1005 // Add all of the arguments we parsed to the method...
1006 if ($4 && !CurMeth.isDeclare) { // Is null if empty...
1007 Method::ArgumentListType &ArgList = M->getArgumentList();
1009 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
1011 ArgList.push_back(*I);
1013 delete $4; // We're now done with the argument list
1017 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
1018 $$ = CurMeth.CurrentMethod;
1020 // Resolve circular types before we parse the body of the method.
1021 ResolveTypes(CurMeth.LateResolveTypes);
1024 Method : BasicBlockList END {
1028 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
1029 $$ = CurMeth.CurrentMethod;
1030 if (!$$->getParent())
1031 CurModule.CurrentModule->getMethodList().push_back($$);
1032 CurMeth.MethodDone();
1035 //===----------------------------------------------------------------------===//
1036 // Rules to match Basic Blocks
1037 //===----------------------------------------------------------------------===//
1039 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1040 $$ = ValID::create($1);
1043 $$ = ValID::create($1);
1045 | FPVAL { // Perhaps it's an FP constant?
1046 $$ = ValID::create($1);
1049 $$ = ValID::create((int64_t)1);
1052 $$ = ValID::create((int64_t)0);
1055 | STRINGCONSTANT { // Quoted strings work too... especially for methods
1056 $$ = ValID::create_conststr($1);
1060 // ValueRef - A reference to a definition...
1061 ValueRef : INTVAL { // Is it an integer reference...?
1062 $$ = ValID::create($1);
1064 | VAR_ID { // Is it a named reference...?
1065 $$ = ValID::create($1);
1071 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1072 // type immediately preceeds the value reference, and allows complex constant
1073 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1074 ResolvedVal : ExtendedConstVal {
1078 $$ = getVal(*$1, $2); delete $1;
1082 BasicBlockList : BasicBlockList BasicBlock {
1083 $1->getBasicBlocks().push_back($2);
1086 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
1087 $$ = $1; // in them...
1088 $1->getBasicBlocks().push_back($2);
1092 // Basic blocks are terminated by branching instructions:
1093 // br, br/cc, switch, ret
1095 BasicBlock : InstructionList BBTerminatorInst {
1096 $1->getInstList().push_back($2);
1100 | LABELSTR InstructionList BBTerminatorInst {
1101 $2->getInstList().push_back($3);
1102 setValueName($2, $1);
1108 InstructionList : InstructionList Inst {
1109 $1->getInstList().push_back($2);
1113 $$ = new BasicBlock();
1116 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1117 $$ = new ReturnInst($2);
1119 | RET VOID { // Return with no result...
1120 $$ = new ReturnInst();
1122 | BR LABEL ValueRef { // Unconditional Branch...
1123 $$ = new BranchInst(getVal(Type::LabelTy, $3)->castBasicBlockAsserting());
1124 } // Conditional Branch...
1125 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1126 $$ = new BranchInst(getVal(Type::LabelTy, $6)->castBasicBlockAsserting(),
1127 getVal(Type::LabelTy, $9)->castBasicBlockAsserting(),
1128 getVal(Type::BoolTy, $3));
1130 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1131 SwitchInst *S = new SwitchInst(getVal($2, $3),
1132 getVal(Type::LabelTy, $6)->castBasicBlockAsserting());
1135 list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(),
1137 for (; I != end; ++I)
1138 S->dest_push_back(I->first, I->second);
1141 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1143 ConstPoolVal *V = getVal($2, $3, true)->castConstantAsserting();
1145 ThrowException("May only switch on a constant pool value!");
1147 $$->push_back(make_pair(V, getVal($5, $6)->castBasicBlockAsserting()));
1149 | IntType ConstValueRef ',' LABEL ValueRef {
1150 $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
1151 ConstPoolVal *V = getVal($1, $2, true)->castConstantAsserting();
1154 ThrowException("May only switch on a constant pool value!");
1156 $$->push_back(make_pair(V, getVal($4, $5)->castBasicBlockAsserting()));
1159 Inst : OptAssign InstVal {
1160 setValueName($2, $1); // Is this definition named?? if so, assign the name...
1166 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1167 $$ = new list<pair<Value*, BasicBlock*> >();
1168 $$->push_back(make_pair(getVal(*$1, $3),
1169 getVal(Type::LabelTy, $5)->castBasicBlockAsserting()));
1172 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1174 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1175 getVal(Type::LabelTy, $6)->castBasicBlockAsserting()));
1179 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1180 $$ = new list<Value*>();
1183 | ValueRefList ',' ResolvedVal {
1188 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1189 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1191 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1192 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1194 ThrowException("binary operator returned null!");
1197 | UnaryOps ResolvedVal {
1198 $$ = UnaryOperator::create($1, $2);
1200 ThrowException("unary operator returned null!");
1202 | ShiftOps ResolvedVal ',' ResolvedVal {
1203 if ($4->getType() != Type::UByteTy)
1204 ThrowException("Shift amount must be ubyte!");
1205 $$ = new ShiftInst($1, $2, $4);
1207 | CAST ResolvedVal TO Types {
1208 $$ = new CastInst($2, *$4);
1212 const Type *Ty = $2->front().first->getType();
1213 $$ = new PHINode(Ty);
1214 while ($2->begin() != $2->end()) {
1215 if ($2->front().first->getType() != Ty)
1216 ThrowException("All elements of a PHI node must be of the same type!");
1217 ((PHINode*)$$)->addIncoming($2->front().first, $2->front().second);
1220 delete $2; // Free the list...
1222 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1223 const MethodType *Ty;
1225 if (!(Ty = (*$2)->dyncastMethodType())) {
1226 // Pull out the types of all of the arguments...
1227 vector<const Type*> ParamTypes;
1228 for (list<Value*>::iterator I = $5->begin(), E = $5->end(); I != E; ++I)
1229 ParamTypes.push_back((*I)->getType());
1230 Ty = MethodType::get(*$2, ParamTypes);
1234 Value *V = getVal(Ty, $3); // Get the method we're calling...
1236 // Create the call node...
1237 if (!$5) { // Has no arguments?
1238 $$ = new CallInst(V->castMethodAsserting(), vector<Value*>());
1239 } else { // Has arguments?
1240 // Loop through MethodType's arguments and ensure they are specified
1243 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1244 MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1245 list<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1247 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1248 if ((*ArgI)->getType() != *I)
1249 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1250 (*I)->getName() + "'!");
1252 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1253 ThrowException("Invalid number of parameters detected!");
1255 $$ = new CallInst(V->castMethodAsserting(),
1256 vector<Value*>($5->begin(), $5->end()));
1264 // UByteList - List of ubyte values for load and store instructions
1265 UByteList : ',' ConstVector {
1268 $$ = new vector<ConstPoolVal*>();
1271 MemoryInst : MALLOC Types {
1272 $$ = new MallocInst(PointerType::get(*$2));
1275 | MALLOC Types ',' UINT ValueRef {
1276 if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1277 ThrowException("Trying to allocate " + (*$2)->getName() +
1278 " as unsized array!");
1279 const Type *Ty = PointerType::get(*$2);
1280 $$ = new MallocInst(Ty, getVal($4, $5));
1284 $$ = new AllocaInst(PointerType::get(*$2));
1287 | ALLOCA Types ',' UINT ValueRef {
1288 if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1289 ThrowException("Trying to allocate " + (*$2)->getName() +
1290 " as unsized array!");
1291 const Type *Ty = PointerType::get(*$2);
1292 Value *ArrSize = getVal($4, $5);
1293 $$ = new AllocaInst(Ty, ArrSize);
1296 | FREE ResolvedVal {
1297 if (!$2->getType()->isPointerType())
1298 ThrowException("Trying to free nonpointer type " +
1299 $2->getType()->getName() + "!");
1300 $$ = new FreeInst($2);
1303 | LOAD Types ValueRef UByteList {
1304 if (!(*$2)->isPointerType())
1305 ThrowException("Can't load from nonpointer type: " + (*$2)->getName());
1306 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1307 ThrowException("Invalid indices for load instruction!");
1309 $$ = new LoadInst(getVal(*$2, $3), *$4);
1310 delete $4; // Free the vector...
1313 | STORE ResolvedVal ',' Types ValueRef UByteList {
1314 if (!(*$4)->isPointerType())
1315 ThrowException("Can't store to a nonpointer type: " + (*$4)->getName());
1316 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1318 ThrowException("Can't store into that field list!");
1319 if (ElTy != $2->getType())
1320 ThrowException("Can't store '" + $2->getType()->getName() +
1321 "' into space of type '" + ElTy->getName() + "'!");
1322 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1323 delete $4; delete $6;
1325 | GETELEMENTPTR Types ValueRef UByteList {
1326 if (!(*$2)->isPointerType())
1327 ThrowException("getelementptr insn requires pointer operand!");
1328 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1329 ThrowException("Can't get element ptr '" + (*$2)->getName() + "'!");
1330 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1331 delete $2; delete $4;
1335 int yyerror(const char *ErrorMsg) {
1336 ThrowException(string("Parse error: ") + ErrorMsg);