1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
3 // This file implements the bison parser for LLVM assembly languages files.
5 //===------------------------------------------------------------------------=//
8 #include "ParserInternals.h"
9 #include "llvm/Assembly/Parser.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/Module.h"
12 #include "llvm/GlobalVariable.h"
13 #include "llvm/Method.h"
14 #include "llvm/BasicBlock.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/iTerminators.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/iPHINode.h"
19 #include "Support/STLExtras.h"
20 #include "Support/DepthFirstIterator.h"
22 #include <utility> // Get definition of pair class
24 #include <stdio.h> // This embarasment is due to our flex lexer...
35 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
36 int yylex(); // declaration" of xxx warnings.
39 static Module *ParserResult;
42 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
43 // relating to upreferences in the input stream.
45 //#define DEBUG_UPREFS 1
47 #define UR_OUT(X) cerr << X
52 // This contains info used when building the body of a method. It is destroyed
53 // when the method is completed.
55 typedef vector<Value *> ValueList; // Numbered defs
56 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
57 vector<ValueList> *FutureLateResolvers = 0);
59 static struct PerModuleInfo {
60 Module *CurrentModule;
61 vector<ValueList> Values; // Module level numbered definitions
62 vector<ValueList> LateResolveValues;
63 vector<PATypeHolder<Type> > Types;
64 map<ValID, PATypeHolder<Type> > LateResolveTypes;
66 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
67 // references to global values. Global values may be referenced before they
68 // are defined, and if so, the temporary object that they represent is held
69 // here. This is used for forward references of ConstantPointerRefs.
71 typedef map<pair<const PointerType *, ValID>, GlobalVariable*> GlobalRefsType;
72 GlobalRefsType GlobalRefs;
75 // If we could not resolve some methods at method compilation time (calls to
76 // methods before they are defined), resolve them now... Types are resolved
77 // when the constant pool has been completely parsed.
79 ResolveDefinitions(LateResolveValues);
81 // Check to make sure that all global value forward references have been
84 if (!GlobalRefs.empty()) {
85 string UndefinedReferences = "Unresolved global references exist:\n";
87 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
89 UndefinedReferences += " " + I->first.first->getDescription() + " " +
90 I->first.second.getName() + "\n";
92 ThrowException(UndefinedReferences);
95 Values.clear(); // Clear out method local definitions
101 // DeclareNewGlobalValue - Called every type a new GV has been defined. This
102 // is used to remove things from the forward declaration map, resolving them
103 // to the correct thing as needed.
105 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
106 // Check to see if there is a forward reference to this global variable...
107 // if there is, eliminate it and patch the reference to use the new def'n.
108 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), D));
110 if (I != GlobalRefs.end()) {
111 GlobalVariable *OldGV = I->second; // Get the placeholder...
112 I->first.second.destroy(); // Free string memory if neccesary
114 // Loop over all of the uses of the GlobalValue. The only thing they are
115 // allowed to be at this point is ConstantPointerRef's.
116 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
117 while (!OldGV->use_empty()) {
118 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
119 ConstantPointerRef *CPPR = cast<ConstantPointerRef>(U);
120 assert(CPPR->getValue() == OldGV && "Something isn't happy");
122 // Change the const pool reference to point to the real global variable
123 // now. This should drop a use from the OldGV.
124 CPPR->mutateReference(GV);
127 // Remove GV from the module...
128 CurrentModule->getGlobalList().remove(OldGV);
129 delete OldGV; // Delete the old placeholder
131 // Remove the map entry for the global now that it has been created...
138 static struct PerMethodInfo {
139 Method *CurrentMethod; // Pointer to current method being created
141 vector<ValueList> Values; // Keep track of numbered definitions
142 vector<ValueList> LateResolveValues;
143 vector<PATypeHolder<Type> > Types;
144 map<ValID, PATypeHolder<Type> > LateResolveTypes;
145 bool isDeclare; // Is this method a forward declararation?
147 inline PerMethodInfo() {
152 inline ~PerMethodInfo() {}
154 inline void MethodStart(Method *M) {
159 // If we could not resolve some blocks at parsing time (forward branches)
160 // resolve the branches now...
161 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
163 Values.clear(); // Clear out method local definitions
168 } CurMeth; // Info for the current method...
170 static bool inMethodScope() { return CurMeth.CurrentMethod != 0; }
173 //===----------------------------------------------------------------------===//
174 // Code to handle definitions of all the types
175 //===----------------------------------------------------------------------===//
177 static int InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
178 if (D->hasName()) return -1; // Is this a numbered definition?
180 // Yes, insert the value into the value table...
181 unsigned type = D->getType()->getUniqueID();
182 if (ValueTab.size() <= type)
183 ValueTab.resize(type+1, ValueList());
184 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
185 ValueTab[type].push_back(D);
186 return ValueTab[type].size()-1;
189 // TODO: FIXME when Type are not const
190 static void InsertType(const Type *Ty, vector<PATypeHolder<Type> > &Types) {
194 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
196 case 0: { // Is it a numbered definition?
197 unsigned Num = (unsigned)D.Num;
199 // Module constants occupy the lowest numbered slots...
200 if (Num < CurModule.Types.size())
201 return CurModule.Types[Num];
203 Num -= CurModule.Types.size();
205 // Check that the number is within bounds...
206 if (Num <= CurMeth.Types.size())
207 return CurMeth.Types[Num];
210 case 1: { // Is it a named definition?
212 SymbolTable *SymTab = 0;
213 if (inMethodScope()) SymTab = CurMeth.CurrentMethod->getSymbolTable();
214 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
217 // Symbol table doesn't automatically chain yet... because the method
218 // hasn't been added to the module...
220 SymTab = CurModule.CurrentModule->getSymbolTable();
222 N = SymTab->lookup(Type::TypeTy, Name);
226 D.destroy(); // Free old strdup'd memory...
227 return cast<const Type>(N);
230 ThrowException("Invalid symbol type reference!");
233 // If we reached here, we referenced either a symbol that we don't know about
234 // or an id number that hasn't been read yet. We may be referencing something
235 // forward, so just create an entry to be resolved later and get to it...
237 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
239 map<ValID, PATypeHolder<Type> > &LateResolver = inMethodScope() ?
240 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
242 map<ValID, PATypeHolder<Type> >::iterator I = LateResolver.find(D);
243 if (I != LateResolver.end()) {
247 Type *Typ = OpaqueType::get();
248 LateResolver.insert(make_pair(D, Typ));
252 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
253 SymbolTable *SymTab =
254 inMethodScope() ? CurMeth.CurrentMethod->getSymbolTable() : 0;
255 Value *N = SymTab ? SymTab->lookup(Ty, Name) : 0;
258 // Symbol table doesn't automatically chain yet... because the method
259 // hasn't been added to the module...
261 SymTab = CurModule.CurrentModule->getSymbolTable();
263 N = SymTab->lookup(Ty, Name);
269 // getValNonImprovising - Look up the value specified by the provided type and
270 // the provided ValID. If the value exists and has already been defined, return
271 // it. Otherwise return null.
273 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
274 if (isa<MethodType>(Ty))
275 ThrowException("Methods are not values and must be referenced as pointers");
278 case ValID::NumberVal: { // Is it a numbered definition?
279 unsigned type = Ty->getUniqueID();
280 unsigned Num = (unsigned)D.Num;
282 // Module constants occupy the lowest numbered slots...
283 if (type < CurModule.Values.size()) {
284 if (Num < CurModule.Values[type].size())
285 return CurModule.Values[type][Num];
287 Num -= CurModule.Values[type].size();
290 // Make sure that our type is within bounds
291 if (CurMeth.Values.size() <= type) return 0;
293 // Check that the number is within bounds...
294 if (CurMeth.Values[type].size() <= Num) return 0;
296 return CurMeth.Values[type][Num];
299 case ValID::NameVal: { // Is it a named definition?
300 Value *N = lookupInSymbolTable(Ty, string(D.Name));
301 if (N == 0) return 0;
303 D.destroy(); // Free old strdup'd memory...
307 // Check to make sure that "Ty" is an integral type, and that our
308 // value will fit into the specified type...
309 case ValID::ConstSIntVal: // Is it a constant pool reference??
310 if (Ty == Type::BoolTy) { // Special handling for boolean data
311 return ConstantBool::get(D.ConstPool64 != 0);
313 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
314 ThrowException("Symbolic constant pool value '" +
315 itostr(D.ConstPool64) + "' is invalid for type '" +
316 Ty->getDescription() + "'!");
317 return ConstantSInt::get(Ty, D.ConstPool64);
320 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
321 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
322 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
323 ThrowException("Integral constant pool reference is invalid!");
324 } else { // This is really a signed reference. Transmogrify.
325 return ConstantSInt::get(Ty, D.ConstPool64);
328 return ConstantUInt::get(Ty, D.UConstPool64);
331 case ValID::ConstStringVal: // Is it a string const pool reference?
332 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
336 case ValID::ConstFPVal: // Is it a floating point const pool reference?
337 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
338 ThrowException("FP constant invalid for type!!");
339 return ConstantFP::get(Ty, D.ConstPoolFP);
341 case ValID::ConstNullVal: // Is it a null value?
342 if (!Ty->isPointerType())
343 ThrowException("Cannot create a a non pointer null!");
344 return ConstantPointerNull::get(cast<PointerType>(Ty));
347 assert(0 && "Unhandled case!");
351 assert(0 && "Unhandled case!");
356 // getVal - This function is identical to getValNonImprovising, except that if a
357 // value is not already defined, it "improvises" by creating a placeholder var
358 // that looks and acts just like the requested variable. When the value is
359 // defined later, all uses of the placeholder variable are replaced with the
362 static Value *getVal(const Type *Ty, const ValID &D) {
363 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
365 // See if the value has already been defined...
366 Value *V = getValNonImprovising(Ty, D);
369 // If we reached here, we referenced either a symbol that we don't know about
370 // or an id number that hasn't been read yet. We may be referencing something
371 // forward, so just create an entry to be resolved later and get to it...
374 switch (Ty->getPrimitiveID()) {
375 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
376 default: d = new ValuePlaceHolder(Ty, D); break;
379 assert(d != 0 && "How did we not make something?");
381 InsertValue(d, CurMeth.LateResolveValues);
383 InsertValue(d, CurModule.LateResolveValues);
388 //===----------------------------------------------------------------------===//
389 // Code to handle forward references in instructions
390 //===----------------------------------------------------------------------===//
392 // This code handles the late binding needed with statements that reference
393 // values not defined yet... for example, a forward branch, or the PHI node for
396 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
397 // and back patchs after we are done.
400 // ResolveDefinitions - If we could not resolve some defs at parsing
401 // time (forward branches, phi functions for loops, etc...) resolve the
404 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
405 vector<ValueList> *FutureLateResolvers = 0) {
406 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
407 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
408 while (!LateResolvers[ty].empty()) {
409 Value *V = LateResolvers[ty].back();
410 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
412 LateResolvers[ty].pop_back();
413 ValID &DID = getValIDFromPlaceHolder(V);
415 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
417 V->replaceAllUsesWith(TheRealValue);
419 } else if (FutureLateResolvers) {
420 // Methods have their unresolved items forwarded to the module late
422 InsertValue(V, *FutureLateResolvers);
425 ThrowException("Reference to an invalid definition: '" +DID.getName()+
426 "' of type '" + V->getType()->getDescription() + "'",
427 getLineNumFromPlaceHolder(V));
429 ThrowException("Reference to an invalid definition: #" +
430 itostr(DID.Num) + " of type '" +
431 V->getType()->getDescription() + "'",
432 getLineNumFromPlaceHolder(V));
437 LateResolvers.clear();
440 // ResolveTypeTo - A brand new type was just declared. This means that (if
441 // name is not null) things referencing Name can be resolved. Otherwise, things
442 // refering to the number can be resolved. Do this now.
444 static void ResolveTypeTo(char *Name, const Type *ToTy) {
445 vector<PATypeHolder<Type> > &Types = inMethodScope() ?
446 CurMeth.Types : CurModule.Types;
449 if (Name) D = ValID::create(Name);
450 else D = ValID::create((int)Types.size());
452 map<ValID, PATypeHolder<Type> > &LateResolver = inMethodScope() ?
453 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
455 map<ValID, PATypeHolder<Type> >::iterator I = LateResolver.find(D);
456 if (I != LateResolver.end()) {
457 cast<DerivedType>(I->second.get())->refineAbstractTypeTo(ToTy);
458 LateResolver.erase(I);
462 // ResolveTypes - At this point, all types should be resolved. Any that aren't
465 static void ResolveTypes(map<ValID, PATypeHolder<Type> > &LateResolveTypes) {
466 if (!LateResolveTypes.empty()) {
467 const ValID &DID = LateResolveTypes.begin()->first;
469 if (DID.Type == ValID::NameVal)
470 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
472 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
477 // setValueName - Set the specified value to the name given. The name may be
478 // null potentially, in which case this is a noop. The string passed in is
479 // assumed to be a malloc'd string buffer, and is freed by this function.
481 // This function returns true if the value has already been defined, but is
482 // allowed to be redefined in the specified context. If the name is a new name
483 // for the typeplane, false is returned.
485 static bool setValueName(Value *V, char *NameStr) {
486 if (NameStr == 0) return false;
488 string Name(NameStr); // Copy string
489 free(NameStr); // Free old string
491 if (V->getType() == Type::VoidTy)
492 ThrowException("Can't assign name '" + Name +
493 "' to a null valued instruction!");
495 SymbolTable *ST = inMethodScope() ?
496 CurMeth.CurrentMethod->getSymbolTableSure() :
497 CurModule.CurrentModule->getSymbolTableSure();
499 Value *Existing = ST->lookup(V->getType(), Name);
500 if (Existing) { // Inserting a name that is already defined???
501 // There is only one case where this is allowed: when we are refining an
502 // opaque type. In this case, Existing will be an opaque type.
503 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
504 if (OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
505 // We ARE replacing an opaque type!
506 OpTy->refineAbstractTypeTo(cast<Type>(V));
511 // Otherwise, we are a simple redefinition of a value, check to see if it
512 // is defined the same as the old one...
513 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
514 if (Ty == cast<const Type>(V)) return true; // Yes, it's equal.
515 // cerr << "Type: " << Ty->getDescription() << " != "
516 // << cast<const Type>(V)->getDescription() << "!\n";
517 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
518 // We are allowed to redefine a global variable in two circumstances:
519 // 1. If at least one of the globals is uninitialized or
520 // 2. If both initializers have the same value.
522 // This can only be done if the const'ness of the vars is the same.
524 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
525 if (EGV->isConstant() == GV->isConstant() &&
526 (!EGV->hasInitializer() || !GV->hasInitializer() ||
527 EGV->getInitializer() == GV->getInitializer())) {
529 // Make sure the existing global version gets the initializer!
530 if (GV->hasInitializer() && !EGV->hasInitializer())
531 EGV->setInitializer(GV->getInitializer());
533 delete GV; // Destroy the duplicate!
534 return true; // They are equivalent!
538 ThrowException("Redefinition of value named '" + Name + "' in the '" +
539 V->getType()->getDescription() + "' type plane!");
542 V->setName(Name, ST);
547 //===----------------------------------------------------------------------===//
548 // Code for handling upreferences in type names...
551 // TypeContains - Returns true if Ty contains E in it.
553 static bool TypeContains(const Type *Ty, const Type *E) {
554 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
558 static vector<pair<unsigned, OpaqueType *> > UpRefs;
560 static PATypeHolder<Type> HandleUpRefs(const Type *ty) {
561 PATypeHolder<Type> Ty(ty);
562 UR_OUT("Type '" << ty->getDescription() <<
563 "' newly formed. Resolving upreferences.\n" <<
564 UpRefs.size() << " upreferences active!\n");
565 for (unsigned i = 0; i < UpRefs.size(); ) {
566 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
567 << UpRefs[i].second->getDescription() << ") = "
568 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
569 if (TypeContains(Ty, UpRefs[i].second)) {
570 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
571 UR_OUT(" Uplevel Ref Level = " << Level << endl);
572 if (Level == 0) { // Upreference should be resolved!
573 UR_OUT(" * Resolving upreference for "
574 << UpRefs[i].second->getDescription() << endl;
575 string OldName = UpRefs[i].second->getDescription());
576 UpRefs[i].second->refineAbstractTypeTo(Ty);
577 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
578 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
579 << (const void*)Ty << ", " << Ty->getDescription() << endl);
584 ++i; // Otherwise, no resolve, move on...
586 // FIXME: TODO: this should return the updated type
590 template <class TypeTy>
591 inline static void TypeDone(PATypeHolder<TypeTy> *Ty) {
593 ThrowException("Invalid upreference in type: " + (*Ty)->getDescription());
596 // newTH - Allocate a new type holder for the specified type
597 template <class TypeTy>
598 inline static PATypeHolder<TypeTy> *newTH(const TypeTy *Ty) {
599 return new PATypeHolder<TypeTy>(Ty);
601 template <class TypeTy>
602 inline static PATypeHolder<TypeTy> *newTH(const PATypeHolder<TypeTy> &TH) {
603 return new PATypeHolder<TypeTy>(TH);
607 //===----------------------------------------------------------------------===//
608 // RunVMAsmParser - Define an interface to this parser
609 //===----------------------------------------------------------------------===//
611 Module *RunVMAsmParser(const string &Filename, FILE *F) {
613 CurFilename = Filename;
614 llvmAsmlineno = 1; // Reset the current line number...
616 CurModule.CurrentModule = new Module(); // Allocate a new module to read
617 yyparse(); // Parse the file.
618 Module *Result = ParserResult;
619 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
630 std::pair<MethodArgument*,char*> *MethArgVal;
631 BasicBlock *BasicBlockVal;
632 TerminatorInst *TermInstVal;
633 Instruction *InstVal;
636 const Type *PrimType;
637 PATypeHolder<Type> *TypeVal;
640 std::list<std::pair<MethodArgument*,char*> > *MethodArgList;
641 std::vector<Value*> *ValueList;
642 std::list<PATypeHolder<Type> > *TypeList;
643 std::list<std::pair<Value*,
644 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
645 std::list<std::pair<Constant*, BasicBlock*> > *JumpTable;
646 std::vector<Constant*> *ConstVector;
655 char *StrVal; // This memory is strdup'd!
656 ValID ValIDVal; // strdup'd memory maybe!
658 Instruction::UnaryOps UnaryOpVal;
659 Instruction::BinaryOps BinaryOpVal;
660 Instruction::TermOps TermOpVal;
661 Instruction::MemoryOps MemOpVal;
662 Instruction::OtherOps OtherOpVal;
665 %type <ModuleVal> Module MethodList
666 %type <MethodVal> Method MethodProto MethodHeader BasicBlockList
667 %type <BasicBlockVal> BasicBlock InstructionList
668 %type <TermInstVal> BBTerminatorInst
669 %type <InstVal> Inst InstVal MemoryInst
670 %type <ConstVal> ConstVal
671 %type <ConstVector> ConstVector
672 %type <MethodArgList> ArgList ArgListH
673 %type <MethArgVal> ArgVal
674 %type <PHIList> PHIList
675 %type <ValueList> ValueRefList ValueRefListE // For call param lists
676 %type <ValueList> IndexList // For GEP derived indices
677 %type <TypeList> TypeListI ArgTypeListI
678 %type <JumpTable> JumpTable
679 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
681 // ValueRef - Unresolved reference to a definition or BB
682 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
683 %type <ValueVal> ResolvedVal // <type> <valref> pair
684 // Tokens and types for handling constant integer values
686 // ESINT64VAL - A negative number within long long range
687 %token <SInt64Val> ESINT64VAL
689 // EUINT64VAL - A positive number within uns. long long range
690 %token <UInt64Val> EUINT64VAL
691 %type <SInt64Val> EINT64VAL
693 %token <SIntVal> SINTVAL // Signed 32 bit ints...
694 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
695 %type <SIntVal> INTVAL
696 %token <FPVal> FPVAL // Float or Double constant
699 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
700 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
701 %token <TypeVal> OPAQUE
702 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
703 %token <PrimType> FLOAT DOUBLE TYPE LABEL
705 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
706 %type <StrVal> OptVAR_ID OptAssign
709 %token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE GLOBAL CONSTANT UNINIT
710 %token TO EXCEPT DOTDOTDOT STRING NULL_TOK CONST INTERNAL
712 // Basic Block Terminating Operators
713 %token <TermOpVal> RET BR SWITCH
716 %type <UnaryOpVal> UnaryOps // all the unary operators
717 %token <UnaryOpVal> NOT
720 %type <BinaryOpVal> BinaryOps // all the binary operators
721 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
722 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
724 // Memory Instructions
725 %token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
728 %type <OtherOpVal> ShiftOps
729 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
734 // Handle constant integer size restriction and conversion...
739 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
740 ThrowException("Value too large for type!");
745 EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
746 EINT64VAL : EUINT64VAL {
747 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
748 ThrowException("Value too large for type!");
752 // Operations that are notably excluded from this list include:
753 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
756 BinaryOps : ADD | SUB | MUL | DIV | REM | AND | OR | XOR
757 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
760 // These are some types that allow classification if we only want a particular
761 // thing... for example, only a signed, unsigned, or integral type.
762 SIntType : LONG | INT | SHORT | SBYTE
763 UIntType : ULONG | UINT | USHORT | UBYTE
764 IntType : SIntType | UIntType
765 FPType : FLOAT | DOUBLE
767 // OptAssign - Value producing statements have an optional assignment component
768 OptAssign : VAR_ID '=' {
775 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; }
777 //===----------------------------------------------------------------------===//
778 // Types includes all predefined types... except void, because it can only be
779 // used in specific contexts (method returning void for example). To have
780 // access to it, a user must explicitly use TypesV.
783 // TypesV includes all of 'Types', but it also includes the void type.
784 TypesV : Types | VOID { $$ = newTH($1); }
785 UpRTypesV : UpRTypes | VOID { $$ = newTH($1); }
792 // Derived types are added later...
794 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
795 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
796 UpRTypes : OPAQUE | PrimType { $$ = newTH($1); }
797 UpRTypes : ValueRef { // Named types are also simple types...
798 $$ = newTH(getTypeVal($1));
801 // Include derived types in the Types production.
803 UpRTypes : '\\' EUINT64VAL { // Type UpReference
804 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
805 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
806 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
807 $$ = newTH<Type>(OT);
808 UR_OUT("New Upreference!\n");
810 | UpRTypesV '(' ArgTypeListI ')' { // Method derived type?
811 vector<const Type*> Params;
812 mapto($3->begin(), $3->end(), std::back_inserter(Params),
813 std::mem_fun_ref(&PATypeHandle<Type>::get));
814 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
815 if (isVarArg) Params.pop_back();
817 $$ = newTH(HandleUpRefs(MethodType::get(*$1, Params, isVarArg)));
818 delete $3; // Delete the argument list
819 delete $1; // Delete the old type handle
821 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
822 $$ = newTH<Type>(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
825 | '{' TypeListI '}' { // Structure type?
826 vector<const Type*> Elements;
827 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
828 std::mem_fun_ref(&PATypeHandle<Type>::get));
830 $$ = newTH<Type>(HandleUpRefs(StructType::get(Elements)));
833 | '{' '}' { // Empty structure type?
834 $$ = newTH<Type>(StructType::get(vector<const Type*>()));
836 | UpRTypes '*' { // Pointer type?
837 $$ = newTH<Type>(HandleUpRefs(PointerType::get(*$1)));
841 // TypeList - Used for struct declarations and as a basis for method type
842 // declaration type lists
844 TypeListI : UpRTypes {
845 $$ = new list<PATypeHolder<Type> >();
846 $$->push_back(*$1); delete $1;
848 | TypeListI ',' UpRTypes {
849 ($$=$1)->push_back(*$3); delete $3;
852 // ArgTypeList - List of types for a method type declaration...
853 ArgTypeListI : TypeListI
854 | TypeListI ',' DOTDOTDOT {
855 ($$=$1)->push_back(Type::VoidTy);
858 ($$ = new list<PATypeHolder<Type> >())->push_back(Type::VoidTy);
861 $$ = new list<PATypeHolder<Type> >();
865 // ConstVal - The various declarations that go into the constant pool. This
866 // includes all forward declarations of types, constants, and functions.
868 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
869 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
871 ThrowException("Cannot make array constant with type: '" +
872 (*$1)->getDescription() + "'!");
873 const Type *ETy = ATy->getElementType();
874 int NumElements = ATy->getNumElements();
876 // Verify that we have the correct size...
877 if (NumElements != -1 && NumElements != (int)$3->size())
878 ThrowException("Type mismatch: constant sized array initialized with " +
879 utostr($3->size()) + " arguments, but has size of " +
880 itostr(NumElements) + "!");
882 // Verify all elements are correct type!
883 for (unsigned i = 0; i < $3->size(); i++) {
884 if (ETy != (*$3)[i]->getType())
885 ThrowException("Element #" + utostr(i) + " is not of type '" +
886 ETy->getDescription() +"' as required!\nIt is of type '"+
887 (*$3)[i]->getType()->getDescription() + "'.");
890 $$ = ConstantArray::get(ATy, *$3);
891 delete $1; delete $3;
894 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
896 ThrowException("Cannot make array constant with type: '" +
897 (*$1)->getDescription() + "'!");
899 int NumElements = ATy->getNumElements();
900 if (NumElements != -1 && NumElements != 0)
901 ThrowException("Type mismatch: constant sized array initialized with 0"
902 " arguments, but has size of " + itostr(NumElements) +"!");
903 $$ = ConstantArray::get(ATy, vector<Constant*>());
906 | Types 'c' STRINGCONSTANT {
907 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
909 ThrowException("Cannot make array constant with type: '" +
910 (*$1)->getDescription() + "'!");
912 int NumElements = ATy->getNumElements();
913 const Type *ETy = ATy->getElementType();
914 char *EndStr = UnEscapeLexed($3, true);
915 if (NumElements != -1 && NumElements != (EndStr-$3))
916 ThrowException("Can't build string constant of size " +
917 itostr((int)(EndStr-$3)) +
918 " when array has size " + itostr(NumElements) + "!");
919 vector<Constant*> Vals;
920 if (ETy == Type::SByteTy) {
921 for (char *C = $3; C != EndStr; ++C)
922 Vals.push_back(ConstantSInt::get(ETy, *C));
923 } else if (ETy == Type::UByteTy) {
924 for (char *C = $3; C != EndStr; ++C)
925 Vals.push_back(ConstantUInt::get(ETy, *C));
928 ThrowException("Cannot build string arrays of non byte sized elements!");
931 $$ = ConstantArray::get(ATy, Vals);
934 | Types '{' ConstVector '}' {
935 const StructType *STy = dyn_cast<const StructType>($1->get());
937 ThrowException("Cannot make struct constant with type: '" +
938 (*$1)->getDescription() + "'!");
939 // FIXME: TODO: Check to see that the constants are compatible with the type
941 $$ = ConstantStruct::get(STy, *$3);
942 delete $1; delete $3;
945 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
947 ThrowException("Cannot make null pointer constant with type: '" +
948 (*$1)->getDescription() + "'!");
950 $$ = ConstantPointerNull::get(PTy);
953 | Types SymbolicValueRef {
954 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
956 ThrowException("Global const reference must be a pointer type!");
958 Value *V = getValNonImprovising(Ty, $2);
960 // If this is an initializer for a constant pointer, which is referencing a
961 // (currently) undefined variable, create a stub now that shall be replaced
962 // in the future with the right type of variable.
965 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
966 const PointerType *PT = cast<PointerType>(Ty);
968 // First check to see if the forward references value is already created!
969 PerModuleInfo::GlobalRefsType::iterator I =
970 CurModule.GlobalRefs.find(make_pair(PT, $2));
972 if (I != CurModule.GlobalRefs.end()) {
973 V = I->second; // Placeholder already exists, use it...
975 // TODO: Include line number info by creating a subclass of
976 // TODO: GlobalVariable here that includes the said information!
978 // Create a placeholder for the global variable reference...
979 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
981 // Keep track of the fact that we have a forward ref to recycle it
982 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
984 // Must temporarily push this value into the module table...
985 CurModule.CurrentModule->getGlobalList().push_back(GV);
990 GlobalValue *GV = cast<GlobalValue>(V);
991 $$ = ConstantPointerRef::get(GV);
992 delete $1; // Free the type handle
996 ConstVal : SIntType EINT64VAL { // integral constants
997 if (!ConstantSInt::isValueValidForType($1, $2))
998 ThrowException("Constant value doesn't fit in type!");
999 $$ = ConstantSInt::get($1, $2);
1001 | UIntType EUINT64VAL { // integral constants
1002 if (!ConstantUInt::isValueValidForType($1, $2))
1003 ThrowException("Constant value doesn't fit in type!");
1004 $$ = ConstantUInt::get($1, $2);
1006 | BOOL TRUE { // Boolean constants
1007 $$ = ConstantBool::True;
1009 | BOOL FALSE { // Boolean constants
1010 $$ = ConstantBool::False;
1012 | FPType FPVAL { // Float & Double constants
1013 $$ = ConstantFP::get($1, $2);
1016 // ConstVector - A list of comma seperated constants.
1017 ConstVector : ConstVector ',' ConstVal {
1018 ($$ = $1)->push_back($3);
1021 $$ = new vector<Constant*>();
1026 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1027 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; }
1030 // ConstPool - Constants with optional names assigned to them.
1031 ConstPool : ConstPool OptAssign CONST ConstVal {
1032 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1035 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1036 // Eagerly resolve types. This is not an optimization, this is a
1037 // requirement that is due to the fact that we could have this:
1039 // %list = type { %list * }
1040 // %list = type { %list * } ; repeated type decl
1042 // If types are not resolved eagerly, then the two types will not be
1043 // determined to be the same type!
1045 ResolveTypeTo($2, $4->get());
1047 // TODO: FIXME when Type are not const
1048 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1049 // If this is not a redefinition of a type...
1051 InsertType($4->get(),
1052 inMethodScope() ? CurMeth.Types : CurModule.Types);
1058 | ConstPool MethodProto { // Method prototypes can be in const pool
1060 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1061 const Type *Ty = $5->getType();
1062 // Global declarations appear in Constant Pool
1063 Constant *Initializer = $5;
1064 if (Initializer == 0)
1065 ThrowException("Global value initializer is not a constant!");
1067 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1068 if (!setValueName(GV, $2)) { // If not redefining...
1069 CurModule.CurrentModule->getGlobalList().push_back(GV);
1070 int Slot = InsertValue(GV, CurModule.Values);
1073 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1075 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1076 (char*)GV->getName().c_str()));
1080 | ConstPool OptAssign OptInternal UNINIT GlobalType Types {
1081 const Type *Ty = *$6;
1082 // Global declarations appear in Constant Pool
1083 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1084 if (!setValueName(GV, $2)) { // If not redefining...
1085 CurModule.CurrentModule->getGlobalList().push_back(GV);
1086 int Slot = InsertValue(GV, CurModule.Values);
1089 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1091 assert(GV->hasName() && "Not named and not numbered!?");
1092 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1093 (char*)GV->getName().c_str()));
1097 | /* empty: end of list */ {
1101 //===----------------------------------------------------------------------===//
1102 // Rules to match Modules
1103 //===----------------------------------------------------------------------===//
1105 // Module rule: Capture the result of parsing the whole file into a result
1108 Module : MethodList {
1109 $$ = ParserResult = $1;
1110 CurModule.ModuleDone();
1113 // MethodList - A list of methods, preceeded by a constant pool.
1115 MethodList : MethodList Method {
1117 assert($2->getParent() == 0 && "Method already in module!");
1118 $1->getMethodList().push_back($2);
1119 CurMeth.MethodDone();
1121 | MethodList MethodProto {
1124 | ConstPool IMPLEMENTATION {
1125 $$ = CurModule.CurrentModule;
1126 // Resolve circular types before we parse the body of the module
1127 ResolveTypes(CurModule.LateResolveTypes);
1131 //===----------------------------------------------------------------------===//
1132 // Rules to match Method Headers
1133 //===----------------------------------------------------------------------===//
1135 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
1137 ArgVal : Types OptVAR_ID {
1138 $$ = new pair<MethodArgument*,char*>(new MethodArgument(*$1), $2);
1139 delete $1; // Delete the type handle..
1142 ArgListH : ArgVal ',' ArgListH {
1144 $3->push_front(*$1);
1148 $$ = new list<pair<MethodArgument*,char*> >();
1149 $$->push_front(*$1);
1153 $$ = new list<pair<MethodArgument*, char*> >();
1154 $$->push_front(pair<MethodArgument*,char*>(
1155 new MethodArgument(Type::VoidTy), 0));
1158 ArgList : ArgListH {
1165 MethodHeaderH : OptInternal TypesV STRINGCONSTANT '(' ArgList ')' {
1167 string MethodName($3);
1169 vector<const Type*> ParamTypeList;
1171 for (list<pair<MethodArgument*,char*> >::iterator I = $5->begin();
1172 I != $5->end(); ++I)
1173 ParamTypeList.push_back(I->first->getType());
1175 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1176 if (isVarArg) ParamTypeList.pop_back();
1178 const MethodType *MT = MethodType::get(*$2, ParamTypeList, isVarArg);
1179 const PointerType *PMT = PointerType::get(MT);
1183 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1184 if (Value *V = ST->lookup(PMT, MethodName)) { // Method already in symtab?
1185 M = cast<Method>(V);
1187 // Yes it is. If this is the case, either we need to be a forward decl,
1188 // or it needs to be.
1189 if (!CurMeth.isDeclare && !M->isExternal())
1190 ThrowException("Redefinition of method '" + MethodName + "'!");
1192 // If we found a preexisting method prototype, remove it from the module,
1193 // so that we don't get spurious conflicts with global & local variables.
1195 CurModule.CurrentModule->getMethodList().remove(M);
1199 if (M == 0) { // Not already defined?
1200 M = new Method(MT, $1, MethodName);
1201 InsertValue(M, CurModule.Values);
1202 CurModule.DeclareNewGlobalValue(M, ValID::create($3));
1204 free($3); // Free strdup'd memory!
1206 CurMeth.MethodStart(M);
1208 // Add all of the arguments we parsed to the method...
1209 if ($5 && !CurMeth.isDeclare) { // Is null if empty...
1210 Method::ArgumentListType &ArgList = M->getArgumentList();
1212 for (list<pair<MethodArgument*, char*> >::iterator I = $5->begin();
1213 I != $5->end(); ++I) {
1214 if (setValueName(I->first, I->second)) { // Insert into symtab...
1215 assert(0 && "No arg redef allowed!");
1218 InsertValue(I->first);
1219 ArgList.push_back(I->first);
1221 delete $5; // We're now done with the argument list
1223 // If we are a declaration, we should free the memory for the argument list!
1224 for (list<pair<MethodArgument*, char*> >::iterator I = $5->begin();
1225 I != $5->end(); ++I)
1226 if (I->second) free(I->second); // Free the memory for the name...
1227 delete $5; // Free the memory for the list itself
1231 MethodHeader : MethodHeaderH ConstPool BEGINTOK {
1232 $$ = CurMeth.CurrentMethod;
1234 // Resolve circular types before we parse the body of the method.
1235 ResolveTypes(CurMeth.LateResolveTypes);
1238 Method : BasicBlockList END {
1242 MethodProto : DECLARE { CurMeth.isDeclare = true; } MethodHeaderH {
1243 $$ = CurMeth.CurrentMethod;
1244 assert($$->getParent() == 0 && "Method already in module!");
1245 CurModule.CurrentModule->getMethodList().push_back($$);
1246 CurMeth.MethodDone();
1249 //===----------------------------------------------------------------------===//
1250 // Rules to match Basic Blocks
1251 //===----------------------------------------------------------------------===//
1253 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1254 $$ = ValID::create($1);
1257 $$ = ValID::create($1);
1259 | FPVAL { // Perhaps it's an FP constant?
1260 $$ = ValID::create($1);
1263 $$ = ValID::create((int64_t)1);
1266 $$ = ValID::create((int64_t)0);
1269 $$ = ValID::createNull();
1273 | STRINGCONSTANT { // Quoted strings work too... especially for methods
1274 $$ = ValID::create_conststr($1);
1278 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1281 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1282 $$ = ValID::create($1);
1284 | VAR_ID { // Is it a named reference...?
1285 $$ = ValID::create($1);
1288 // ValueRef - A reference to a definition... either constant or symbolic
1289 ValueRef : SymbolicValueRef | ConstValueRef
1292 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1293 // type immediately preceeds the value reference, and allows complex constant
1294 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1295 ResolvedVal : Types ValueRef {
1296 $$ = getVal(*$1, $2); delete $1;
1300 BasicBlockList : BasicBlockList BasicBlock {
1301 ($$ = $1)->getBasicBlocks().push_back($2);
1303 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
1304 ($$ = $1)->getBasicBlocks().push_back($2);
1308 // Basic blocks are terminated by branching instructions:
1309 // br, br/cc, switch, ret
1311 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1312 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1315 $1->getInstList().push_back($3);
1319 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1320 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1323 $2->getInstList().push_back($4);
1324 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1330 InstructionList : InstructionList Inst {
1331 $1->getInstList().push_back($2);
1335 $$ = new BasicBlock();
1338 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1339 $$ = new ReturnInst($2);
1341 | RET VOID { // Return with no result...
1342 $$ = new ReturnInst();
1344 | BR LABEL ValueRef { // Unconditional Branch...
1345 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1346 } // Conditional Branch...
1347 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1348 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1349 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1350 getVal(Type::BoolTy, $3));
1352 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1353 SwitchInst *S = new SwitchInst(getVal($2, $3),
1354 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1357 list<pair<Constant*, BasicBlock*> >::iterator I = $8->begin(),
1359 for (; I != end; ++I)
1360 S->dest_push_back(I->first, I->second);
1362 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1363 EXCEPT ResolvedVal {
1364 const PointerType *PMTy;
1365 const MethodType *Ty;
1367 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1368 !(Ty = dyn_cast<MethodType>(PMTy->getElementType()))) {
1369 // Pull out the types of all of the arguments...
1370 vector<const Type*> ParamTypes;
1372 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1373 ParamTypes.push_back((*I)->getType());
1376 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1377 if (isVarArg) ParamTypes.pop_back();
1379 Ty = MethodType::get($2->get(), ParamTypes, isVarArg);
1380 PMTy = PointerType::get(Ty);
1384 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1386 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1387 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1389 if (Normal == 0 || Except == 0)
1390 ThrowException("Invoke instruction without label destinations!");
1392 // Create the call node...
1393 if (!$5) { // Has no arguments?
1394 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1395 } else { // Has arguments?
1396 // Loop through MethodType's arguments and ensure they are specified
1399 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1400 MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1401 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1403 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1404 if ((*ArgI)->getType() != *I)
1405 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1406 (*I)->getDescription() + "'!");
1408 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1409 ThrowException("Invalid number of parameters detected!");
1411 $$ = new InvokeInst(V, Normal, Except, *$5);
1418 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1420 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1422 ThrowException("May only switch on a constant pool value!");
1424 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1426 | IntType ConstValueRef ',' LABEL ValueRef {
1427 $$ = new list<pair<Constant*, BasicBlock*> >();
1428 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1431 ThrowException("May only switch on a constant pool value!");
1433 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1436 Inst : OptAssign InstVal {
1437 // Is this definition named?? if so, assign the name...
1438 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1443 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1444 $$ = new list<pair<Value*, BasicBlock*> >();
1445 $$->push_back(make_pair(getVal(*$1, $3),
1446 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1449 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1451 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1452 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1456 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1457 $$ = new vector<Value*>();
1460 | ValueRefList ',' ResolvedVal {
1465 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1466 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
1468 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1469 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1471 ThrowException("binary operator returned null!");
1474 | UnaryOps ResolvedVal {
1475 $$ = UnaryOperator::create($1, $2);
1477 ThrowException("unary operator returned null!");
1479 | ShiftOps ResolvedVal ',' ResolvedVal {
1480 if ($4->getType() != Type::UByteTy)
1481 ThrowException("Shift amount must be ubyte!");
1482 $$ = new ShiftInst($1, $2, $4);
1484 | CAST ResolvedVal TO Types {
1485 $$ = new CastInst($2, *$4);
1489 const Type *Ty = $2->front().first->getType();
1490 $$ = new PHINode(Ty);
1491 while ($2->begin() != $2->end()) {
1492 if ($2->front().first->getType() != Ty)
1493 ThrowException("All elements of a PHI node must be of the same type!");
1494 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1497 delete $2; // Free the list...
1499 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1500 const PointerType *PMTy;
1501 const MethodType *Ty;
1503 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1504 !(Ty = dyn_cast<MethodType>(PMTy->getElementType()))) {
1505 // Pull out the types of all of the arguments...
1506 vector<const Type*> ParamTypes;
1508 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1509 ParamTypes.push_back((*I)->getType());
1512 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1513 if (isVarArg) ParamTypes.pop_back();
1515 Ty = MethodType::get($2->get(), ParamTypes, isVarArg);
1516 PMTy = PointerType::get(Ty);
1520 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1522 // Create the call node...
1523 if (!$5) { // Has no arguments?
1524 $$ = new CallInst(V, vector<Value*>());
1525 } else { // Has arguments?
1526 // Loop through MethodType's arguments and ensure they are specified
1529 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1530 MethodType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1531 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1533 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1534 if ((*ArgI)->getType() != *I)
1535 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1536 (*I)->getDescription() + "'!");
1538 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1539 ThrowException("Invalid number of parameters detected!");
1541 $$ = new CallInst(V, *$5);
1550 // IndexList - List of indices for GEP based instructions...
1551 IndexList : ',' ValueRefList {
1554 $$ = new vector<Value*>();
1557 MemoryInst : MALLOC Types {
1558 $$ = new MallocInst(PointerType::get(*$2));
1561 | MALLOC Types ',' UINT ValueRef {
1562 const Type *Ty = PointerType::get(*$2);
1563 $$ = new MallocInst(Ty, getVal($4, $5));
1567 $$ = new AllocaInst(PointerType::get(*$2));
1570 | ALLOCA Types ',' UINT ValueRef {
1571 const Type *Ty = PointerType::get(*$2);
1572 Value *ArrSize = getVal($4, $5);
1573 $$ = new AllocaInst(Ty, ArrSize);
1576 | FREE ResolvedVal {
1577 if (!$2->getType()->isPointerType())
1578 ThrowException("Trying to free nonpointer type " +
1579 $2->getType()->getDescription() + "!");
1580 $$ = new FreeInst($2);
1583 | LOAD Types ValueRef IndexList {
1584 if (!(*$2)->isPointerType())
1585 ThrowException("Can't load from nonpointer type: " +
1586 (*$2)->getDescription());
1587 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1588 ThrowException("Invalid indices for load instruction!");
1590 $$ = new LoadInst(getVal(*$2, $3), *$4);
1591 delete $4; // Free the vector...
1594 | STORE ResolvedVal ',' Types ValueRef IndexList {
1595 if (!(*$4)->isPointerType())
1596 ThrowException("Can't store to a nonpointer type: " +
1597 (*$4)->getDescription());
1598 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1600 ThrowException("Can't store into that field list!");
1601 if (ElTy != $2->getType())
1602 ThrowException("Can't store '" + $2->getType()->getDescription() +
1603 "' into space of type '" + ElTy->getDescription() + "'!");
1604 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1605 delete $4; delete $6;
1607 | GETELEMENTPTR Types ValueRef IndexList {
1608 if (!(*$2)->isPointerType())
1609 ThrowException("getelementptr insn requires pointer operand!");
1610 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1611 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1612 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1613 delete $2; delete $4;
1617 int yyerror(const char *ErrorMsg) {
1618 ThrowException(string("Parse error: ") + ErrorMsg);