1 //===-- Execution.cpp - Implement code to simulate the program ------------===//
3 // This file contains the actual instruction interpreter.
5 //===----------------------------------------------------------------------===//
7 #include "Interpreter.h"
8 #include "ExecutionAnnotations.h"
9 #include "llvm/iOther.h"
10 #include "llvm/iTerminators.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/Type.h"
13 #include "llvm/ConstPoolVals.h"
14 #include "llvm/Assembly/Writer.h"
15 #include "llvm/Support/DataTypes.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/GlobalVariable.h"
19 // Create a TargetData structure to handle memory addressing and size/alignment
22 static TargetData TD("lli Interpreter");
24 //===----------------------------------------------------------------------===//
25 // Value Manipulation code
26 //===----------------------------------------------------------------------===//
28 static unsigned getOperandSlot(Value *V) {
29 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
30 assert(SN && "Operand does not have a slot number annotation!");
34 #define GET_CONST_VAL(TY, CLASS) \
35 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(CPV)->getValue(); break
37 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
38 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(V)) {
40 switch (CPV->getType()->getPrimitiveID()) {
41 GET_CONST_VAL(Bool , ConstPoolBool);
42 GET_CONST_VAL(UByte , ConstPoolUInt);
43 GET_CONST_VAL(SByte , ConstPoolSInt);
44 GET_CONST_VAL(UShort , ConstPoolUInt);
45 GET_CONST_VAL(Short , ConstPoolSInt);
46 GET_CONST_VAL(UInt , ConstPoolUInt);
47 GET_CONST_VAL(Int , ConstPoolSInt);
48 GET_CONST_VAL(ULong , ConstPoolUInt);
49 GET_CONST_VAL(Long , ConstPoolSInt);
50 GET_CONST_VAL(Float , ConstPoolFP);
51 GET_CONST_VAL(Double , ConstPoolFP);
52 case Type::PointerTyID:
53 if (isa<ConstPoolPointerNull>(CPV)) {
54 Result.PointerVal = 0;
55 } else if (ConstPoolPointerRef *CPR =dyn_cast<ConstPoolPointerRef>(CPV)) {
56 assert(0 && "Not implemented!");
58 assert(0 && "Unknown constant pointer type!");
62 cout << "ERROR: Constant unimp for type: " << CPV->getType() << endl;
65 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
66 GlobalAddress *Address =
67 (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
69 Result.PointerVal = (GenericValue*)Address->Ptr;
72 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
73 return SF.Values[TyP][getOperandSlot(V)];
77 static void printOperandInfo(Value *V, ExecutionContext &SF) {
78 if (isa<ConstPoolVal>(V)) {
79 cout << "Constant Pool Value\n";
80 } else if (isa<GlobalValue>(V)) {
81 cout << "Global Value\n";
83 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
84 unsigned Slot = getOperandSlot(V);
85 cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
86 << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF << endl;
92 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
93 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
95 //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << endl;
96 SF.Values[TyP][getOperandSlot(V)] = Val;
100 //===----------------------------------------------------------------------===//
101 // Annotation Wrangling code
102 //===----------------------------------------------------------------------===//
104 void Interpreter::initializeExecutionEngine() {
105 AnnotationManager::registerAnnotationFactory(MethodInfoAID,
106 &MethodInfo::Create);
107 AnnotationManager::registerAnnotationFactory(GlobalAddressAID,
108 &GlobalAddress::Create);
111 // InitializeMemory - Recursive function to apply a ConstPool value into the
112 // specified memory location...
114 static void InitializeMemory(ConstPoolVal *Init, char *Addr) {
115 #define INITIALIZE_MEMORY(TYID, CLASS, TY) \
116 case Type::TYID##TyID: { \
117 TY Tmp = cast<CLASS>(Init)->getValue(); \
118 memcpy(Addr, &Tmp, sizeof(TY)); \
121 switch (Init->getType()->getPrimitiveID()) {
122 INITIALIZE_MEMORY(Bool , ConstPoolBool, bool);
123 INITIALIZE_MEMORY(UByte , ConstPoolUInt, unsigned char);
124 INITIALIZE_MEMORY(SByte , ConstPoolSInt, signed char);
125 INITIALIZE_MEMORY(UShort , ConstPoolUInt, unsigned short);
126 INITIALIZE_MEMORY(Short , ConstPoolSInt, signed short);
127 INITIALIZE_MEMORY(UInt , ConstPoolUInt, unsigned int);
128 INITIALIZE_MEMORY(Int , ConstPoolSInt, signed int);
129 INITIALIZE_MEMORY(ULong , ConstPoolUInt, uint64_t);
130 INITIALIZE_MEMORY(Long , ConstPoolSInt, int64_t);
131 INITIALIZE_MEMORY(Float , ConstPoolFP , float);
132 INITIALIZE_MEMORY(Double , ConstPoolFP , double);
133 #undef INITIALIZE_MEMORY
135 case Type::ArrayTyID: {
136 ConstPoolArray *CPA = cast<ConstPoolArray>(Init);
137 const vector<Use> &Val = CPA->getValues();
138 unsigned ElementSize =
139 TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
140 for (unsigned i = 0; i < Val.size(); ++i)
141 InitializeMemory(cast<ConstPoolVal>(Val[i].get()), Addr+i*ElementSize);
145 case Type::StructTyID: {
146 ConstPoolStruct *CPS = cast<ConstPoolStruct>(Init);
147 const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
148 const vector<Use> &Val = CPS->getValues();
149 for (unsigned i = 0; i < Val.size(); ++i)
150 InitializeMemory(cast<ConstPoolVal>(Val[i].get()),
151 Addr+SL->MemberOffsets[i]);
155 case Type::PointerTyID:
156 if (isa<ConstPoolPointerNull>(Init)) {
158 } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(Init)) {
159 GlobalAddress *Address =
160 (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
161 *(void**)Addr = (GenericValue*)Address->Ptr;
163 assert(0 && "Unknown Constant pointer type!");
168 cout << "Bad Type: " << Init->getType()->getDescription() << endl;
169 assert(0 && "Unknown constant type to initialize memory with!");
173 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
174 assert(AID == GlobalAddressAID);
176 // This annotation will only be created on GlobalValue objects...
177 GlobalValue *GVal = cast<GlobalValue>((Value*)O);
179 if (isa<Method>(GVal)) {
180 // The GlobalAddress object for a method is just a pointer to method itself.
181 // Don't delete it when the annotation is gone though!
182 return new GlobalAddress(GVal, false);
185 // Handle the case of a global variable...
186 assert(isa<GlobalVariable>(GVal) &&
187 "Global value found that isn't a method or global variable!");
188 GlobalVariable *GV = cast<GlobalVariable>(GVal);
190 // First off, we must allocate space for the global variable to point at...
191 const Type *Ty = GV->getType()->getValueType(); // Type to be allocated
192 unsigned NumElements = 1;
194 if (isa<ArrayType>(Ty) && cast<ArrayType>(Ty)->isUnsized()) {
195 assert(GV->hasInitializer() && "Const val must have an initializer!");
196 // Allocating a unsized array type?
197 Ty = cast<const ArrayType>(Ty)->getElementType(); // Get the actual type...
199 // Get the number of elements being allocated by the array...
200 NumElements =cast<ConstPoolArray>(GV->getInitializer())->getValues().size();
203 // Allocate enough memory to hold the type...
204 void *Addr = malloc(NumElements * TD.getTypeSize(Ty));
205 assert(Addr != 0 && "Null pointer returned by malloc!");
207 // Initialize the memory if there is an initializer...
208 if (GV->hasInitializer())
209 InitializeMemory(GV->getInitializer(), (char*)Addr);
211 return new GlobalAddress(Addr, true); // Simply invoke the ctor
215 //===----------------------------------------------------------------------===//
216 // Binary Instruction Implementations
217 //===----------------------------------------------------------------------===//
219 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
220 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
221 #define IMPLEMENT_BINARY_PTR_OPERATOR(OP) \
222 case Type::PointerTyID: Dest.PointerVal = \
223 (GenericValue*)((unsigned long)Src1.PointerVal OP (unsigned long)Src2.PointerVal); break
225 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
226 const Type *Ty, ExecutionContext &SF) {
228 switch (Ty->getPrimitiveID()) {
229 IMPLEMENT_BINARY_OPERATOR(+, UByte);
230 IMPLEMENT_BINARY_OPERATOR(+, SByte);
231 IMPLEMENT_BINARY_OPERATOR(+, UShort);
232 IMPLEMENT_BINARY_OPERATOR(+, Short);
233 IMPLEMENT_BINARY_OPERATOR(+, UInt);
234 IMPLEMENT_BINARY_OPERATOR(+, Int);
235 IMPLEMENT_BINARY_OPERATOR(+, ULong);
236 IMPLEMENT_BINARY_OPERATOR(+, Long);
237 IMPLEMENT_BINARY_OPERATOR(+, Float);
238 IMPLEMENT_BINARY_OPERATOR(+, Double);
239 IMPLEMENT_BINARY_PTR_OPERATOR(+);
241 cout << "Unhandled type for Add instruction: " << Ty << endl;
246 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
247 const Type *Ty, ExecutionContext &SF) {
249 switch (Ty->getPrimitiveID()) {
250 IMPLEMENT_BINARY_OPERATOR(-, UByte);
251 IMPLEMENT_BINARY_OPERATOR(-, SByte);
252 IMPLEMENT_BINARY_OPERATOR(-, UShort);
253 IMPLEMENT_BINARY_OPERATOR(-, Short);
254 IMPLEMENT_BINARY_OPERATOR(-, UInt);
255 IMPLEMENT_BINARY_OPERATOR(-, Int);
256 IMPLEMENT_BINARY_OPERATOR(-, ULong);
257 IMPLEMENT_BINARY_OPERATOR(-, Long);
258 IMPLEMENT_BINARY_OPERATOR(-, Float);
259 IMPLEMENT_BINARY_OPERATOR(-, Double);
260 IMPLEMENT_BINARY_PTR_OPERATOR(-);
262 cout << "Unhandled type for Sub instruction: " << Ty << endl;
267 #define IMPLEMENT_SETCC(OP, TY) \
268 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
270 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
271 const Type *Ty, ExecutionContext &SF) {
273 switch (Ty->getPrimitiveID()) {
274 IMPLEMENT_SETCC(==, UByte);
275 IMPLEMENT_SETCC(==, SByte);
276 IMPLEMENT_SETCC(==, UShort);
277 IMPLEMENT_SETCC(==, Short);
278 IMPLEMENT_SETCC(==, UInt);
279 IMPLEMENT_SETCC(==, Int);
280 IMPLEMENT_SETCC(==, ULong);
281 IMPLEMENT_SETCC(==, Long);
282 IMPLEMENT_SETCC(==, Float);
283 IMPLEMENT_SETCC(==, Double);
284 IMPLEMENT_SETCC(==, Pointer);
286 cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
291 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
292 const Type *Ty, ExecutionContext &SF) {
294 switch (Ty->getPrimitiveID()) {
295 IMPLEMENT_SETCC(!=, UByte);
296 IMPLEMENT_SETCC(!=, SByte);
297 IMPLEMENT_SETCC(!=, UShort);
298 IMPLEMENT_SETCC(!=, Short);
299 IMPLEMENT_SETCC(!=, UInt);
300 IMPLEMENT_SETCC(!=, Int);
301 IMPLEMENT_SETCC(!=, ULong);
302 IMPLEMENT_SETCC(!=, Long);
303 IMPLEMENT_SETCC(!=, Float);
304 IMPLEMENT_SETCC(!=, Double);
305 IMPLEMENT_SETCC(!=, Pointer);
307 cout << "Unhandled type for SetNE instruction: " << Ty << endl;
312 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
313 const Type *Ty, ExecutionContext &SF) {
315 switch (Ty->getPrimitiveID()) {
316 IMPLEMENT_SETCC(<=, UByte);
317 IMPLEMENT_SETCC(<=, SByte);
318 IMPLEMENT_SETCC(<=, UShort);
319 IMPLEMENT_SETCC(<=, Short);
320 IMPLEMENT_SETCC(<=, UInt);
321 IMPLEMENT_SETCC(<=, Int);
322 IMPLEMENT_SETCC(<=, ULong);
323 IMPLEMENT_SETCC(<=, Long);
324 IMPLEMENT_SETCC(<=, Float);
325 IMPLEMENT_SETCC(<=, Double);
326 IMPLEMENT_SETCC(<=, Pointer);
328 cout << "Unhandled type for SetLE instruction: " << Ty << endl;
333 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
334 const Type *Ty, ExecutionContext &SF) {
336 switch (Ty->getPrimitiveID()) {
337 IMPLEMENT_SETCC(>=, UByte);
338 IMPLEMENT_SETCC(>=, SByte);
339 IMPLEMENT_SETCC(>=, UShort);
340 IMPLEMENT_SETCC(>=, Short);
341 IMPLEMENT_SETCC(>=, UInt);
342 IMPLEMENT_SETCC(>=, Int);
343 IMPLEMENT_SETCC(>=, ULong);
344 IMPLEMENT_SETCC(>=, Long);
345 IMPLEMENT_SETCC(>=, Float);
346 IMPLEMENT_SETCC(>=, Double);
347 IMPLEMENT_SETCC(>=, Pointer);
349 cout << "Unhandled type for SetGE instruction: " << Ty << endl;
354 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
355 const Type *Ty, ExecutionContext &SF) {
357 switch (Ty->getPrimitiveID()) {
358 IMPLEMENT_SETCC(<, UByte);
359 IMPLEMENT_SETCC(<, SByte);
360 IMPLEMENT_SETCC(<, UShort);
361 IMPLEMENT_SETCC(<, Short);
362 IMPLEMENT_SETCC(<, UInt);
363 IMPLEMENT_SETCC(<, Int);
364 IMPLEMENT_SETCC(<, ULong);
365 IMPLEMENT_SETCC(<, Long);
366 IMPLEMENT_SETCC(<, Float);
367 IMPLEMENT_SETCC(<, Double);
368 IMPLEMENT_SETCC(<, Pointer);
370 cout << "Unhandled type for SetLT instruction: " << Ty << endl;
375 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
376 const Type *Ty, ExecutionContext &SF) {
378 switch (Ty->getPrimitiveID()) {
379 IMPLEMENT_SETCC(>, UByte);
380 IMPLEMENT_SETCC(>, SByte);
381 IMPLEMENT_SETCC(>, UShort);
382 IMPLEMENT_SETCC(>, Short);
383 IMPLEMENT_SETCC(>, UInt);
384 IMPLEMENT_SETCC(>, Int);
385 IMPLEMENT_SETCC(>, ULong);
386 IMPLEMENT_SETCC(>, Long);
387 IMPLEMENT_SETCC(>, Float);
388 IMPLEMENT_SETCC(>, Double);
389 IMPLEMENT_SETCC(>, Pointer);
391 cout << "Unhandled type for SetGT instruction: " << Ty << endl;
396 static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
397 const Type *Ty = I->getOperand(0)->getType();
398 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
399 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
400 GenericValue R; // Result
402 switch (I->getOpcode()) {
403 case Instruction::Add: R = executeAddInst(Src1, Src2, Ty, SF); break;
404 case Instruction::Sub: R = executeSubInst(Src1, Src2, Ty, SF); break;
405 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
406 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
407 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
408 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
409 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
410 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
412 cout << "Don't know how to handle this binary operator!\n-->" << I;
418 //===----------------------------------------------------------------------===//
419 // Terminator Instruction Implementations
420 //===----------------------------------------------------------------------===//
422 void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
423 const Type *RetTy = 0;
426 // Save away the return value... (if we are not 'ret void')
427 if (I->getNumOperands()) {
428 RetTy = I->getReturnValue()->getType();
429 Result = getOperandValue(I->getReturnValue(), SF);
432 // Save previously executing meth
433 const Method *M = ECStack.back().CurMethod;
435 // Pop the current stack frame... this invalidates SF
438 if (ECStack.empty()) { // Finished main. Put result into exit code...
439 if (RetTy) { // Nonvoid return type?
440 cout << "Method " << M->getType() << " \"" << M->getName()
442 print(RetTy, Result);
445 if (RetTy->isIntegral())
446 ExitCode = Result.SByteVal; // Capture the exit code of the program
453 // If we have a previous stack frame, and we have a previous call, fill in
454 // the return value...
456 ExecutionContext &NewSF = ECStack.back();
458 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
459 SetValue(NewSF.Caller, Result, NewSF);
461 NewSF.Caller = 0; // We returned from the call...
463 // This must be a function that is executing because of a user 'call'
465 cout << "Method " << M->getType() << " \"" << M->getName()
467 print(RetTy, Result);
472 void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
473 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
476 Dest = I->getSuccessor(0); // Uncond branches have a fixed dest...
477 if (!I->isUnconditional()) {
478 if (getOperandValue(I->getCondition(), SF).BoolVal == 0) // If false cond...
479 Dest = I->getSuccessor(1);
481 SF.CurBB = Dest; // Update CurBB to branch destination
482 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
485 //===----------------------------------------------------------------------===//
486 // Memory Instruction Implementations
487 //===----------------------------------------------------------------------===//
489 void Interpreter::executeAllocInst(AllocationInst *I, ExecutionContext &SF) {
490 const Type *Ty = I->getType()->getValueType(); // Type to be allocated
491 unsigned NumElements = 1;
493 if (I->getNumOperands()) { // Allocating a unsized array type?
494 assert(isa<ArrayType>(Ty) && cast<const ArrayType>(Ty)->isUnsized() &&
495 "Allocation inst with size operand for !unsized array type???");
496 Ty = cast<const ArrayType>(Ty)->getElementType(); // Get the actual type...
498 // Get the number of elements being allocated by the array...
499 GenericValue NumEl = getOperandValue(I->getOperand(0), SF);
500 NumElements = NumEl.UIntVal;
503 // Allocate enough memory to hold the type...
505 Result.PointerVal = (GenericValue*)malloc(NumElements * TD.getTypeSize(Ty));
506 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
507 SetValue(I, Result, SF);
509 if (I->getOpcode() == Instruction::Alloca) {
510 // TODO: FIXME: alloca should keep track of memory to free it later...
514 static void executeFreeInst(FreeInst *I, ExecutionContext &SF) {
515 assert(I->getOperand(0)->getType()->isPointerType() && "Freeing nonptr?");
516 GenericValue Value = getOperandValue(I->getOperand(0), SF);
517 // TODO: Check to make sure memory is allocated
518 free(Value.PointerVal); // Free memory
521 static void executeLoadInst(LoadInst *I, ExecutionContext &SF) {
522 assert(I->getNumOperands() == 1 && "NI!");
523 GenericValue *Ptr = getOperandValue(I->getPtrOperand(), SF).PointerVal;
526 switch (I->getType()->getPrimitiveID()) {
528 case Type::UByteTyID:
529 case Type::SByteTyID: Result.SByteVal = Ptr->SByteVal; break;
530 case Type::UShortTyID:
531 case Type::ShortTyID: Result.ShortVal = Ptr->ShortVal; break;
533 case Type::IntTyID: Result.IntVal = Ptr->IntVal; break;
534 case Type::ULongTyID:
535 case Type::LongTyID: Result.LongVal = Ptr->LongVal; break;
536 case Type::FloatTyID: Result.FloatVal = Ptr->FloatVal; break;
537 case Type::DoubleTyID: Result.DoubleVal = Ptr->DoubleVal; break;
538 case Type::PointerTyID: Result.PointerVal = Ptr->PointerVal; break;
540 cout << "Cannot load value of type " << I->getType() << "!\n";
543 SetValue(I, Result, SF);
546 static void executeStoreInst(StoreInst *I, ExecutionContext &SF) {
547 GenericValue *Ptr = getOperandValue(I->getPtrOperand(), SF).PointerVal;
548 GenericValue Val = getOperandValue(I->getOperand(0), SF);
549 assert(I->getNumOperands() == 2 && "NI!");
551 switch (I->getOperand(0)->getType()->getPrimitiveID()) {
553 case Type::UByteTyID:
554 case Type::SByteTyID: Ptr->SByteVal = Val.SByteVal; break;
555 case Type::UShortTyID:
556 case Type::ShortTyID: Ptr->ShortVal = Val.ShortVal; break;
558 case Type::IntTyID: Ptr->IntVal = Val.IntVal; break;
559 case Type::ULongTyID:
560 case Type::LongTyID: Ptr->LongVal = Val.LongVal; break;
561 case Type::FloatTyID: Ptr->FloatVal = Val.FloatVal; break;
562 case Type::DoubleTyID: Ptr->DoubleVal = Val.DoubleVal; break;
563 case Type::PointerTyID: Ptr->PointerVal = Val.PointerVal; break;
565 cout << "Cannot store value of type " << I->getType() << "!\n";
570 //===----------------------------------------------------------------------===//
571 // Miscellaneous Instruction Implementations
572 //===----------------------------------------------------------------------===//
574 void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
575 ECStack.back().Caller = I;
576 vector<GenericValue> ArgVals;
577 ArgVals.reserve(I->getNumOperands()-1);
578 for (unsigned i = 1; i < I->getNumOperands(); ++i)
579 ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
581 callMethod(I->getCalledMethod(), ArgVals);
584 static void executePHINode(PHINode *I, ExecutionContext &SF) {
585 BasicBlock *PrevBB = SF.PrevBB;
586 Value *IncomingValue = 0;
588 // Search for the value corresponding to this previous bb...
589 for (unsigned i = I->getNumIncomingValues(); i > 0;) {
590 if (I->getIncomingBlock(--i) == PrevBB) {
591 IncomingValue = I->getIncomingValue(i);
595 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
597 // Found the value, set as the result...
598 SetValue(I, getOperandValue(IncomingValue, SF), SF);
601 #define IMPLEMENT_SHIFT(OP, TY) \
602 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
604 static void executeShlInst(ShiftInst *I, ExecutionContext &SF) {
605 const Type *Ty = I->getOperand(0)->getType();
606 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
607 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
610 switch (Ty->getPrimitiveID()) {
611 IMPLEMENT_SHIFT(<<, UByte);
612 IMPLEMENT_SHIFT(<<, SByte);
613 IMPLEMENT_SHIFT(<<, UShort);
614 IMPLEMENT_SHIFT(<<, Short);
615 IMPLEMENT_SHIFT(<<, UInt);
616 IMPLEMENT_SHIFT(<<, Int);
617 IMPLEMENT_SHIFT(<<, ULong);
618 IMPLEMENT_SHIFT(<<, Long);
620 cout << "Unhandled type for Shl instruction: " << Ty << endl;
622 SetValue(I, Dest, SF);
625 static void executeShrInst(ShiftInst *I, ExecutionContext &SF) {
626 const Type *Ty = I->getOperand(0)->getType();
627 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
628 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
631 switch (Ty->getPrimitiveID()) {
632 IMPLEMENT_SHIFT(>>, UByte);
633 IMPLEMENT_SHIFT(>>, SByte);
634 IMPLEMENT_SHIFT(>>, UShort);
635 IMPLEMENT_SHIFT(>>, Short);
636 IMPLEMENT_SHIFT(>>, UInt);
637 IMPLEMENT_SHIFT(>>, Int);
638 IMPLEMENT_SHIFT(>>, ULong);
639 IMPLEMENT_SHIFT(>>, Long);
641 cout << "Unhandled type for Shr instruction: " << Ty << endl;
643 SetValue(I, Dest, SF);
646 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
647 case Type::STY##TyID: Dest.DTY##Val = (DCTY)Src.STY##Val; break;
649 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
650 case Type::DESTTY##TyID: \
651 switch (SrcTy->getPrimitiveID()) { \
652 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
653 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
654 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
655 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
656 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
657 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
658 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
659 IMPLEMENT_CAST(DESTTY, DESTCTY, Long);
661 #define IMPLEMENT_CAST_CASE_PTR_IMP(DESTTY, DESTCTY) \
662 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer)
664 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
665 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
666 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
668 #define IMPLEMENT_CAST_CASE_END() \
669 default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << endl; \
674 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
675 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
676 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
677 IMPLEMENT_CAST_CASE_PTR_IMP(DESTTY, DESTCTY); \
678 IMPLEMENT_CAST_CASE_END()
680 #define IMPLEMENT_CAST_CASE_FP(DESTTY, DESTCTY) \
681 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
682 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
683 IMPLEMENT_CAST_CASE_END()
685 #define IMPLEMENT_CAST_CASE_PTR(DESTTY, DESTCTY) \
686 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
687 IMPLEMENT_CAST_CASE_PTR_IMP(DESTTY, DESTCTY); \
688 IMPLEMENT_CAST_CASE_END()
690 static void executeCastInst(CastInst *I, ExecutionContext &SF) {
691 const Type *Ty = I->getType();
692 const Type *SrcTy = I->getOperand(0)->getType();
693 GenericValue Src = getOperandValue(I->getOperand(0), SF);
696 switch (Ty->getPrimitiveID()) {
697 IMPLEMENT_CAST_CASE(UByte , unsigned char);
698 IMPLEMENT_CAST_CASE(SByte , signed char);
699 IMPLEMENT_CAST_CASE(UShort, unsigned short);
700 IMPLEMENT_CAST_CASE(Short , signed char);
701 IMPLEMENT_CAST_CASE(UInt , unsigned int );
702 IMPLEMENT_CAST_CASE(Int , signed int );
703 IMPLEMENT_CAST_CASE(ULong , uint64_t );
704 IMPLEMENT_CAST_CASE(Long , int64_t );
705 IMPLEMENT_CAST_CASE_FP(Float , float);
706 IMPLEMENT_CAST_CASE_FP(Double, double);
707 IMPLEMENT_CAST_CASE_PTR(Pointer, GenericValue *);
709 cout << "Unhandled dest type for cast instruction: " << Ty << endl;
711 SetValue(I, Dest, SF);
717 //===----------------------------------------------------------------------===//
718 // Dispatch and Execution Code
719 //===----------------------------------------------------------------------===//
721 MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
722 // Assign slot numbers to the method arguments...
723 const Method::ArgumentListType &ArgList = M->getArgumentList();
724 for (Method::ArgumentListType::const_iterator AI = ArgList.begin(),
725 AE = ArgList.end(); AI != AE; ++AI) {
726 MethodArgument *MA = *AI;
727 MA->addAnnotation(new SlotNumber(getValueSlot(MA)));
730 // Iterate over all of the instructions...
731 unsigned InstNum = 0;
732 for (Method::inst_iterator MI = M->inst_begin(), ME = M->inst_end();
734 Instruction *I = *MI; // For each instruction...
735 I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I))); // Add Annote
739 unsigned MethodInfo::getValueSlot(const Value *V) {
740 unsigned Plane = V->getType()->getUniqueID();
741 if (Plane >= NumPlaneElements.size())
742 NumPlaneElements.resize(Plane+1, 0);
743 return NumPlaneElements[Plane]++;
747 //===----------------------------------------------------------------------===//
748 // callMethod - Execute the specified method...
750 void Interpreter::callMethod(Method *M, const vector<GenericValue> &ArgVals) {
751 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
752 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
753 "Incorrect number of arguments passed into function call!");
754 if (M->isExternal()) {
755 callExternalMethod(M, ArgVals);
759 // Process the method, assigning instruction numbers to the instructions in
760 // the method. Also calculate the number of values for each type slot active.
762 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
763 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
765 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
766 StackFrame.CurMethod = M;
767 StackFrame.CurBB = M->front();
768 StackFrame.CurInst = StackFrame.CurBB->begin();
769 StackFrame.MethInfo = MethInfo;
771 // Initialize the values to nothing...
772 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
773 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i)
774 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
776 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
779 // Run through the method arguments and initialize their values...
780 assert(ArgVals.size() == M->getArgumentList().size() &&
781 "Invalid number of values passed to method invocation!");
783 for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
784 ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
785 SetValue(*MI, ArgVals[i], StackFrame);
789 // executeInstruction - Interpret a single instruction, increment the "PC", and
790 // return true if the next instruction is a breakpoint...
792 bool Interpreter::executeInstruction() {
793 assert(!ECStack.empty() && "No program running, cannot execute inst!");
795 ExecutionContext &SF = ECStack.back(); // Current stack frame
796 Instruction *I = *SF.CurInst++; // Increment before execute
798 if (I->isBinaryOp()) {
799 executeBinaryInst((BinaryOperator*)I, SF);
801 switch (I->getOpcode()) {
803 case Instruction::Ret: executeRetInst ((ReturnInst*)I, SF); break;
804 case Instruction::Br: executeBrInst ((BranchInst*)I, SF); break;
805 // Memory Instructions
806 case Instruction::Alloca:
807 case Instruction::Malloc: executeAllocInst ((AllocationInst*)I, SF); break;
808 case Instruction::Free: executeFreeInst (cast<FreeInst> (I), SF); break;
809 case Instruction::Load: executeLoadInst (cast<LoadInst> (I), SF); break;
810 case Instruction::Store: executeStoreInst (cast<StoreInst>(I), SF); break;
812 // Miscellaneous Instructions
813 case Instruction::Call: executeCallInst (cast<CallInst> (I), SF); break;
814 case Instruction::PHINode: executePHINode (cast<PHINode> (I), SF); break;
815 case Instruction::Shl: executeShlInst (cast<ShiftInst>(I), SF); break;
816 case Instruction::Shr: executeShrInst (cast<ShiftInst>(I), SF); break;
817 case Instruction::Cast: executeCastInst (cast<CastInst> (I), SF); break;
819 cout << "Don't know how to execute this instruction!\n-->" << I;
823 // Reset the current frame location to the top of stack
824 CurFrame = ECStack.size()-1;
826 if (CurFrame == -1) return false; // No breakpoint if no code
828 // Return true if there is a breakpoint annotation on the instruction...
829 return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
832 void Interpreter::stepInstruction() { // Do the 'step' command
833 if (ECStack.empty()) {
834 cout << "Error: no program running, cannot step!\n";
838 // Run an instruction...
839 executeInstruction();
841 // Print the next instruction to execute...
842 printCurrentInstruction();
846 void Interpreter::nextInstruction() { // Do the 'next' command
847 if (ECStack.empty()) {
848 cout << "Error: no program running, cannot 'next'!\n";
852 // If this is a call instruction, step over the call instruction...
853 // TODO: ICALL, CALL WITH, ...
854 if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
855 // Step into the function...
856 if (executeInstruction()) {
857 // Hit a breakpoint, print current instruction, then return to user...
858 cout << "Breakpoint hit!\n";
859 printCurrentInstruction();
863 // Finish executing the function...
866 // Normal instruction, just step...
871 void Interpreter::run() {
872 if (ECStack.empty()) {
873 cout << "Error: no program running, cannot run!\n";
877 bool HitBreakpoint = false;
878 while (!ECStack.empty() && !HitBreakpoint) {
879 // Run an instruction...
880 HitBreakpoint = executeInstruction();
884 cout << "Breakpoint hit!\n";
886 // Print the next instruction to execute...
887 printCurrentInstruction();
890 void Interpreter::finish() {
891 if (ECStack.empty()) {
892 cout << "Error: no program running, cannot run!\n";
896 unsigned StackSize = ECStack.size();
897 bool HitBreakpoint = false;
898 while (ECStack.size() >= StackSize && !HitBreakpoint) {
899 // Run an instruction...
900 HitBreakpoint = executeInstruction();
904 cout << "Breakpoint hit!\n";
907 // Print the next instruction to execute...
908 printCurrentInstruction();
913 // printCurrentInstruction - Print out the instruction that the virtual PC is
914 // at, or fail silently if no program is running.
916 void Interpreter::printCurrentInstruction() {
917 if (!ECStack.empty()) {
918 Instruction *I = *ECStack.back().CurInst;
919 InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
920 assert(IN && "Instruction has no numbering annotation!");
921 cout << "#" << IN->InstNum << I;
925 void Interpreter::printValue(const Type *Ty, GenericValue V) {
926 switch (Ty->getPrimitiveID()) {
927 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
928 case Type::SByteTyID: cout << V.SByteVal; break;
929 case Type::UByteTyID: cout << V.UByteVal; break;
930 case Type::ShortTyID: cout << V.ShortVal; break;
931 case Type::UShortTyID: cout << V.UShortVal; break;
932 case Type::IntTyID: cout << V.IntVal; break;
933 case Type::UIntTyID: cout << V.UIntVal; break;
934 case Type::LongTyID: cout << V.LongVal; break;
935 case Type::ULongTyID: cout << V.ULongVal; break;
936 case Type::FloatTyID: cout << V.FloatVal; break;
937 case Type::DoubleTyID: cout << V.DoubleVal; break;
938 case Type::PointerTyID:cout << V.PointerVal; break;
940 cout << "- Don't know how to print value of this type!";
945 void Interpreter::print(const Type *Ty, GenericValue V) {
950 void Interpreter::print(const string &Name) {
951 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
952 if (!PickedVal) return;
954 if (const Method *M = dyn_cast<const Method>(PickedVal)) {
955 cout << M; // Print the method
956 } else { // Otherwise there should be an annotation for the slot#
957 print(PickedVal->getType(),
958 getOperandValue(PickedVal, ECStack[CurFrame]));
964 void Interpreter::infoValue(const string &Name) {
965 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
966 if (!PickedVal) return;
969 print(PickedVal->getType(),
970 getOperandValue(PickedVal, ECStack[CurFrame]));
972 printOperandInfo(PickedVal, ECStack[CurFrame]);
975 void Interpreter::list() {
977 cout << "Error: No program executing!\n";
979 cout << ECStack[CurFrame].CurMethod; // Just print the method out...
982 void Interpreter::printStackTrace() {
983 if (ECStack.empty()) cout << "No program executing!\n";
985 for (unsigned i = 0; i < ECStack.size(); ++i) {
986 cout << (((int)i == CurFrame) ? '>' : '-');
987 cout << "#" << i << ". " << ECStack[i].CurMethod->getType() << " \""
988 << ECStack[i].CurMethod->getName() << "\"(";
991 cout << *ECStack[i].CurInst;