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 ValID::NumberVal: { // 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 ValID::NameVal: { // 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 ValID::ConstSIntVal: // Is it a constant pool reference??
227 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
228 case ValID::ConstStringVal: // Is it a string const pool reference?
229 case ValID::ConstFPVal: // Is it a floating point const pool reference?
230 case ValID::ConstNullVal: { // Is it a null value?
231 ConstPoolVal *CPV = 0;
233 // Check to make sure that "Ty" is an integral type, and that our
234 // value will fit into the specified type...
236 case ValID::ConstSIntVal:
237 if (Ty == Type::BoolTy) { // Special handling for boolean data
238 CPV = ConstPoolBool::get(D.ConstPool64 != 0);
240 if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64))
241 ThrowException("Symbolic constant pool value '" +
242 itostr(D.ConstPool64) + "' is invalid for type '" +
243 Ty->getName() + "'!");
244 CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
247 case ValID::ConstUIntVal:
248 if (!ConstPoolUInt::isValueValidForType(Ty, D.UConstPool64)) {
249 if (!ConstPoolSInt::isValueValidForType(Ty, D.ConstPool64)) {
250 ThrowException("Integral constant pool reference is invalid!");
251 } else { // This is really a signed reference. Transmogrify.
252 CPV = ConstPoolSInt::get(Ty, D.ConstPool64);
255 CPV = ConstPoolUInt::get(Ty, D.UConstPool64);
258 case ValID::ConstStringVal:
259 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
262 case ValID::ConstFPVal:
263 if (!ConstPoolFP::isValueValidForType(Ty, D.ConstPoolFP))
264 ThrowException("FP constant invalid for type!!");
265 CPV = ConstPoolFP::get(Ty, D.ConstPoolFP);
267 case ValID::ConstNullVal:
268 if (!Ty->isPointerType())
269 ThrowException("Cannot create a a non pointer null!");
270 CPV = ConstPoolPointer::getNullPointer(Ty->castPointerType());
273 assert(0 && "Unhandled case!");
275 assert(CPV && "How did we escape creating a constant??");
277 } // End of case 2,3,4
279 assert(0 && "Unhandled case!");
283 // If we reached here, we referenced either a symbol that we don't know about
284 // or an id number that hasn't been read yet. We may be referencing something
285 // forward, so just create an entry to be resolved later and get to it...
287 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
290 vector<ValueList> *LateResolver = (CurMeth.CurrentMethod) ?
291 &CurMeth.LateResolveValues : &CurModule.LateResolveValues;
293 switch (Ty->getPrimitiveID()) {
294 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
295 case Type::MethodTyID: d = new MethPlaceHolder(Ty, D);
296 LateResolver = &CurModule.LateResolveValues; break;
297 default: d = new ValuePlaceHolder(Ty, D); break;
300 assert(d != 0 && "How did we not make something?");
301 InsertValue(d, *LateResolver);
306 //===----------------------------------------------------------------------===//
307 // Code to handle forward references in instructions
308 //===----------------------------------------------------------------------===//
310 // This code handles the late binding needed with statements that reference
311 // values not defined yet... for example, a forward branch, or the PHI node for
314 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
315 // and back patchs after we are done.
318 // ResolveDefinitions - If we could not resolve some defs at parsing
319 // time (forward branches, phi functions for loops, etc...) resolve the
322 static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
323 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
324 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
325 while (!LateResolvers[ty].empty()) {
326 Value *V = LateResolvers[ty].back();
327 LateResolvers[ty].pop_back();
328 ValID &DID = getValIDFromPlaceHolder(V);
330 Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
332 if (TheRealValue == 0) {
334 ThrowException("Reference to an invalid definition: '" +DID.getName()+
335 "' of type '" + V->getType()->getDescription() + "'",
336 getLineNumFromPlaceHolder(V));
338 ThrowException("Reference to an invalid definition: #" +
339 itostr(DID.Num) + " of type '" +
340 V->getType()->getDescription() + "'",
341 getLineNumFromPlaceHolder(V));
344 assert(!V->isType() && "Types should be in LateResolveTypes!");
346 V->replaceAllUsesWith(TheRealValue);
351 LateResolvers.clear();
355 // ResolveTypes - This goes through the forward referenced type table and makes
356 // sure that all type references are complete. This code is executed after the
357 // constant pool of a method or module is completely parsed.
359 static void ResolveTypes(vector<PATypeHolder<Type> > &LateResolveTypes) {
360 while (!LateResolveTypes.empty()) {
361 const Type *Ty = LateResolveTypes.back();
362 ValID &DID = getValIDFromPlaceHolder(Ty);
364 const Type *TheRealType = getTypeVal(DID, true);
365 if (TheRealType == 0) {
367 ThrowException("Reference to an invalid type: '" +DID.getName(),
368 getLineNumFromPlaceHolder(Ty));
370 ThrowException("Reference to an invalid type: #" + itostr(DID.Num),
371 getLineNumFromPlaceHolder(Ty));
374 // FIXME: When types are not const
375 DerivedType *DTy = const_cast<DerivedType*>(Ty->castDerivedTypeAsserting());
377 // Refine the opaque type we had to the new type we are getting.
378 DTy->refineAbstractTypeTo(TheRealType);
380 // No need to delete type, refine does that for us.
381 LateResolveTypes.pop_back();
385 // setValueName - Set the specified value to the name given. The name may be
386 // null potentially, in which case this is a noop. The string passed in is
387 // assumed to be a malloc'd string buffer, and is freed by this function.
389 static void setValueName(Value *V, char *NameStr) {
390 if (NameStr == 0) return;
391 string Name(NameStr); // Copy string
392 free(NameStr); // Free old string
394 SymbolTable *ST = CurMeth.CurrentMethod ?
395 CurMeth.CurrentMethod->getSymbolTableSure() :
396 CurModule.CurrentModule->getSymbolTableSure();
398 Value *Existing = ST->lookup(V->getType(), Name);
399 if (Existing) { // Inserting a name that is already defined???
400 // There is only one case where this is allowed: when we are refining an
401 // opaque type. In this case, Existing will be an opaque type.
402 if (const Type *Ty = Existing->castType())
403 if (Ty->isOpaqueType()) {
404 // We ARE replacing an opaque type!
406 // TODO: FIXME when types are not const!
407 const_cast<DerivedType*>(Ty->castDerivedTypeAsserting())->refineAbstractTypeTo(V->castTypeAsserting());
411 // Otherwise, we are a simple redefinition of a value, check to see if it
412 // is defined the same as the old one...
413 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
414 if (Ty == cast<const Type>(V)) return; // Yes, it's equal.
418 ThrowException("Redefinition of value name '" + Name + "' in the '" +
419 V->getType()->getDescription() + "' type plane!");
422 V->setName(Name, ST);
426 //===----------------------------------------------------------------------===//
427 // Code for handling upreferences in type names...
430 // TypeContains - Returns true if Ty contains E in it.
432 static bool TypeContains(const Type *Ty, const Type *E) {
433 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
437 static vector<pair<unsigned, OpaqueType *> > UpRefs;
439 static PATypeHolder<Type> HandleUpRefs(const Type *ty) {
440 PATypeHolder<Type> Ty(ty);
441 UR_OUT(UpRefs.size() << " upreferences active!\n");
442 for (unsigned i = 0; i < UpRefs.size(); ) {
443 UR_OUT("TypeContains(" << Ty->getDescription() << ", "
444 << UpRefs[i].second->getDescription() << ") = "
445 << TypeContains(Ty, UpRefs[i].second) << endl);
446 if (TypeContains(Ty, UpRefs[i].second)) {
447 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
448 UR_OUT("Uplevel Ref Level = " << Level << endl);
449 if (Level == 0) { // Upreference should be resolved!
450 UR_OUT("About to resolve upreference!\n";
451 string OldName = UpRefs[i].second->getDescription());
452 UpRefs[i].second->refineAbstractTypeTo(Ty);
453 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
454 UR_OUT("Type '" << OldName << "' refined upreference to: "
455 << (const void*)Ty << ", " << Ty->getDescription() << endl);
460 ++i; // Otherwise, no resolve, move on...
462 // FIXME: TODO: this should return the updated type
466 template <class TypeTy>
467 inline static void TypeDone(PATypeHolder<TypeTy> *Ty) {
469 ThrowException("Invalid upreference in type: " + (*Ty)->getDescription());
472 // newTH - Allocate a new type holder for the specified type
473 template <class TypeTy>
474 inline static PATypeHolder<TypeTy> *newTH(const TypeTy *Ty) {
475 return new PATypeHolder<TypeTy>(Ty);
477 template <class TypeTy>
478 inline static PATypeHolder<TypeTy> *newTH(const PATypeHolder<TypeTy> &TH) {
479 return new PATypeHolder<TypeTy>(TH);
483 // newTHC - Allocate a new type holder for the specified type that can be
484 // casted to a new Type type.
485 template <class TypeTy, class OldTy>
486 inline static PATypeHolder<TypeTy> *newTHC(const PATypeHolder<OldTy> &Old) {
487 return new PATypeHolder<TypeTy>((const TypeTy*)Old.get());
491 //===----------------------------------------------------------------------===//
492 // RunVMAsmParser - Define an interface to this parser
493 //===----------------------------------------------------------------------===//
495 Module *RunVMAsmParser(const string &Filename, FILE *F) {
497 CurFilename = Filename;
498 llvmAsmlineno = 1; // Reset the current line number...
500 CurModule.CurrentModule = new Module(); // Allocate a new module to read
501 yyparse(); // Parse the file.
502 Module *Result = ParserResult;
503 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
514 MethodArgument *MethArgVal;
515 BasicBlock *BasicBlockVal;
516 TerminatorInst *TermInstVal;
517 Instruction *InstVal;
518 ConstPoolVal *ConstVal;
520 const Type *PrimType;
521 PATypeHolder<Type> *TypeVal;
522 PATypeHolder<ArrayType> *ArrayTypeTy;
523 PATypeHolder<StructType> *StructTypeTy;
524 PATypeHolder<PointerType> *PointerTypeTy;
527 list<MethodArgument*> *MethodArgList;
528 list<Value*> *ValueList;
529 list<PATypeHolder<Type> > *TypeList;
530 list<pair<Value*, BasicBlock*> > *PHIList; // Represent the RHS of PHI node
531 list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
532 vector<ConstPoolVal*> *ConstVector;
541 char *StrVal; // This memory is strdup'd!
542 ValID ValIDVal; // strdup'd memory maybe!
544 Instruction::UnaryOps UnaryOpVal;
545 Instruction::BinaryOps BinaryOpVal;
546 Instruction::TermOps TermOpVal;
547 Instruction::MemoryOps MemOpVal;
548 Instruction::OtherOps OtherOpVal;
551 %type <ModuleVal> Module MethodList
552 %type <MethodVal> Method MethodProto MethodHeader BasicBlockList
553 %type <BasicBlockVal> BasicBlock InstructionList
554 %type <TermInstVal> BBTerminatorInst
555 %type <InstVal> Inst InstVal MemoryInst
556 %type <ConstVal> ConstVal ExtendedConstVal
557 %type <ConstVector> ConstVector UByteList
558 %type <MethodArgList> ArgList ArgListH
559 %type <MethArgVal> ArgVal
560 %type <PHIList> PHIList
561 %type <ValueList> ValueRefList ValueRefListE // For call param lists
562 %type <TypeList> TypeListI ArgTypeListI
563 %type <JumpTable> JumpTable
564 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
566 %type <ValIDVal> ValueRef ConstValueRef // Reference to a definition or BB
567 %type <ValueVal> ResolvedVal // <type> <valref> pair
568 // Tokens and types for handling constant integer values
570 // ESINT64VAL - A negative number within long long range
571 %token <SInt64Val> ESINT64VAL
573 // EUINT64VAL - A positive number within uns. long long range
574 %token <UInt64Val> EUINT64VAL
575 %type <SInt64Val> EINT64VAL
577 %token <SIntVal> SINTVAL // Signed 32 bit ints...
578 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
579 %type <SIntVal> INTVAL
580 %token <FPVal> FPVAL // Float or Double constant
583 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
584 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
585 %token <TypeVal> OPAQUE
586 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
587 %token <PrimType> FLOAT DOUBLE TYPE LABEL
588 %type <ArrayTypeTy> ArrayType ArrayTypeI
589 %type <StructTypeTy> StructType StructTypeI
590 %type <PointerTypeTy> PointerType PointerTypeI
592 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
593 %type <StrVal> OptVAR_ID OptAssign
596 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
597 %token TO DOTDOTDOT STRING NULL_TOK
599 // Basic Block Terminating Operators
600 %token <TermOpVal> RET BR SWITCH
603 %type <UnaryOpVal> UnaryOps // all the unary operators
604 %token <UnaryOpVal> NOT
607 %type <BinaryOpVal> BinaryOps // all the binary operators
608 %token <BinaryOpVal> ADD SUB MUL DIV REM
609 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
611 // Memory Instructions
612 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
615 %type <OtherOpVal> ShiftOps
616 %token <OtherOpVal> PHI CALL CAST SHL SHR
621 // Handle constant integer size restriction and conversion...
626 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
627 ThrowException("Value too large for type!");
632 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
633 EINT64VAL : EUINT64VAL {
634 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
635 ThrowException("Value too large for type!");
639 // Operations that are notably excluded from this list include:
640 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
643 BinaryOps : ADD | SUB | MUL | DIV | REM
644 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
647 // These are some types that allow classification if we only want a particular
648 // thing... for example, only a signed, unsigned, or integral type.
649 SIntType : LONG | INT | SHORT | SBYTE
650 UIntType : ULONG | UINT | USHORT | UBYTE
651 IntType : SIntType | UIntType
652 FPType : FLOAT | DOUBLE
654 // OptAssign - Value producing statements have an optional assignment component
655 OptAssign : VAR_ID '=' {
663 //===----------------------------------------------------------------------===//
664 // Types includes all predefined types... except void, because it can only be
665 // used in specific contexts (method returning void for example). To have
666 // access to it, a user must explicitly use TypesV.
669 // TypesV includes all of 'Types', but it also includes the void type.
670 TypesV : Types | VOID { $$ = newTH($1); }
671 UpRTypesV : UpRTypes | VOID { $$ = newTH($1); }
678 // Derived types are added later...
680 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
681 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
682 UpRTypes : OPAQUE | PrimType { $$ = newTH($1); }
683 UpRTypes : ValueRef { // Named types are also simple types...
684 $$ = newTH(getTypeVal($1));
687 // ArrayTypeI - Internal version of ArrayType that can have incomplete uprefs
689 ArrayTypeI : '[' UpRTypesV ']' { // Unsized array type?
690 $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$2)));
693 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
694 $$ = newTHC<ArrayType>(HandleUpRefs(ArrayType::get(*$4, (int)$2)));
698 StructTypeI : '{' TypeListI '}' { // Structure type?
699 vector<const Type*> Elements;
700 mapto($2->begin(), $2->end(), back_inserter(Elements),
701 mem_fun_ref(&PATypeHandle<Type>::get));
703 $$ = newTHC<StructType>(HandleUpRefs(StructType::get(Elements)));
706 | '{' '}' { // Empty structure type?
707 $$ = newTH(StructType::get(vector<const Type*>()));
710 PointerTypeI : UpRTypes '*' { // Pointer type?
711 $$ = newTHC<PointerType>(HandleUpRefs(PointerType::get(*$1)));
712 delete $1; // Delete the type handle
715 // Include derived types in the Types production.
717 UpRTypes : '\\' EUINT64VAL { // Type UpReference
718 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
719 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
720 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
721 $$ = newTH<Type>(OT);
722 UR_OUT("New Upreference!\n");
724 | UpRTypesV '(' ArgTypeListI ')' { // Method derived type?
725 vector<const Type*> Params;
726 mapto($3->begin(), $3->end(), back_inserter(Params),
727 mem_fun_ref(&PATypeHandle<Type>::get));
728 $$ = newTH(HandleUpRefs(MethodType::get(*$1, Params)));
729 delete $3; // Delete the argument list
730 delete $1; // Delete the old type handle
732 | ArrayTypeI { // [Un]sized array type?
733 $$ = newTHC<Type>(*$1); delete $1;
735 | StructTypeI { // Structure type?
736 $$ = newTHC<Type>(*$1); delete $1;
738 | PointerTypeI { // Pointer type?
739 $$ = newTHC<Type>(*$1); delete $1;
742 // Define some helpful top level types that do not allow UpReferences to escape
744 ArrayType : ArrayTypeI { TypeDone($$ = $1); }
745 StructType : StructTypeI { TypeDone($$ = $1); }
746 PointerType : PointerTypeI { TypeDone($$ = $1); }
749 // TypeList - Used for struct declarations and as a basis for method type
750 // declaration type lists
752 TypeListI : UpRTypes {
753 $$ = new list<PATypeHolder<Type> >();
754 $$->push_back(*$1); delete $1;
756 | TypeListI ',' UpRTypes {
757 ($$=$1)->push_back(*$3); delete $3;
760 // ArgTypeList - List of types for a method type declaration...
761 ArgTypeListI : TypeListI
762 | TypeListI ',' DOTDOTDOT {
763 ($$=$1)->push_back(Type::VoidTy);
766 ($$ = new list<PATypeHolder<Type> >())->push_back(Type::VoidTy);
769 $$ = new list<PATypeHolder<Type> >();
773 // ConstVal - The various declarations that go into the constant pool. This
774 // includes all forward declarations of types, constants, and functions.
776 // This is broken into two sections: ExtendedConstVal and ConstVal
778 ExtendedConstVal: ArrayType '[' ConstVector ']' { // Nonempty unsized arr
779 const ArrayType *ATy = *$1;
780 const Type *ETy = ATy->getElementType();
781 int NumElements = ATy->getNumElements();
783 // Verify that we have the correct size...
784 if (NumElements != -1 && NumElements != (int)$3->size())
785 ThrowException("Type mismatch: constant sized array initialized with " +
786 utostr($3->size()) + " arguments, but has size of " +
787 itostr(NumElements) + "!");
789 // Verify all elements are correct type!
790 for (unsigned i = 0; i < $3->size(); i++) {
791 if (ETy != (*$3)[i]->getType())
792 ThrowException("Element #" + utostr(i) + " is not of type '" +
793 ETy->getName() + "' as required!\nIt is of type '" +
794 (*$3)[i]->getType()->getName() + "'.");
797 $$ = ConstPoolArray::get(ATy, *$3);
798 delete $1; delete $3;
800 | ArrayType '[' ']' {
801 int NumElements = (*$1)->getNumElements();
802 if (NumElements != -1 && NumElements != 0)
803 ThrowException("Type mismatch: constant sized array initialized with 0"
804 " arguments, but has size of " + itostr(NumElements) +"!");
805 $$ = ConstPoolArray::get((*$1), vector<ConstPoolVal*>());
808 | ArrayType 'c' STRINGCONSTANT {
809 const ArrayType *ATy = *$1;
810 int NumElements = ATy->getNumElements();
811 const Type *ETy = ATy->getElementType();
812 char *EndStr = UnEscapeLexed($3, true);
813 if (NumElements != -1 && NumElements != (EndStr-$3))
814 ThrowException("Can't build string constant of size " +
815 itostr((int)(EndStr-$3)) +
816 " when array has size " + itostr(NumElements) + "!");
817 vector<ConstPoolVal*> Vals;
818 if (ETy == Type::SByteTy) {
819 for (char *C = $3; C != EndStr; ++C)
820 Vals.push_back(ConstPoolSInt::get(ETy, *C));
821 } else if (ETy == Type::UByteTy) {
822 for (char *C = $3; C != EndStr; ++C)
823 Vals.push_back(ConstPoolUInt::get(ETy, *C));
826 ThrowException("Cannot build string arrays of non byte sized elements!");
829 $$ = ConstPoolArray::get(ATy, Vals);
832 | StructType '{' ConstVector '}' {
833 // FIXME: TODO: Check to see that the constants are compatible with the type
835 $$ = ConstPoolStruct::get(*$1, *$3);
836 delete $1; delete $3;
839 | Types '*' ConstVal {
845 ConstVal : ExtendedConstVal {
848 | SIntType EINT64VAL { // integral constants
849 if (!ConstPoolSInt::isValueValidForType($1, $2))
850 ThrowException("Constant value doesn't fit in type!");
851 $$ = ConstPoolSInt::get($1, $2);
853 | UIntType EUINT64VAL { // integral constants
854 if (!ConstPoolUInt::isValueValidForType($1, $2))
855 ThrowException("Constant value doesn't fit in type!");
856 $$ = ConstPoolUInt::get($1, $2);
858 | BOOL TRUE { // Boolean constants
859 $$ = ConstPoolBool::True;
861 | BOOL FALSE { // Boolean constants
862 $$ = ConstPoolBool::False;
864 | FPType FPVAL { // Float & Double constants
865 $$ = ConstPoolFP::get($1, $2);
868 // ConstVector - A list of comma seperated constants.
869 ConstVector : ConstVector ',' ConstVal {
870 ($$ = $1)->push_back($3);
873 $$ = new vector<ConstPoolVal*>();
878 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
879 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
882 // ConstPool - Constants with optional names assigned to them.
883 ConstPool : ConstPool OptAssign ConstVal {
884 setValueName($3, $2);
887 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
888 // TODO: FIXME when Type are not const
889 setValueName(const_cast<Type*>($4->get()), $2);
892 InsertType($4->get(),
893 CurMeth.CurrentMethod ? CurMeth.Types : CurModule.Types);
897 | ConstPool MethodProto { // Method prototypes can be in const pool
899 | ConstPool OptAssign GlobalType ResolvedVal {
900 const Type *Ty = $4->getType();
901 // Global declarations appear in Constant Pool
902 ConstPoolVal *Initializer = $4->castConstant();
903 if (Initializer == 0)
904 ThrowException("Global value initializer is not a constant!");
906 GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $3,
908 setValueName(GV, $2);
910 CurModule.CurrentModule->getGlobalList().push_back(GV);
911 InsertValue(GV, CurModule.Values);
913 | ConstPool OptAssign UNINIT GlobalType Types {
914 const Type *Ty = *$5;
915 // Global declarations appear in Constant Pool
916 if (Ty->isArrayType() && Ty->castArrayType()->isUnsized()) {
917 ThrowException("Type '" + Ty->getDescription() +
918 "' is not a sized type!");
921 GlobalVariable *GV = new GlobalVariable(PointerType::get(Ty), $4);
922 setValueName(GV, $2);
924 CurModule.CurrentModule->getGlobalList().push_back(GV);
925 InsertValue(GV, CurModule.Values);
927 | /* empty: end of list */ {
931 //===----------------------------------------------------------------------===//
932 // Rules to match Modules
933 //===----------------------------------------------------------------------===//
935 // Module rule: Capture the result of parsing the whole file into a result
938 Module : MethodList {
939 $$ = ParserResult = $1;
940 CurModule.ModuleDone();
943 // MethodList - A list of methods, preceeded by a constant pool.
945 MethodList : MethodList Method {
947 if (!$2->getParent())
948 $1->getMethodList().push_back($2);
949 CurMeth.MethodDone();
951 | MethodList MethodProto {
954 | ConstPool IMPLEMENTATION {
955 $$ = CurModule.CurrentModule;
956 // Resolve circular types before we parse the body of the module
957 ResolveTypes(CurModule.LateResolveTypes);
961 //===----------------------------------------------------------------------===//
962 // Rules to match Method Headers
963 //===----------------------------------------------------------------------===//
965 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
967 ArgVal : Types OptVAR_ID {
968 $$ = new MethodArgument(*$1); delete $1;
969 setValueName($$, $2);
972 ArgListH : ArgVal ',' ArgListH {
977 $$ = new list<MethodArgument*>();
981 $$ = new list<MethodArgument*>();
982 $$->push_back(new MethodArgument(Type::VoidTy));
992 MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
994 vector<const Type*> ParamTypeList;
996 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I)
997 ParamTypeList.push_back((*I)->getType());
999 const MethodType *MT = MethodType::get(*$1, ParamTypeList);
1003 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1004 if (Value *V = ST->lookup(MT, $2)) { // Method already in symtab?
1005 M = cast<Method>(V);
1007 // Yes it is. If this is the case, either we need to be a forward decl,
1008 // or it needs to be.
1009 if (!CurMeth.isDeclare && !M->isExternal())
1010 ThrowException("Redefinition of method '" + string($2) + "'!");
1014 if (M == 0) { // Not already defined?
1015 M = new Method(MT, $2);
1016 InsertValue(M, CurModule.Values);
1019 free($2); // Free strdup'd memory!
1021 CurMeth.MethodStart(M);
1023 // Add all of the arguments we parsed to the method...
1024 if ($4 && !CurMeth.isDeclare) { // Is null if empty...
1025 Method::ArgumentListType &ArgList = M->getArgumentList();
1027 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); ++I) {
1029 ArgList.push_back(*I);
1031 delete $4; // We're now done with the argument list
1035 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
1036 $$ = CurMeth.CurrentMethod;
1038 // Resolve circular types before we parse the body of the method.
1039 ResolveTypes(CurMeth.LateResolveTypes);
1042 Method : BasicBlockList END {
1046 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
1047 $$ = CurMeth.CurrentMethod;
1048 if (!$$->getParent())
1049 CurModule.CurrentModule->getMethodList().push_back($$);
1050 CurMeth.MethodDone();
1053 //===----------------------------------------------------------------------===//
1054 // Rules to match Basic Blocks
1055 //===----------------------------------------------------------------------===//
1057 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1058 $$ = ValID::create($1);
1061 $$ = ValID::create($1);
1063 | FPVAL { // Perhaps it's an FP constant?
1064 $$ = ValID::create($1);
1067 $$ = ValID::create((int64_t)1);
1070 $$ = ValID::create((int64_t)0);
1073 $$ = ValID::createNull();
1077 | STRINGCONSTANT { // Quoted strings work too... especially for methods
1078 $$ = ValID::create_conststr($1);
1082 // ValueRef - A reference to a definition...
1083 ValueRef : INTVAL { // Is it an integer reference...?
1084 $$ = ValID::create($1);
1086 | VAR_ID { // Is it a named reference...?
1087 $$ = ValID::create($1);
1093 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1094 // type immediately preceeds the value reference, and allows complex constant
1095 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1096 ResolvedVal : ExtendedConstVal {
1100 $$ = getVal(*$1, $2); delete $1;
1104 BasicBlockList : BasicBlockList BasicBlock {
1105 $1->getBasicBlocks().push_back($2);
1108 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
1109 $$ = $1; // in them...
1110 $1->getBasicBlocks().push_back($2);
1114 // Basic blocks are terminated by branching instructions:
1115 // br, br/cc, switch, ret
1117 BasicBlock : InstructionList BBTerminatorInst {
1118 $1->getInstList().push_back($2);
1122 | LABELSTR InstructionList BBTerminatorInst {
1123 $2->getInstList().push_back($3);
1124 setValueName($2, $1);
1130 InstructionList : InstructionList Inst {
1131 $1->getInstList().push_back($2);
1135 $$ = new BasicBlock();
1138 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1139 $$ = new ReturnInst($2);
1141 | RET VOID { // Return with no result...
1142 $$ = new ReturnInst();
1144 | BR LABEL ValueRef { // Unconditional Branch...
1145 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1146 } // Conditional Branch...
1147 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1148 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1149 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1150 getVal(Type::BoolTy, $3));
1152 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1153 SwitchInst *S = new SwitchInst(getVal($2, $3),
1154 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1157 list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(),
1159 for (; I != end; ++I)
1160 S->dest_push_back(I->first, I->second);
1163 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1165 ConstPoolVal *V = getVal($2, $3, true)->castConstantAsserting();
1167 ThrowException("May only switch on a constant pool value!");
1169 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1171 | IntType ConstValueRef ',' LABEL ValueRef {
1172 $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
1173 ConstPoolVal *V = getVal($1, $2, true)->castConstantAsserting();
1176 ThrowException("May only switch on a constant pool value!");
1178 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1181 Inst : OptAssign InstVal {
1182 setValueName($2, $1); // Is this definition named?? if so, assign the name...
1188 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1189 $$ = new list<pair<Value*, BasicBlock*> >();
1190 $$->push_back(make_pair(getVal(*$1, $3),
1191 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1194 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1196 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1197 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1201 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1202 $$ = new list<Value*>();
1205 | ValueRefList ',' ResolvedVal {
1210 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1211 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1213 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1214 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1216 ThrowException("binary operator returned null!");
1219 | UnaryOps ResolvedVal {
1220 $$ = UnaryOperator::create($1, $2);
1222 ThrowException("unary operator returned null!");
1224 | ShiftOps ResolvedVal ',' ResolvedVal {
1225 if ($4->getType() != Type::UByteTy)
1226 ThrowException("Shift amount must be ubyte!");
1227 $$ = new ShiftInst($1, $2, $4);
1229 | CAST ResolvedVal TO Types {
1230 $$ = new CastInst($2, *$4);
1234 const Type *Ty = $2->front().first->getType();
1235 $$ = new PHINode(Ty);
1236 while ($2->begin() != $2->end()) {
1237 if ($2->front().first->getType() != Ty)
1238 ThrowException("All elements of a PHI node must be of the same type!");
1239 ((PHINode*)$$)->addIncoming($2->front().first, $2->front().second);
1242 delete $2; // Free the list...
1244 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1245 const MethodType *Ty;
1247 if (!(Ty = dyn_cast<MethodType>($2->get()))) {
1248 // Pull out the types of all of the arguments...
1249 vector<const Type*> ParamTypes;
1250 for (list<Value*>::iterator I = $5->begin(), E = $5->end(); I != E; ++I)
1251 ParamTypes.push_back((*I)->getType());
1252 Ty = MethodType::get(*$2, ParamTypes);
1256 Value *V = getVal(Ty, $3); // Get the method we're calling...
1258 // Create the call node...
1259 if (!$5) { // Has no arguments?
1260 $$ = new CallInst(cast<Method>(V), vector<Value*>());
1261 } else { // Has arguments?
1262 // Loop through MethodType's arguments and ensure they are specified
1265 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1266 MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1267 list<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1269 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1270 if ((*ArgI)->getType() != *I)
1271 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1272 (*I)->getName() + "'!");
1274 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1275 ThrowException("Invalid number of parameters detected!");
1277 $$ = new CallInst(cast<Method>(V),
1278 vector<Value*>($5->begin(), $5->end()));
1286 // UByteList - List of ubyte values for load and store instructions
1287 UByteList : ',' ConstVector {
1290 $$ = new vector<ConstPoolVal*>();
1293 MemoryInst : MALLOC Types {
1294 $$ = new MallocInst(PointerType::get(*$2));
1297 | MALLOC Types ',' UINT ValueRef {
1298 if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1299 ThrowException("Trying to allocate " + (*$2)->getName() +
1300 " as unsized array!");
1301 const Type *Ty = PointerType::get(*$2);
1302 $$ = new MallocInst(Ty, getVal($4, $5));
1306 $$ = new AllocaInst(PointerType::get(*$2));
1309 | ALLOCA Types ',' UINT ValueRef {
1310 if (!(*$2)->isArrayType() || ((const ArrayType*)$2->get())->isSized())
1311 ThrowException("Trying to allocate " + (*$2)->getName() +
1312 " as unsized array!");
1313 const Type *Ty = PointerType::get(*$2);
1314 Value *ArrSize = getVal($4, $5);
1315 $$ = new AllocaInst(Ty, ArrSize);
1318 | FREE ResolvedVal {
1319 if (!$2->getType()->isPointerType())
1320 ThrowException("Trying to free nonpointer type " +
1321 $2->getType()->getName() + "!");
1322 $$ = new FreeInst($2);
1325 | LOAD Types ValueRef UByteList {
1326 if (!(*$2)->isPointerType())
1327 ThrowException("Can't load from nonpointer type: " + (*$2)->getName());
1328 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1329 ThrowException("Invalid indices for load instruction!");
1331 $$ = new LoadInst(getVal(*$2, $3), *$4);
1332 delete $4; // Free the vector...
1335 | STORE ResolvedVal ',' Types ValueRef UByteList {
1336 if (!(*$4)->isPointerType())
1337 ThrowException("Can't store to a nonpointer type: " + (*$4)->getName());
1338 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1340 ThrowException("Can't store into that field list!");
1341 if (ElTy != $2->getType())
1342 ThrowException("Can't store '" + $2->getType()->getName() +
1343 "' into space of type '" + ElTy->getName() + "'!");
1344 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1345 delete $4; delete $6;
1347 | GETELEMENTPTR Types ValueRef UByteList {
1348 if (!(*$2)->isPointerType())
1349 ThrowException("getelementptr insn requires pointer operand!");
1350 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1351 ThrowException("Can't get element ptr '" + (*$2)->getName() + "'!");
1352 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1353 delete $2; delete $4;
1357 int yyerror(const char *ErrorMsg) {
1358 ThrowException(string("Parse error: ") + ErrorMsg);