1 //===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
3 // This file implements the bison parser for LLVM assembly languages files.
5 //===------------------------------------------------------------------------=//
8 #include "ParserInternals.h"
9 #include "llvm/SymbolTable.h"
10 #include "llvm/Module.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iPHINode.h"
14 #include "Support/STLExtras.h"
15 #include "Support/DepthFirstIterator.h"
27 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
28 int yylex(); // declaration" of xxx warnings.
31 static Module *ParserResult;
34 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
35 // relating to upreferences in the input stream.
37 //#define DEBUG_UPREFS 1
39 #define UR_OUT(X) std::cerr << X
44 #define YYERROR_VERBOSE 1
46 // This contains info used when building the body of a function. It is
47 // destroyed when the function is completed.
49 typedef vector<Value *> ValueList; // Numbered defs
50 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
51 vector<ValueList> *FutureLateResolvers = 0);
53 static struct PerModuleInfo {
54 Module *CurrentModule;
55 vector<ValueList> Values; // Module level numbered definitions
56 vector<ValueList> LateResolveValues;
57 vector<PATypeHolder> Types;
58 map<ValID, PATypeHolder> LateResolveTypes;
60 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
61 // references to global values. Global values may be referenced before they
62 // are defined, and if so, the temporary object that they represent is held
63 // here. This is used for forward references of ConstantPointerRefs.
65 typedef map<pair<const PointerType *, ValID>, GlobalVariable*> GlobalRefsType;
66 GlobalRefsType GlobalRefs;
69 // If we could not resolve some functions at function compilation time
70 // (calls to functions before they are defined), resolve them now... Types
71 // are resolved when the constant pool has been completely parsed.
73 ResolveDefinitions(LateResolveValues);
75 // Check to make sure that all global value forward references have been
78 if (!GlobalRefs.empty()) {
79 string UndefinedReferences = "Unresolved global references exist:\n";
81 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
83 UndefinedReferences += " " + I->first.first->getDescription() + " " +
84 I->first.second.getName() + "\n";
86 ThrowException(UndefinedReferences);
89 Values.clear(); // Clear out function local definitions
95 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
96 // is used to remove things from the forward declaration map, resolving them
97 // to the correct thing as needed.
99 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
100 // Check to see if there is a forward reference to this global variable...
101 // if there is, eliminate it and patch the reference to use the new def'n.
102 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), D));
104 if (I != GlobalRefs.end()) {
105 GlobalVariable *OldGV = I->second; // Get the placeholder...
106 I->first.second.destroy(); // Free string memory if neccesary
108 // Loop over all of the uses of the GlobalValue. The only thing they are
109 // allowed to be is ConstantPointerRef's.
110 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
111 while (!OldGV->use_empty()) {
112 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
113 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
114 assert(CPR->getValue() == OldGV && "Something isn't happy");
116 // Change the const pool reference to point to the real global variable
117 // now. This should drop a use from the OldGV.
118 CPR->mutateReferences(OldGV, GV);
121 // Remove OldGV from the module...
122 CurrentModule->getGlobalList().remove(OldGV);
123 delete OldGV; // Delete the old placeholder
125 // Remove the map entry for the global now that it has been created...
132 static struct PerFunctionInfo {
133 Function *CurrentFunction; // Pointer to current function being created
135 vector<ValueList> Values; // Keep track of numbered definitions
136 vector<ValueList> LateResolveValues;
137 vector<PATypeHolder> Types;
138 map<ValID, PATypeHolder> LateResolveTypes;
139 bool isDeclare; // Is this function a forward declararation?
141 inline PerFunctionInfo() {
146 inline ~PerFunctionInfo() {}
148 inline void FunctionStart(Function *M) {
152 void FunctionDone() {
153 // If we could not resolve some blocks at parsing time (forward branches)
154 // resolve the branches now...
155 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
157 Values.clear(); // Clear out function local definitions
162 } CurMeth; // Info for the current function...
164 static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
167 //===----------------------------------------------------------------------===//
168 // Code to handle definitions of all the types
169 //===----------------------------------------------------------------------===//
171 static int InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
172 if (D->hasName()) return -1; // Is this a numbered definition?
174 // Yes, insert the value into the value table...
175 unsigned type = D->getType()->getUniqueID();
176 if (ValueTab.size() <= type)
177 ValueTab.resize(type+1, ValueList());
178 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
179 ValueTab[type].push_back(D);
180 return ValueTab[type].size()-1;
183 // TODO: FIXME when Type are not const
184 static void InsertType(const Type *Ty, vector<PATypeHolder> &Types) {
188 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
190 case ValID::NumberVal: { // Is it a numbered definition?
191 unsigned Num = (unsigned)D.Num;
193 // Module constants occupy the lowest numbered slots...
194 if (Num < CurModule.Types.size())
195 return CurModule.Types[Num];
197 Num -= CurModule.Types.size();
199 // Check that the number is within bounds...
200 if (Num <= CurMeth.Types.size())
201 return CurMeth.Types[Num];
204 case ValID::NameVal: { // Is it a named definition?
206 SymbolTable *SymTab = 0;
207 if (inFunctionScope()) SymTab = CurMeth.CurrentFunction->getSymbolTable();
208 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
211 // Symbol table doesn't automatically chain yet... because the function
212 // hasn't been added to the module...
214 SymTab = CurModule.CurrentModule->getSymbolTable();
216 N = SymTab->lookup(Type::TypeTy, Name);
220 D.destroy(); // Free old strdup'd memory...
221 return cast<const Type>(N);
224 ThrowException("Internal parser error: Invalid symbol type reference!");
227 // If we reached here, we referenced either a symbol that we don't know about
228 // or an id number that hasn't been read yet. We may be referencing something
229 // forward, so just create an entry to be resolved later and get to it...
231 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
233 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
234 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
236 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
237 if (I != LateResolver.end()) {
241 Type *Typ = OpaqueType::get();
242 LateResolver.insert(make_pair(D, Typ));
246 static Value *lookupInSymbolTable(const Type *Ty, const string &Name) {
247 SymbolTable *SymTab =
248 inFunctionScope() ? CurMeth.CurrentFunction->getSymbolTable() :
249 CurModule.CurrentModule->getSymbolTable();
250 return SymTab ? SymTab->lookup(Ty, Name) : 0;
253 // getValNonImprovising - Look up the value specified by the provided type and
254 // the provided ValID. If the value exists and has already been defined, return
255 // it. Otherwise return null.
257 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
258 if (isa<FunctionType>(Ty))
259 ThrowException("Functions are not values and "
260 "must be referenced as pointers");
263 case ValID::NumberVal: { // Is it a numbered definition?
264 unsigned type = Ty->getUniqueID();
265 unsigned Num = (unsigned)D.Num;
267 // Module constants occupy the lowest numbered slots...
268 if (type < CurModule.Values.size()) {
269 if (Num < CurModule.Values[type].size())
270 return CurModule.Values[type][Num];
272 Num -= CurModule.Values[type].size();
275 // Make sure that our type is within bounds
276 if (CurMeth.Values.size() <= type) return 0;
278 // Check that the number is within bounds...
279 if (CurMeth.Values[type].size() <= Num) return 0;
281 return CurMeth.Values[type][Num];
284 case ValID::NameVal: { // Is it a named definition?
285 Value *N = lookupInSymbolTable(Ty, string(D.Name));
286 if (N == 0) return 0;
288 D.destroy(); // Free old strdup'd memory...
292 // Check to make sure that "Ty" is an integral type, and that our
293 // value will fit into the specified type...
294 case ValID::ConstSIntVal: // Is it a constant pool reference??
295 if (Ty == Type::BoolTy) { // Special handling for boolean data
296 return ConstantBool::get(D.ConstPool64 != 0);
298 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
299 ThrowException("Signed integral constant '" +
300 itostr(D.ConstPool64) + "' is invalid for type '" +
301 Ty->getDescription() + "'!");
302 return ConstantSInt::get(Ty, D.ConstPool64);
305 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
306 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
307 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
308 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
309 "' is invalid or out of range!");
310 } else { // This is really a signed reference. Transmogrify.
311 return ConstantSInt::get(Ty, D.ConstPool64);
314 return ConstantUInt::get(Ty, D.UConstPool64);
317 case ValID::ConstFPVal: // Is it a floating point const pool reference?
318 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
319 ThrowException("FP constant invalid for type!!");
320 return ConstantFP::get(Ty, D.ConstPoolFP);
322 case ValID::ConstNullVal: // Is it a null value?
323 if (!isa<PointerType>(Ty))
324 ThrowException("Cannot create a a non pointer null!");
325 return ConstantPointerNull::get(cast<PointerType>(Ty));
328 assert(0 && "Unhandled case!");
332 assert(0 && "Unhandled case!");
337 // getVal - This function is identical to getValNonImprovising, except that if a
338 // value is not already defined, it "improvises" by creating a placeholder var
339 // that looks and acts just like the requested variable. When the value is
340 // defined later, all uses of the placeholder variable are replaced with the
343 static Value *getVal(const Type *Ty, const ValID &D) {
344 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
346 // See if the value has already been defined...
347 Value *V = getValNonImprovising(Ty, D);
350 // If we reached here, we referenced either a symbol that we don't know about
351 // or an id number that hasn't been read yet. We may be referencing something
352 // forward, so just create an entry to be resolved later and get to it...
355 switch (Ty->getPrimitiveID()) {
356 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
357 default: d = new ValuePlaceHolder(Ty, D); break;
360 assert(d != 0 && "How did we not make something?");
361 if (inFunctionScope())
362 InsertValue(d, CurMeth.LateResolveValues);
364 InsertValue(d, CurModule.LateResolveValues);
369 //===----------------------------------------------------------------------===//
370 // Code to handle forward references in instructions
371 //===----------------------------------------------------------------------===//
373 // This code handles the late binding needed with statements that reference
374 // values not defined yet... for example, a forward branch, or the PHI node for
377 // This keeps a table (CurMeth.LateResolveValues) of all such forward references
378 // and back patchs after we are done.
381 // ResolveDefinitions - If we could not resolve some defs at parsing
382 // time (forward branches, phi functions for loops, etc...) resolve the
385 static void ResolveDefinitions(vector<ValueList> &LateResolvers,
386 vector<ValueList> *FutureLateResolvers) {
387 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
388 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
389 while (!LateResolvers[ty].empty()) {
390 Value *V = LateResolvers[ty].back();
391 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
393 LateResolvers[ty].pop_back();
394 ValID &DID = getValIDFromPlaceHolder(V);
396 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
398 V->replaceAllUsesWith(TheRealValue);
400 } else if (FutureLateResolvers) {
401 // Functions have their unresolved items forwarded to the module late
403 InsertValue(V, *FutureLateResolvers);
405 if (DID.Type == ValID::NameVal)
406 ThrowException("Reference to an invalid definition: '" +DID.getName()+
407 "' of type '" + V->getType()->getDescription() + "'",
408 getLineNumFromPlaceHolder(V));
410 ThrowException("Reference to an invalid definition: #" +
411 itostr(DID.Num) + " of type '" +
412 V->getType()->getDescription() + "'",
413 getLineNumFromPlaceHolder(V));
418 LateResolvers.clear();
421 // ResolveTypeTo - A brand new type was just declared. This means that (if
422 // name is not null) things referencing Name can be resolved. Otherwise, things
423 // refering to the number can be resolved. Do this now.
425 static void ResolveTypeTo(char *Name, const Type *ToTy) {
426 vector<PATypeHolder> &Types = inFunctionScope() ?
427 CurMeth.Types : CurModule.Types;
430 if (Name) D = ValID::create(Name);
431 else D = ValID::create((int)Types.size());
433 map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
434 CurMeth.LateResolveTypes : CurModule.LateResolveTypes;
436 map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
437 if (I != LateResolver.end()) {
438 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
439 LateResolver.erase(I);
443 // ResolveTypes - At this point, all types should be resolved. Any that aren't
446 static void ResolveTypes(map<ValID, PATypeHolder> &LateResolveTypes) {
447 if (!LateResolveTypes.empty()) {
448 const ValID &DID = LateResolveTypes.begin()->first;
450 if (DID.Type == ValID::NameVal)
451 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
453 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
458 // setValueName - Set the specified value to the name given. The name may be
459 // null potentially, in which case this is a noop. The string passed in is
460 // assumed to be a malloc'd string buffer, and is freed by this function.
462 // This function returns true if the value has already been defined, but is
463 // allowed to be redefined in the specified context. If the name is a new name
464 // for the typeplane, false is returned.
466 static bool setValueName(Value *V, char *NameStr) {
467 if (NameStr == 0) return false;
469 string Name(NameStr); // Copy string
470 free(NameStr); // Free old string
472 if (V->getType() == Type::VoidTy)
473 ThrowException("Can't assign name '" + Name +
474 "' to a null valued instruction!");
476 SymbolTable *ST = inFunctionScope() ?
477 CurMeth.CurrentFunction->getSymbolTableSure() :
478 CurModule.CurrentModule->getSymbolTableSure();
480 Value *Existing = ST->lookup(V->getType(), Name);
481 if (Existing) { // Inserting a name that is already defined???
482 // There is only one case where this is allowed: when we are refining an
483 // opaque type. In this case, Existing will be an opaque type.
484 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
485 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
486 // We ARE replacing an opaque type!
487 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
492 // Otherwise, we are a simple redefinition of a value, check to see if it
493 // is defined the same as the old one...
494 if (const Type *Ty = dyn_cast<const Type>(Existing)) {
495 if (Ty == cast<const Type>(V)) return true; // Yes, it's equal.
496 // std::cerr << "Type: " << Ty->getDescription() << " != "
497 // << cast<const Type>(V)->getDescription() << "!\n";
498 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
499 // We are allowed to redefine a global variable in two circumstances:
500 // 1. If at least one of the globals is uninitialized or
501 // 2. If both initializers have the same value.
503 // This can only be done if the const'ness of the vars is the same.
505 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
506 if (EGV->isConstant() == GV->isConstant() &&
507 (!EGV->hasInitializer() || !GV->hasInitializer() ||
508 EGV->getInitializer() == GV->getInitializer())) {
510 // Make sure the existing global version gets the initializer!
511 if (GV->hasInitializer() && !EGV->hasInitializer())
512 EGV->setInitializer(GV->getInitializer());
514 delete GV; // Destroy the duplicate!
515 return true; // They are equivalent!
519 ThrowException("Redefinition of value named '" + Name + "' in the '" +
520 V->getType()->getDescription() + "' type plane!");
523 V->setName(Name, ST);
528 //===----------------------------------------------------------------------===//
529 // Code for handling upreferences in type names...
532 // TypeContains - Returns true if Ty contains E in it.
534 static bool TypeContains(const Type *Ty, const Type *E) {
535 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
539 static vector<pair<unsigned, OpaqueType *> > UpRefs;
541 static PATypeHolder HandleUpRefs(const Type *ty) {
543 UR_OUT("Type '" << ty->getDescription() <<
544 "' newly formed. Resolving upreferences.\n" <<
545 UpRefs.size() << " upreferences active!\n");
546 for (unsigned i = 0; i < UpRefs.size(); ) {
547 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
548 << UpRefs[i].second->getDescription() << ") = "
549 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
550 if (TypeContains(Ty, UpRefs[i].second)) {
551 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
552 UR_OUT(" Uplevel Ref Level = " << Level << endl);
553 if (Level == 0) { // Upreference should be resolved!
554 UR_OUT(" * Resolving upreference for "
555 << UpRefs[i].second->getDescription() << endl;
556 string OldName = UpRefs[i].second->getDescription());
557 UpRefs[i].second->refineAbstractTypeTo(Ty);
558 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
559 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
560 << (const void*)Ty << ", " << Ty->getDescription() << endl);
565 ++i; // Otherwise, no resolve, move on...
567 // FIXME: TODO: this should return the updated type
572 //===----------------------------------------------------------------------===//
573 // RunVMAsmParser - Define an interface to this parser
574 //===----------------------------------------------------------------------===//
576 Module *RunVMAsmParser(const string &Filename, FILE *F) {
578 CurFilename = Filename;
579 llvmAsmlineno = 1; // Reset the current line number...
581 CurModule.CurrentModule = new Module(); // Allocate a new module to read
582 yyparse(); // Parse the file.
583 Module *Result = ParserResult;
584 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
594 Function *FunctionVal;
595 std::pair<Argument*, char*> *ArgVal;
596 BasicBlock *BasicBlockVal;
597 TerminatorInst *TermInstVal;
598 Instruction *InstVal;
601 const Type *PrimType;
602 PATypeHolder *TypeVal;
605 std::list<std::pair<Argument*,char*> > *ArgList;
606 std::vector<Value*> *ValueList;
607 std::list<PATypeHolder> *TypeList;
608 std::list<std::pair<Value*,
609 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
610 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
611 std::vector<Constant*> *ConstVector;
620 char *StrVal; // This memory is strdup'd!
621 ValID ValIDVal; // strdup'd memory maybe!
623 Instruction::BinaryOps BinaryOpVal;
624 Instruction::TermOps TermOpVal;
625 Instruction::MemoryOps MemOpVal;
626 Instruction::OtherOps OtherOpVal;
629 %type <ModuleVal> Module FunctionList
630 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
631 %type <BasicBlockVal> BasicBlock InstructionList
632 %type <TermInstVal> BBTerminatorInst
633 %type <InstVal> Inst InstVal MemoryInst
634 %type <ConstVal> ConstVal ConstExpr
635 %type <ConstVector> ConstVector
636 %type <ArgList> ArgList ArgListH
637 %type <ArgVal> ArgVal
638 %type <PHIList> PHIList
639 %type <ValueList> ValueRefList ValueRefListE // For call param lists
640 %type <ValueList> IndexList // For GEP derived indices
641 %type <TypeList> TypeListI ArgTypeListI
642 %type <JumpTable> JumpTable
643 %type <BoolVal> GlobalType OptInternal // GLOBAL or CONSTANT? Intern?
645 // ValueRef - Unresolved reference to a definition or BB
646 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
647 %type <ValueVal> ResolvedVal // <type> <valref> pair
648 // Tokens and types for handling constant integer values
650 // ESINT64VAL - A negative number within long long range
651 %token <SInt64Val> ESINT64VAL
653 // EUINT64VAL - A positive number within uns. long long range
654 %token <UInt64Val> EUINT64VAL
655 %type <SInt64Val> EINT64VAL
657 %token <SIntVal> SINTVAL // Signed 32 bit ints...
658 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
659 %type <SIntVal> INTVAL
660 %token <FPVal> FPVAL // Float or Double constant
663 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
664 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
665 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
666 %token <PrimType> FLOAT DOUBLE TYPE LABEL
668 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
669 %type <StrVal> OptVAR_ID OptAssign FuncName
672 %token IMPLEMENTATION TRUE FALSE BEGINTOK ENDTOK DECLARE GLOBAL CONSTANT UNINIT
673 %token TO EXCEPT DOTDOTDOT STRING NULL_TOK CONST INTERNAL OPAQUE NOT
675 // Basic Block Terminating Operators
676 %token <TermOpVal> RET BR SWITCH
679 %type <BinaryOpVal> BinaryOps // all the binary operators
680 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
681 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
683 // Memory Instructions
684 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
687 %type <OtherOpVal> ShiftOps
688 %token <OtherOpVal> PHI CALL INVOKE CAST SHL SHR
693 // Handle constant integer size restriction and conversion...
698 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
699 ThrowException("Value too large for type!");
704 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
705 EINT64VAL : EUINT64VAL {
706 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
707 ThrowException("Value too large for type!");
711 // Operations that are notably excluded from this list include:
712 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
714 BinaryOps : ADD | SUB | MUL | DIV | REM | AND | OR | XOR;
715 BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
716 ShiftOps : SHL | SHR;
718 // These are some types that allow classification if we only want a particular
719 // thing... for example, only a signed, unsigned, or integral type.
720 SIntType : LONG | INT | SHORT | SBYTE;
721 UIntType : ULONG | UINT | USHORT | UBYTE;
722 IntType : SIntType | UIntType;
723 FPType : FLOAT | DOUBLE;
725 // OptAssign - Value producing statements have an optional assignment component
726 OptAssign : VAR_ID '=' {
733 OptInternal : INTERNAL { $$ = true; } | /*empty*/ { $$ = false; };
735 //===----------------------------------------------------------------------===//
736 // Types includes all predefined types... except void, because it can only be
737 // used in specific contexts (function returning void for example). To have
738 // access to it, a user must explicitly use TypesV.
741 // TypesV includes all of 'Types', but it also includes the void type.
742 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
743 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
747 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
752 // Derived types are added later...
754 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
755 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
757 $$ = new PATypeHolder(OpaqueType::get());
760 $$ = new PATypeHolder($1);
762 UpRTypes : ValueRef { // Named types are also simple types...
763 $$ = new PATypeHolder(getTypeVal($1));
766 // Include derived types in the Types production.
768 UpRTypes : '\\' EUINT64VAL { // Type UpReference
769 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
770 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
771 UpRefs.push_back(make_pair((unsigned)$2, OT)); // Add to vector...
772 $$ = new PATypeHolder(OT);
773 UR_OUT("New Upreference!\n");
775 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
776 vector<const Type*> Params;
777 mapto($3->begin(), $3->end(), std::back_inserter(Params),
778 std::mem_fun_ref(&PATypeHandle<Type>::get));
779 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
780 if (isVarArg) Params.pop_back();
782 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
783 delete $3; // Delete the argument list
784 delete $1; // Delete the old type handle
786 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
787 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
790 | '{' TypeListI '}' { // Structure type?
791 vector<const Type*> Elements;
792 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
793 std::mem_fun_ref(&PATypeHandle<Type>::get));
795 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
798 | '{' '}' { // Empty structure type?
799 $$ = new PATypeHolder(StructType::get(vector<const Type*>()));
801 | UpRTypes '*' { // Pointer type?
802 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
806 // TypeList - Used for struct declarations and as a basis for function type
807 // declaration type lists
809 TypeListI : UpRTypes {
810 $$ = new list<PATypeHolder>();
811 $$->push_back(*$1); delete $1;
813 | TypeListI ',' UpRTypes {
814 ($$=$1)->push_back(*$3); delete $3;
817 // ArgTypeList - List of types for a function type declaration...
818 ArgTypeListI : TypeListI
819 | TypeListI ',' DOTDOTDOT {
820 ($$=$1)->push_back(Type::VoidTy);
823 ($$ = new list<PATypeHolder>())->push_back(Type::VoidTy);
826 $$ = new list<PATypeHolder>();
829 // ConstVal - The various declarations that go into the constant pool. This
830 // includes all forward declarations of types, constants, and functions.
832 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
833 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
835 ThrowException("Cannot make array constant with type: '" +
836 (*$1)->getDescription() + "'!");
837 const Type *ETy = ATy->getElementType();
838 int NumElements = ATy->getNumElements();
840 // Verify that we have the correct size...
841 if (NumElements != -1 && NumElements != (int)$3->size())
842 ThrowException("Type mismatch: constant sized array initialized with " +
843 utostr($3->size()) + " arguments, but has size of " +
844 itostr(NumElements) + "!");
846 // Verify all elements are correct type!
847 for (unsigned i = 0; i < $3->size(); i++) {
848 if (ETy != (*$3)[i]->getType())
849 ThrowException("Element #" + utostr(i) + " is not of type '" +
850 ETy->getDescription() +"' as required!\nIt is of type '"+
851 (*$3)[i]->getType()->getDescription() + "'.");
854 $$ = ConstantArray::get(ATy, *$3);
855 delete $1; delete $3;
858 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
860 ThrowException("Cannot make array constant with type: '" +
861 (*$1)->getDescription() + "'!");
863 int NumElements = ATy->getNumElements();
864 if (NumElements != -1 && NumElements != 0)
865 ThrowException("Type mismatch: constant sized array initialized with 0"
866 " arguments, but has size of " + itostr(NumElements) +"!");
867 $$ = ConstantArray::get(ATy, vector<Constant*>());
870 | Types 'c' STRINGCONSTANT {
871 const ArrayType *ATy = dyn_cast<const ArrayType>($1->get());
873 ThrowException("Cannot make array constant with type: '" +
874 (*$1)->getDescription() + "'!");
876 int NumElements = ATy->getNumElements();
877 const Type *ETy = ATy->getElementType();
878 char *EndStr = UnEscapeLexed($3, true);
879 if (NumElements != -1 && NumElements != (EndStr-$3))
880 ThrowException("Can't build string constant of size " +
881 itostr((int)(EndStr-$3)) +
882 " when array has size " + itostr(NumElements) + "!");
883 vector<Constant*> Vals;
884 if (ETy == Type::SByteTy) {
885 for (char *C = $3; C != EndStr; ++C)
886 Vals.push_back(ConstantSInt::get(ETy, *C));
887 } else if (ETy == Type::UByteTy) {
888 for (char *C = $3; C != EndStr; ++C)
889 Vals.push_back(ConstantUInt::get(ETy, *C));
892 ThrowException("Cannot build string arrays of non byte sized elements!");
895 $$ = ConstantArray::get(ATy, Vals);
898 | Types '{' ConstVector '}' {
899 const StructType *STy = dyn_cast<const StructType>($1->get());
901 ThrowException("Cannot make struct constant with type: '" +
902 (*$1)->getDescription() + "'!");
903 // FIXME: TODO: Check to see that the constants are compatible with the type
905 $$ = ConstantStruct::get(STy, *$3);
906 delete $1; delete $3;
909 const PointerType *PTy = dyn_cast<const PointerType>($1->get());
911 ThrowException("Cannot make null pointer constant with type: '" +
912 (*$1)->getDescription() + "'!");
914 $$ = ConstantPointerNull::get(PTy);
917 | Types SymbolicValueRef {
918 const PointerType *Ty = dyn_cast<const PointerType>($1->get());
920 ThrowException("Global const reference must be a pointer type!");
922 // ConstExprs can exist in the body of a function, thus creating
923 // ConstantPointerRefs whenever they refer to a variable. Because we are in
924 // the context of a function, getValNonImprovising will search the functions
925 // symbol table instead of the module symbol table for the global symbol,
926 // which throws things all off. To get around this, we just tell
927 // getValNonImprovising that we are at global scope here.
929 Function *SavedCurFn = CurMeth.CurrentFunction;
930 CurMeth.CurrentFunction = 0;
932 Value *V = getValNonImprovising(Ty, $2);
934 CurMeth.CurrentFunction = SavedCurFn;
937 // If this is an initializer for a constant pointer, which is referencing a
938 // (currently) undefined variable, create a stub now that shall be replaced
939 // in the future with the right type of variable.
942 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
943 const PointerType *PT = cast<PointerType>(Ty);
945 // First check to see if the forward references value is already created!
946 PerModuleInfo::GlobalRefsType::iterator I =
947 CurModule.GlobalRefs.find(make_pair(PT, $2));
949 if (I != CurModule.GlobalRefs.end()) {
950 V = I->second; // Placeholder already exists, use it...
952 // TODO: Include line number info by creating a subclass of
953 // TODO: GlobalVariable here that includes the said information!
955 // Create a placeholder for the global variable reference...
956 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
958 // Keep track of the fact that we have a forward ref to recycle it
959 CurModule.GlobalRefs.insert(make_pair(make_pair(PT, $2), GV));
961 // Must temporarily push this value into the module table...
962 CurModule.CurrentModule->getGlobalList().push_back(GV);
967 GlobalValue *GV = cast<GlobalValue>(V);
968 $$ = ConstantPointerRef::get(GV);
969 delete $1; // Free the type handle
976 ConstExpr: Types CAST ConstVal {
977 $$ = ConstantExpr::getCast($3, $1->get());
980 | Types GETELEMENTPTR '(' ConstVal IndexList ')' {
981 if (!isa<PointerType>($4->getType()))
982 ThrowException("GetElementPtr requires a pointer operand!");
985 GetElementPtrInst::getIndexedType($4->getType(), *$5, true);
987 ThrowException("Index list invalid for constant getelementptr!");
988 if (PointerType::get(IdxTy) != $1->get())
989 ThrowException("Declared type of constant getelementptr is incorrect!");
991 vector<Constant*> IdxVec;
992 for (unsigned i = 0, e = $5->size(); i != e; ++i)
993 if (Constant *C = dyn_cast<Constant>((*$5)[i]))
996 ThrowException("Indices to constant getelementptr must be constants!");
1000 $$ = ConstantExpr::getGetElementPtr($4, IdxVec);
1003 | Types BinaryOps ConstVal ',' ConstVal {
1004 if ($3->getType() != $5->getType())
1005 ThrowException("Binary operator types must match!");
1006 if ($1->get() != $3->getType())
1007 ThrowException("Return type of binary constant must match arguments!");
1008 $$ = ConstantExpr::get($2, $3, $5);
1011 | Types ShiftOps ConstVal ',' ConstVal {
1012 if ($1->get() != $3->getType())
1013 ThrowException("Return type of shift constant must match argument!");
1014 if ($5->getType() != Type::UByteTy)
1015 ThrowException("Shift count for shift constant must be unsigned byte!");
1017 $$ = ConstantExpr::get($2, $3, $5);
1022 ConstVal : SIntType EINT64VAL { // integral constants
1023 if (!ConstantSInt::isValueValidForType($1, $2))
1024 ThrowException("Constant value doesn't fit in type!");
1025 $$ = ConstantSInt::get($1, $2);
1027 | UIntType EUINT64VAL { // integral constants
1028 if (!ConstantUInt::isValueValidForType($1, $2))
1029 ThrowException("Constant value doesn't fit in type!");
1030 $$ = ConstantUInt::get($1, $2);
1032 | BOOL TRUE { // Boolean constants
1033 $$ = ConstantBool::True;
1035 | BOOL FALSE { // Boolean constants
1036 $$ = ConstantBool::False;
1038 | FPType FPVAL { // Float & Double constants
1039 $$ = ConstantFP::get($1, $2);
1042 // ConstVector - A list of comma seperated constants.
1043 ConstVector : ConstVector ',' ConstVal {
1044 ($$ = $1)->push_back($3);
1047 $$ = new vector<Constant*>();
1052 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1053 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1056 //===----------------------------------------------------------------------===//
1057 // Rules to match Modules
1058 //===----------------------------------------------------------------------===//
1060 // Module rule: Capture the result of parsing the whole file into a result
1063 Module : FunctionList {
1064 $$ = ParserResult = $1;
1065 CurModule.ModuleDone();
1068 // FunctionList - A list of functions, preceeded by a constant pool.
1070 FunctionList : FunctionList Function {
1072 assert($2->getParent() == 0 && "Function already in module!");
1073 $1->getFunctionList().push_back($2);
1074 CurMeth.FunctionDone();
1076 | FunctionList FunctionProto {
1079 | FunctionList IMPLEMENTATION {
1083 $$ = CurModule.CurrentModule;
1084 // Resolve circular types before we parse the body of the module
1085 ResolveTypes(CurModule.LateResolveTypes);
1088 // ConstPool - Constants with optional names assigned to them.
1089 ConstPool : ConstPool OptAssign CONST ConstVal {
1090 if (setValueName($4, $2)) { assert(0 && "No redefinitions allowed!"); }
1093 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1094 // Eagerly resolve types. This is not an optimization, this is a
1095 // requirement that is due to the fact that we could have this:
1097 // %list = type { %list * }
1098 // %list = type { %list * } ; repeated type decl
1100 // If types are not resolved eagerly, then the two types will not be
1101 // determined to be the same type!
1103 ResolveTypeTo($2, $4->get());
1105 // TODO: FIXME when Type are not const
1106 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1107 // If this is not a redefinition of a type...
1109 InsertType($4->get(),
1110 inFunctionScope() ? CurMeth.Types : CurModule.Types);
1116 | ConstPool FunctionProto { // Function prototypes can be in const pool
1118 | ConstPool OptAssign OptInternal GlobalType ConstVal {
1119 const Type *Ty = $5->getType();
1120 // Global declarations appear in Constant Pool
1121 Constant *Initializer = $5;
1122 if (Initializer == 0)
1123 ThrowException("Global value initializer is not a constant!");
1125 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1126 if (!setValueName(GV, $2)) { // If not redefining...
1127 CurModule.CurrentModule->getGlobalList().push_back(GV);
1128 int Slot = InsertValue(GV, CurModule.Values);
1131 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1133 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1134 (char*)GV->getName().c_str()));
1138 | ConstPool OptAssign OptInternal UNINIT GlobalType Types {
1139 const Type *Ty = *$6;
1140 // Global declarations appear in Constant Pool
1141 GlobalVariable *GV = new GlobalVariable(Ty, $5, $3);
1142 if (!setValueName(GV, $2)) { // If not redefining...
1143 CurModule.CurrentModule->getGlobalList().push_back(GV);
1144 int Slot = InsertValue(GV, CurModule.Values);
1147 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1149 assert(GV->hasName() && "Not named and not numbered!?");
1150 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1151 (char*)GV->getName().c_str()));
1156 | /* empty: end of list */ {
1160 //===----------------------------------------------------------------------===//
1161 // Rules to match Function Headers
1162 //===----------------------------------------------------------------------===//
1164 OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; };
1166 ArgVal : Types OptVAR_ID {
1167 $$ = new pair<Argument*, char*>(new Argument(*$1), $2);
1168 delete $1; // Delete the type handle..
1171 ArgListH : ArgVal ',' ArgListH {
1173 $3->push_front(*$1);
1177 $$ = new list<pair<Argument*,char*> >();
1178 $$->push_front(*$1);
1182 $$ = new list<pair<Argument*, char*> >();
1183 $$->push_front(pair<Argument*,char*>(new Argument(Type::VoidTy), 0));
1186 ArgList : ArgListH {
1193 FuncName : VAR_ID | STRINGCONSTANT;
1195 FunctionHeaderH : OptInternal TypesV FuncName '(' ArgList ')' {
1197 string FunctionName($3);
1199 vector<const Type*> ParamTypeList;
1201 for (list<pair<Argument*,char*> >::iterator I = $5->begin();
1202 I != $5->end(); ++I)
1203 ParamTypeList.push_back(I->first->getType());
1205 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1206 if (isVarArg) ParamTypeList.pop_back();
1208 const FunctionType *MT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1209 const PointerType *PMT = PointerType::get(MT);
1213 if (SymbolTable *ST = CurModule.CurrentModule->getSymbolTable()) {
1214 // Is the function already in symtab?
1215 if (Value *V = ST->lookup(PMT, FunctionName)) {
1216 M = cast<Function>(V);
1218 // Yes it is. If this is the case, either we need to be a forward decl,
1219 // or it needs to be.
1220 if (!CurMeth.isDeclare && !M->isExternal())
1221 ThrowException("Redefinition of function '" + FunctionName + "'!");
1223 // Make sure that we keep track of the internal marker, even if there was
1224 // a previous "declare".
1226 M->setInternalLinkage(true);
1228 // If we found a preexisting function prototype, remove it from the
1229 // module, so that we don't get spurious conflicts with global & local
1232 CurModule.CurrentModule->getFunctionList().remove(M);
1236 if (M == 0) { // Not already defined?
1237 M = new Function(MT, $1, FunctionName);
1238 InsertValue(M, CurModule.Values);
1239 CurModule.DeclareNewGlobalValue(M, ValID::create($3));
1241 free($3); // Free strdup'd memory!
1243 CurMeth.FunctionStart(M);
1245 // Add all of the arguments we parsed to the function...
1246 if ($5 && !CurMeth.isDeclare) { // Is null if empty...
1247 for (list<pair<Argument*, char*> >::iterator I = $5->begin();
1248 I != $5->end(); ++I) {
1249 if (setValueName(I->first, I->second)) { // Insert into symtab...
1250 assert(0 && "No arg redef allowed!");
1253 InsertValue(I->first);
1254 M->getArgumentList().push_back(I->first);
1256 delete $5; // We're now done with the argument list
1258 // If we are a declaration, we should free the memory for the argument list!
1259 for (list<pair<Argument*, char*> >::iterator I = $5->begin(), E = $5->end();
1261 if (I->second) free(I->second); // Free the memory for the name...
1262 delete I->first; // Free the unused function argument
1264 delete $5; // Free the memory for the list itself
1268 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1270 FunctionHeader : FunctionHeaderH BEGIN {
1271 $$ = CurMeth.CurrentFunction;
1273 // Resolve circular types before we parse the body of the function.
1274 ResolveTypes(CurMeth.LateResolveTypes);
1277 END : ENDTOK | '}'; // Allow end of '}' to end a function
1279 Function : BasicBlockList END {
1283 FunctionProto : DECLARE { CurMeth.isDeclare = true; } FunctionHeaderH {
1284 $$ = CurMeth.CurrentFunction;
1285 assert($$->getParent() == 0 && "Function already in module!");
1286 CurModule.CurrentModule->getFunctionList().push_back($$);
1287 CurMeth.FunctionDone();
1290 //===----------------------------------------------------------------------===//
1291 // Rules to match Basic Blocks
1292 //===----------------------------------------------------------------------===//
1294 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1295 $$ = ValID::create($1);
1298 $$ = ValID::create($1);
1300 | FPVAL { // Perhaps it's an FP constant?
1301 $$ = ValID::create($1);
1304 $$ = ValID::create((int64_t)1);
1307 $$ = ValID::create((int64_t)0);
1310 $$ = ValID::createNull();
1314 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1317 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1318 $$ = ValID::create($1);
1320 | VAR_ID { // Is it a named reference...?
1321 $$ = ValID::create($1);
1324 // ValueRef - A reference to a definition... either constant or symbolic
1325 ValueRef : SymbolicValueRef | ConstValueRef;
1328 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1329 // type immediately preceeds the value reference, and allows complex constant
1330 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1331 ResolvedVal : Types ValueRef {
1332 $$ = getVal(*$1, $2); delete $1;
1338 BasicBlockList : BasicBlockList BasicBlock {
1339 ($$ = $1)->getBasicBlockList().push_back($2);
1341 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1342 ($$ = $1)->getBasicBlockList().push_back($2);
1346 // Basic blocks are terminated by branching instructions:
1347 // br, br/cc, switch, ret
1349 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1350 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1353 $1->getInstList().push_back($3);
1357 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1358 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1361 $2->getInstList().push_back($4);
1362 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1368 InstructionList : InstructionList Inst {
1369 $1->getInstList().push_back($2);
1373 $$ = new BasicBlock();
1376 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1377 $$ = new ReturnInst($2);
1379 | RET VOID { // Return with no result...
1380 $$ = new ReturnInst();
1382 | BR LABEL ValueRef { // Unconditional Branch...
1383 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1384 } // Conditional Branch...
1385 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1386 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1387 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1388 getVal(Type::BoolTy, $3));
1390 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1391 SwitchInst *S = new SwitchInst(getVal($2, $3),
1392 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1395 vector<pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1398 S->dest_push_back(I->first, I->second);
1400 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1401 EXCEPT ResolvedVal {
1402 const PointerType *PMTy;
1403 const FunctionType *Ty;
1405 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1406 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1407 // Pull out the types of all of the arguments...
1408 vector<const Type*> ParamTypes;
1410 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1411 ParamTypes.push_back((*I)->getType());
1414 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1415 if (isVarArg) ParamTypes.pop_back();
1417 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1418 PMTy = PointerType::get(Ty);
1422 Value *V = getVal(PMTy, $3); // Get the function we're calling...
1424 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1425 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1427 if (Normal == 0 || Except == 0)
1428 ThrowException("Invoke instruction without label destinations!");
1430 // Create the call node...
1431 if (!$5) { // Has no arguments?
1432 $$ = new InvokeInst(V, Normal, Except, vector<Value*>());
1433 } else { // Has arguments?
1434 // Loop through FunctionType's arguments and ensure they are specified
1437 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1438 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1439 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1441 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1442 if ((*ArgI)->getType() != *I)
1443 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1444 (*I)->getDescription() + "'!");
1446 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1447 ThrowException("Invalid number of parameters detected!");
1449 $$ = new InvokeInst(V, Normal, Except, *$5);
1456 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1458 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1460 ThrowException("May only switch on a constant pool value!");
1462 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1464 | IntType ConstValueRef ',' LABEL ValueRef {
1465 $$ = new vector<pair<Constant*, BasicBlock*> >();
1466 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1469 ThrowException("May only switch on a constant pool value!");
1471 $$->push_back(make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1474 Inst : OptAssign InstVal {
1475 // Is this definition named?? if so, assign the name...
1476 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1481 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1482 $$ = new list<pair<Value*, BasicBlock*> >();
1483 $$->push_back(make_pair(getVal(*$1, $3),
1484 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1487 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1489 $1->push_back(make_pair(getVal($1->front().first->getType(), $4),
1490 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1494 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1495 $$ = new vector<Value*>();
1498 | ValueRefList ',' ResolvedVal {
1503 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1504 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1506 InstVal : BinaryOps Types ValueRef ',' ValueRef {
1507 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1509 ThrowException("binary operator returned null!");
1513 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1514 << " Replacing with 'xor'.\n";
1516 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1518 ThrowException("Expected integral type for not instruction!");
1520 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1522 ThrowException("Could not create a xor instruction!");
1524 | ShiftOps ResolvedVal ',' ResolvedVal {
1525 if ($4->getType() != Type::UByteTy)
1526 ThrowException("Shift amount must be ubyte!");
1527 $$ = new ShiftInst($1, $2, $4);
1529 | CAST ResolvedVal TO Types {
1530 $$ = new CastInst($2, *$4);
1534 const Type *Ty = $2->front().first->getType();
1535 $$ = new PHINode(Ty);
1536 while ($2->begin() != $2->end()) {
1537 if ($2->front().first->getType() != Ty)
1538 ThrowException("All elements of a PHI node must be of the same type!");
1539 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1542 delete $2; // Free the list...
1544 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1545 const PointerType *PMTy;
1546 const FunctionType *Ty;
1548 if (!(PMTy = dyn_cast<PointerType>($2->get())) ||
1549 !(Ty = dyn_cast<FunctionType>(PMTy->getElementType()))) {
1550 // Pull out the types of all of the arguments...
1551 vector<const Type*> ParamTypes;
1553 for (vector<Value*>::iterator I = $5->begin(), E = $5->end(); I!=E; ++I)
1554 ParamTypes.push_back((*I)->getType());
1557 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1558 if (isVarArg) ParamTypes.pop_back();
1560 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1561 PMTy = PointerType::get(Ty);
1565 Value *V = getVal(PMTy, $3); // Get the function we're calling...
1567 // Create the call node...
1568 if (!$5) { // Has no arguments?
1569 // Make sure no arguments is a good thing!
1570 if (Ty->getNumParams() != 0)
1571 ThrowException("No arguments passed to a function that "
1572 "expects arguments!");
1574 $$ = new CallInst(V, vector<Value*>());
1575 } else { // Has arguments?
1576 // Loop through FunctionType's arguments and ensure they are specified
1579 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1580 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1581 vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1583 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1584 if ((*ArgI)->getType() != *I)
1585 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1586 (*I)->getDescription() + "'!");
1588 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1589 ThrowException("Invalid number of parameters detected!");
1591 $$ = new CallInst(V, *$5);
1600 // IndexList - List of indices for GEP based instructions...
1601 IndexList : ',' ValueRefList {
1604 $$ = new vector<Value*>();
1607 MemoryInst : MALLOC Types {
1608 $$ = new MallocInst(PointerType::get(*$2));
1611 | MALLOC Types ',' UINT ValueRef {
1612 const Type *Ty = PointerType::get(*$2);
1613 $$ = new MallocInst(Ty, getVal($4, $5));
1617 $$ = new AllocaInst(PointerType::get(*$2));
1620 | ALLOCA Types ',' UINT ValueRef {
1621 const Type *Ty = PointerType::get(*$2);
1622 Value *ArrSize = getVal($4, $5);
1623 $$ = new AllocaInst(Ty, ArrSize);
1626 | FREE ResolvedVal {
1627 if (!isa<PointerType>($2->getType()))
1628 ThrowException("Trying to free nonpointer type " +
1629 $2->getType()->getDescription() + "!");
1630 $$ = new FreeInst($2);
1633 | LOAD Types ValueRef IndexList {
1634 if (!isa<PointerType>($2->get()))
1635 ThrowException("Can't load from nonpointer type: " +
1636 (*$2)->getDescription());
1637 if (LoadInst::getIndexedType(*$2, *$4) == 0)
1638 ThrowException("Invalid indices for load instruction!");
1640 $$ = new LoadInst(getVal(*$2, $3), *$4);
1641 delete $4; // Free the vector...
1644 | STORE ResolvedVal ',' Types ValueRef IndexList {
1645 if (!isa<PointerType>($4->get()))
1646 ThrowException("Can't store to a nonpointer type: " +
1647 (*$4)->getDescription());
1648 const Type *ElTy = StoreInst::getIndexedType(*$4, *$6);
1650 ThrowException("Can't store into that field list!");
1651 if (ElTy != $2->getType())
1652 ThrowException("Can't store '" + $2->getType()->getDescription() +
1653 "' into space of type '" + ElTy->getDescription() + "'!");
1654 $$ = new StoreInst($2, getVal(*$4, $5), *$6);
1655 delete $4; delete $6;
1657 | GETELEMENTPTR Types ValueRef IndexList {
1658 if (!isa<PointerType>($2->get()))
1659 ThrowException("getelementptr insn requires pointer operand!");
1660 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1661 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1662 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1663 delete $2; delete $4;
1667 int yyerror(const char *ErrorMsg) {
1668 string where = string((CurFilename == "-")? string("<stdin>") : CurFilename)
1669 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1670 string errMsg = string(ErrorMsg) + string("\n") + where + " while reading ";
1671 if (yychar == YYEMPTY)
1672 errMsg += "end-of-file.";
1674 errMsg += "token: '" + string(llvmAsmtext, llvmAsmleng) + "'";
1675 ThrowException(errMsg);