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)) {
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.ULongVal = (uint64_t)(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
222 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
223 const Type *Ty, ExecutionContext &SF) {
225 switch (Ty->getPrimitiveID()) {
226 IMPLEMENT_BINARY_OPERATOR(+, UByte);
227 IMPLEMENT_BINARY_OPERATOR(+, SByte);
228 IMPLEMENT_BINARY_OPERATOR(+, UShort);
229 IMPLEMENT_BINARY_OPERATOR(+, Short);
230 IMPLEMENT_BINARY_OPERATOR(+, UInt);
231 IMPLEMENT_BINARY_OPERATOR(+, Int);
232 IMPLEMENT_BINARY_OPERATOR(+, ULong);
233 IMPLEMENT_BINARY_OPERATOR(+, Long);
234 IMPLEMENT_BINARY_OPERATOR(+, Float);
235 IMPLEMENT_BINARY_OPERATOR(+, Double);
236 IMPLEMENT_BINARY_OPERATOR(+, Pointer);
238 cout << "Unhandled type for Add instruction: " << Ty << endl;
243 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
244 const Type *Ty, ExecutionContext &SF) {
246 switch (Ty->getPrimitiveID()) {
247 IMPLEMENT_BINARY_OPERATOR(-, UByte);
248 IMPLEMENT_BINARY_OPERATOR(-, SByte);
249 IMPLEMENT_BINARY_OPERATOR(-, UShort);
250 IMPLEMENT_BINARY_OPERATOR(-, Short);
251 IMPLEMENT_BINARY_OPERATOR(-, UInt);
252 IMPLEMENT_BINARY_OPERATOR(-, Int);
253 IMPLEMENT_BINARY_OPERATOR(-, ULong);
254 IMPLEMENT_BINARY_OPERATOR(-, Long);
255 IMPLEMENT_BINARY_OPERATOR(-, Float);
256 IMPLEMENT_BINARY_OPERATOR(-, Double);
257 IMPLEMENT_BINARY_OPERATOR(-, Pointer);
259 cout << "Unhandled type for Sub instruction: " << Ty << endl;
264 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
265 const Type *Ty, ExecutionContext &SF) {
267 switch (Ty->getPrimitiveID()) {
268 IMPLEMENT_BINARY_OPERATOR(*, UByte);
269 IMPLEMENT_BINARY_OPERATOR(*, SByte);
270 IMPLEMENT_BINARY_OPERATOR(*, UShort);
271 IMPLEMENT_BINARY_OPERATOR(*, Short);
272 IMPLEMENT_BINARY_OPERATOR(*, UInt);
273 IMPLEMENT_BINARY_OPERATOR(*, Int);
274 IMPLEMENT_BINARY_OPERATOR(*, ULong);
275 IMPLEMENT_BINARY_OPERATOR(*, Long);
276 IMPLEMENT_BINARY_OPERATOR(*, Float);
277 IMPLEMENT_BINARY_OPERATOR(*, Double);
278 IMPLEMENT_BINARY_OPERATOR(*, Pointer);
280 cout << "Unhandled type for Mul instruction: " << Ty << endl;
285 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
286 const Type *Ty, ExecutionContext &SF) {
288 switch (Ty->getPrimitiveID()) {
289 IMPLEMENT_BINARY_OPERATOR(/, UByte);
290 IMPLEMENT_BINARY_OPERATOR(/, SByte);
291 IMPLEMENT_BINARY_OPERATOR(/, UShort);
292 IMPLEMENT_BINARY_OPERATOR(/, Short);
293 IMPLEMENT_BINARY_OPERATOR(/, UInt);
294 IMPLEMENT_BINARY_OPERATOR(/, Int);
295 IMPLEMENT_BINARY_OPERATOR(/, ULong);
296 IMPLEMENT_BINARY_OPERATOR(/, Long);
297 IMPLEMENT_BINARY_OPERATOR(/, Float);
298 IMPLEMENT_BINARY_OPERATOR(/, Double);
299 IMPLEMENT_BINARY_OPERATOR(/, Pointer);
301 cout << "Unhandled type for Mul instruction: " << Ty << endl;
306 #define IMPLEMENT_SETCC(OP, TY) \
307 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
309 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
310 const Type *Ty, ExecutionContext &SF) {
312 switch (Ty->getPrimitiveID()) {
313 IMPLEMENT_SETCC(==, UByte);
314 IMPLEMENT_SETCC(==, SByte);
315 IMPLEMENT_SETCC(==, UShort);
316 IMPLEMENT_SETCC(==, Short);
317 IMPLEMENT_SETCC(==, UInt);
318 IMPLEMENT_SETCC(==, Int);
319 IMPLEMENT_SETCC(==, ULong);
320 IMPLEMENT_SETCC(==, Long);
321 IMPLEMENT_SETCC(==, Float);
322 IMPLEMENT_SETCC(==, Double);
323 IMPLEMENT_SETCC(==, Pointer);
325 cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
330 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
331 const Type *Ty, ExecutionContext &SF) {
333 switch (Ty->getPrimitiveID()) {
334 IMPLEMENT_SETCC(!=, UByte);
335 IMPLEMENT_SETCC(!=, SByte);
336 IMPLEMENT_SETCC(!=, UShort);
337 IMPLEMENT_SETCC(!=, Short);
338 IMPLEMENT_SETCC(!=, UInt);
339 IMPLEMENT_SETCC(!=, Int);
340 IMPLEMENT_SETCC(!=, ULong);
341 IMPLEMENT_SETCC(!=, Long);
342 IMPLEMENT_SETCC(!=, Float);
343 IMPLEMENT_SETCC(!=, Double);
344 IMPLEMENT_SETCC(!=, Pointer);
346 cout << "Unhandled type for SetNE instruction: " << Ty << endl;
351 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
352 const Type *Ty, ExecutionContext &SF) {
354 switch (Ty->getPrimitiveID()) {
355 IMPLEMENT_SETCC(<=, UByte);
356 IMPLEMENT_SETCC(<=, SByte);
357 IMPLEMENT_SETCC(<=, UShort);
358 IMPLEMENT_SETCC(<=, Short);
359 IMPLEMENT_SETCC(<=, UInt);
360 IMPLEMENT_SETCC(<=, Int);
361 IMPLEMENT_SETCC(<=, ULong);
362 IMPLEMENT_SETCC(<=, Long);
363 IMPLEMENT_SETCC(<=, Float);
364 IMPLEMENT_SETCC(<=, Double);
365 IMPLEMENT_SETCC(<=, Pointer);
367 cout << "Unhandled type for SetLE instruction: " << Ty << endl;
372 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
373 const Type *Ty, ExecutionContext &SF) {
375 switch (Ty->getPrimitiveID()) {
376 IMPLEMENT_SETCC(>=, UByte);
377 IMPLEMENT_SETCC(>=, SByte);
378 IMPLEMENT_SETCC(>=, UShort);
379 IMPLEMENT_SETCC(>=, Short);
380 IMPLEMENT_SETCC(>=, UInt);
381 IMPLEMENT_SETCC(>=, Int);
382 IMPLEMENT_SETCC(>=, ULong);
383 IMPLEMENT_SETCC(>=, Long);
384 IMPLEMENT_SETCC(>=, Float);
385 IMPLEMENT_SETCC(>=, Double);
386 IMPLEMENT_SETCC(>=, Pointer);
388 cout << "Unhandled type for SetGE instruction: " << Ty << endl;
393 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
394 const Type *Ty, ExecutionContext &SF) {
396 switch (Ty->getPrimitiveID()) {
397 IMPLEMENT_SETCC(<, UByte);
398 IMPLEMENT_SETCC(<, SByte);
399 IMPLEMENT_SETCC(<, UShort);
400 IMPLEMENT_SETCC(<, Short);
401 IMPLEMENT_SETCC(<, UInt);
402 IMPLEMENT_SETCC(<, Int);
403 IMPLEMENT_SETCC(<, ULong);
404 IMPLEMENT_SETCC(<, Long);
405 IMPLEMENT_SETCC(<, Float);
406 IMPLEMENT_SETCC(<, Double);
407 IMPLEMENT_SETCC(<, Pointer);
409 cout << "Unhandled type for SetLT instruction: " << Ty << endl;
414 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
415 const Type *Ty, ExecutionContext &SF) {
417 switch (Ty->getPrimitiveID()) {
418 IMPLEMENT_SETCC(>, UByte);
419 IMPLEMENT_SETCC(>, SByte);
420 IMPLEMENT_SETCC(>, UShort);
421 IMPLEMENT_SETCC(>, Short);
422 IMPLEMENT_SETCC(>, UInt);
423 IMPLEMENT_SETCC(>, Int);
424 IMPLEMENT_SETCC(>, ULong);
425 IMPLEMENT_SETCC(>, Long);
426 IMPLEMENT_SETCC(>, Float);
427 IMPLEMENT_SETCC(>, Double);
428 IMPLEMENT_SETCC(>, Pointer);
430 cout << "Unhandled type for SetGT instruction: " << Ty << endl;
435 static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
436 const Type *Ty = I->getOperand(0)->getType();
437 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
438 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
439 GenericValue R; // Result
441 switch (I->getOpcode()) {
442 case Instruction::Add: R = executeAddInst(Src1, Src2, Ty, SF); break;
443 case Instruction::Sub: R = executeSubInst(Src1, Src2, Ty, SF); break;
444 case Instruction::Mul: R = executeMulInst(Src1, Src2, Ty, SF); break;
445 case Instruction::Div: R = executeDivInst(Src1, Src2, Ty, SF); break;
446 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
447 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
448 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
449 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
450 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
451 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
453 cout << "Don't know how to handle this binary operator!\n-->" << I;
459 //===----------------------------------------------------------------------===//
460 // Terminator Instruction Implementations
461 //===----------------------------------------------------------------------===//
463 void Interpreter::exitCalled(GenericValue GV) {
464 cout << "Program returned ";
465 print(Type::IntTy, GV);
466 cout << " via 'void exit(int)'\n";
468 ExitCode = GV.SByteVal;
472 void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
473 const Type *RetTy = 0;
476 // Save away the return value... (if we are not 'ret void')
477 if (I->getNumOperands()) {
478 RetTy = I->getReturnValue()->getType();
479 Result = getOperandValue(I->getReturnValue(), SF);
482 // Save previously executing meth
483 const Method *M = ECStack.back().CurMethod;
485 // Pop the current stack frame... this invalidates SF
488 if (ECStack.empty()) { // Finished main. Put result into exit code...
489 if (RetTy) { // Nonvoid return type?
490 cout << "Method " << M->getType() << " \"" << M->getName()
492 print(RetTy, Result);
495 if (RetTy->isIntegral())
496 ExitCode = Result.SByteVal; // Capture the exit code of the program
503 // If we have a previous stack frame, and we have a previous call, fill in
504 // the return value...
506 ExecutionContext &NewSF = ECStack.back();
508 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
509 SetValue(NewSF.Caller, Result, NewSF);
511 NewSF.Caller = 0; // We returned from the call...
513 // This must be a function that is executing because of a user 'call'
515 cout << "Method " << M->getType() << " \"" << M->getName()
517 print(RetTy, Result);
522 void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
523 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
526 Dest = I->getSuccessor(0); // Uncond branches have a fixed dest...
527 if (!I->isUnconditional()) {
528 if (getOperandValue(I->getCondition(), SF).BoolVal == 0) // If false cond...
529 Dest = I->getSuccessor(1);
531 SF.CurBB = Dest; // Update CurBB to branch destination
532 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
535 //===----------------------------------------------------------------------===//
536 // Memory Instruction Implementations
537 //===----------------------------------------------------------------------===//
539 void Interpreter::executeAllocInst(AllocationInst *I, ExecutionContext &SF) {
540 const Type *Ty = I->getType()->getValueType(); // Type to be allocated
541 unsigned NumElements = 1;
543 if (I->getNumOperands()) { // Allocating a unsized array type?
544 assert(isa<ArrayType>(Ty) && cast<const ArrayType>(Ty)->isUnsized() &&
545 "Allocation inst with size operand for !unsized array type???");
546 Ty = cast<const ArrayType>(Ty)->getElementType(); // Get the actual type...
548 // Get the number of elements being allocated by the array...
549 GenericValue NumEl = getOperandValue(I->getOperand(0), SF);
550 NumElements = NumEl.UIntVal;
553 // Allocate enough memory to hold the type...
555 Result.ULongVal = (uint64_t)malloc(NumElements * TD.getTypeSize(Ty));
556 assert(Result.ULongVal != 0 && "Null pointer returned by malloc!");
557 SetValue(I, Result, SF);
559 if (I->getOpcode() == Instruction::Alloca) {
560 // TODO: FIXME: alloca should keep track of memory to free it later...
564 static void executeFreeInst(FreeInst *I, ExecutionContext &SF) {
565 assert(I->getOperand(0)->getType()->isPointerType() && "Freeing nonptr?");
566 GenericValue Value = getOperandValue(I->getOperand(0), SF);
567 // TODO: Check to make sure memory is allocated
568 free((void*)Value.ULongVal); // Free memory
571 static void executeLoadInst(LoadInst *I, ExecutionContext &SF) {
572 assert(I->getNumOperands() == 1 && "NI!");
574 (GenericValue*)getOperandValue(I->getPtrOperand(), SF).ULongVal;
577 switch (I->getType()->getPrimitiveID()) {
579 case Type::UByteTyID:
580 case Type::SByteTyID: Result.SByteVal = Ptr->SByteVal; break;
581 case Type::UShortTyID:
582 case Type::ShortTyID: Result.ShortVal = Ptr->ShortVal; break;
584 case Type::IntTyID: Result.IntVal = Ptr->IntVal; break;
585 case Type::ULongTyID:
587 case Type::PointerTyID: Result.ULongVal = Ptr->ULongVal; break;
588 case Type::FloatTyID: Result.FloatVal = Ptr->FloatVal; break;
589 case Type::DoubleTyID: Result.DoubleVal = Ptr->DoubleVal; break;
591 cout << "Cannot load value of type " << I->getType() << "!\n";
594 SetValue(I, Result, SF);
597 static void executeStoreInst(StoreInst *I, ExecutionContext &SF) {
599 (GenericValue *)getOperandValue(I->getPtrOperand(), SF).ULongVal;
600 GenericValue Val = getOperandValue(I->getOperand(0), SF);
601 assert(I->getNumOperands() == 2 && "NI!");
603 switch (I->getOperand(0)->getType()->getPrimitiveID()) {
605 case Type::UByteTyID:
606 case Type::SByteTyID: Ptr->SByteVal = Val.SByteVal; break;
607 case Type::UShortTyID:
608 case Type::ShortTyID: Ptr->ShortVal = Val.ShortVal; break;
610 case Type::IntTyID: Ptr->IntVal = Val.IntVal; break;
611 case Type::ULongTyID:
613 case Type::PointerTyID: Ptr->LongVal = Val.LongVal; break;
614 case Type::FloatTyID: Ptr->FloatVal = Val.FloatVal; break;
615 case Type::DoubleTyID: Ptr->DoubleVal = Val.DoubleVal; break;
617 cout << "Cannot store value of type " << I->getType() << "!\n";
622 //===----------------------------------------------------------------------===//
623 // Miscellaneous Instruction Implementations
624 //===----------------------------------------------------------------------===//
626 void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
627 ECStack.back().Caller = I;
628 vector<GenericValue> ArgVals;
629 ArgVals.reserve(I->getNumOperands()-1);
630 for (unsigned i = 1; i < I->getNumOperands(); ++i)
631 ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
633 callMethod(I->getCalledMethod(), ArgVals);
636 static void executePHINode(PHINode *I, ExecutionContext &SF) {
637 BasicBlock *PrevBB = SF.PrevBB;
638 Value *IncomingValue = 0;
640 // Search for the value corresponding to this previous bb...
641 for (unsigned i = I->getNumIncomingValues(); i > 0;) {
642 if (I->getIncomingBlock(--i) == PrevBB) {
643 IncomingValue = I->getIncomingValue(i);
647 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
649 // Found the value, set as the result...
650 SetValue(I, getOperandValue(IncomingValue, SF), SF);
653 #define IMPLEMENT_SHIFT(OP, TY) \
654 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
656 static void executeShlInst(ShiftInst *I, ExecutionContext &SF) {
657 const Type *Ty = I->getOperand(0)->getType();
658 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
659 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
662 switch (Ty->getPrimitiveID()) {
663 IMPLEMENT_SHIFT(<<, UByte);
664 IMPLEMENT_SHIFT(<<, SByte);
665 IMPLEMENT_SHIFT(<<, UShort);
666 IMPLEMENT_SHIFT(<<, Short);
667 IMPLEMENT_SHIFT(<<, UInt);
668 IMPLEMENT_SHIFT(<<, Int);
669 IMPLEMENT_SHIFT(<<, ULong);
670 IMPLEMENT_SHIFT(<<, Long);
672 cout << "Unhandled type for Shl instruction: " << Ty << endl;
674 SetValue(I, Dest, SF);
677 static void executeShrInst(ShiftInst *I, ExecutionContext &SF) {
678 const Type *Ty = I->getOperand(0)->getType();
679 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
680 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
683 switch (Ty->getPrimitiveID()) {
684 IMPLEMENT_SHIFT(>>, UByte);
685 IMPLEMENT_SHIFT(>>, SByte);
686 IMPLEMENT_SHIFT(>>, UShort);
687 IMPLEMENT_SHIFT(>>, Short);
688 IMPLEMENT_SHIFT(>>, UInt);
689 IMPLEMENT_SHIFT(>>, Int);
690 IMPLEMENT_SHIFT(>>, ULong);
691 IMPLEMENT_SHIFT(>>, Long);
693 cout << "Unhandled type for Shr instruction: " << Ty << endl;
695 SetValue(I, Dest, SF);
698 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
699 case Type::STY##TyID: Dest.DTY##Val = (DCTY)Src.STY##Val; break;
701 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
702 case Type::DESTTY##TyID: \
703 switch (SrcTy->getPrimitiveID()) { \
704 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
705 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
706 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
707 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
708 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
709 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
710 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
711 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
712 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
714 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
715 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
716 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
718 #define IMPLEMENT_CAST_CASE_END() \
719 default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << endl; \
724 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
725 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
726 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
727 IMPLEMENT_CAST_CASE_END()
729 static void executeCastInst(CastInst *I, ExecutionContext &SF) {
730 const Type *Ty = I->getType();
731 const Type *SrcTy = I->getOperand(0)->getType();
732 GenericValue Src = getOperandValue(I->getOperand(0), SF);
735 switch (Ty->getPrimitiveID()) {
736 IMPLEMENT_CAST_CASE(UByte , unsigned char);
737 IMPLEMENT_CAST_CASE(SByte , signed char);
738 IMPLEMENT_CAST_CASE(UShort, unsigned short);
739 IMPLEMENT_CAST_CASE(Short , signed char);
740 IMPLEMENT_CAST_CASE(UInt , unsigned int );
741 IMPLEMENT_CAST_CASE(Int , signed int );
742 IMPLEMENT_CAST_CASE(ULong , uint64_t );
743 IMPLEMENT_CAST_CASE(Long , int64_t );
744 IMPLEMENT_CAST_CASE(Pointer, uint64_t);
745 IMPLEMENT_CAST_CASE(Float , float);
746 IMPLEMENT_CAST_CASE(Double, double);
748 cout << "Unhandled dest type for cast instruction: " << Ty << endl;
750 SetValue(I, Dest, SF);
756 //===----------------------------------------------------------------------===//
757 // Dispatch and Execution Code
758 //===----------------------------------------------------------------------===//
760 MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
761 // Assign slot numbers to the method arguments...
762 const Method::ArgumentListType &ArgList = M->getArgumentList();
763 for (Method::ArgumentListType::const_iterator AI = ArgList.begin(),
764 AE = ArgList.end(); AI != AE; ++AI) {
765 MethodArgument *MA = *AI;
766 MA->addAnnotation(new SlotNumber(getValueSlot(MA)));
769 // Iterate over all of the instructions...
770 unsigned InstNum = 0;
771 for (Method::inst_iterator MI = M->inst_begin(), ME = M->inst_end();
773 Instruction *I = *MI; // For each instruction...
774 I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I))); // Add Annote
778 unsigned MethodInfo::getValueSlot(const Value *V) {
779 unsigned Plane = V->getType()->getUniqueID();
780 if (Plane >= NumPlaneElements.size())
781 NumPlaneElements.resize(Plane+1, 0);
782 return NumPlaneElements[Plane]++;
786 //===----------------------------------------------------------------------===//
787 // callMethod - Execute the specified method...
789 void Interpreter::callMethod(Method *M, const vector<GenericValue> &ArgVals) {
790 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
791 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
792 "Incorrect number of arguments passed into function call!");
793 if (M->isExternal()) {
794 callExternalMethod(M, ArgVals);
798 // Process the method, assigning instruction numbers to the instructions in
799 // the method. Also calculate the number of values for each type slot active.
801 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
802 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
804 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
805 StackFrame.CurMethod = M;
806 StackFrame.CurBB = M->front();
807 StackFrame.CurInst = StackFrame.CurBB->begin();
808 StackFrame.MethInfo = MethInfo;
810 // Initialize the values to nothing...
811 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
812 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i)
813 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
815 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
818 // Run through the method arguments and initialize their values...
819 assert(ArgVals.size() == M->getArgumentList().size() &&
820 "Invalid number of values passed to method invocation!");
822 for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
823 ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
824 SetValue(*MI, ArgVals[i], StackFrame);
828 // executeInstruction - Interpret a single instruction, increment the "PC", and
829 // return true if the next instruction is a breakpoint...
831 bool Interpreter::executeInstruction() {
832 assert(!ECStack.empty() && "No program running, cannot execute inst!");
834 ExecutionContext &SF = ECStack.back(); // Current stack frame
835 Instruction *I = *SF.CurInst++; // Increment before execute
837 if (I->isBinaryOp()) {
838 executeBinaryInst((BinaryOperator*)I, SF);
840 switch (I->getOpcode()) {
842 case Instruction::Ret: executeRetInst ((ReturnInst*)I, SF); break;
843 case Instruction::Br: executeBrInst ((BranchInst*)I, SF); break;
844 // Memory Instructions
845 case Instruction::Alloca:
846 case Instruction::Malloc: executeAllocInst ((AllocationInst*)I, SF); break;
847 case Instruction::Free: executeFreeInst (cast<FreeInst> (I), SF); break;
848 case Instruction::Load: executeLoadInst (cast<LoadInst> (I), SF); break;
849 case Instruction::Store: executeStoreInst (cast<StoreInst>(I), SF); break;
851 // Miscellaneous Instructions
852 case Instruction::Call: executeCallInst (cast<CallInst> (I), SF); break;
853 case Instruction::PHINode: executePHINode (cast<PHINode> (I), SF); break;
854 case Instruction::Shl: executeShlInst (cast<ShiftInst>(I), SF); break;
855 case Instruction::Shr: executeShrInst (cast<ShiftInst>(I), SF); break;
856 case Instruction::Cast: executeCastInst (cast<CastInst> (I), SF); break;
858 cout << "Don't know how to execute this instruction!\n-->" << I;
862 // Reset the current frame location to the top of stack
863 CurFrame = ECStack.size()-1;
865 if (CurFrame == -1) return false; // No breakpoint if no code
867 // Return true if there is a breakpoint annotation on the instruction...
868 return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
871 void Interpreter::stepInstruction() { // Do the 'step' command
872 if (ECStack.empty()) {
873 cout << "Error: no program running, cannot step!\n";
877 // Run an instruction...
878 executeInstruction();
880 // Print the next instruction to execute...
881 printCurrentInstruction();
885 void Interpreter::nextInstruction() { // Do the 'next' command
886 if (ECStack.empty()) {
887 cout << "Error: no program running, cannot 'next'!\n";
891 // If this is a call instruction, step over the call instruction...
892 // TODO: ICALL, CALL WITH, ...
893 if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
894 // Step into the function...
895 if (executeInstruction()) {
896 // Hit a breakpoint, print current instruction, then return to user...
897 cout << "Breakpoint hit!\n";
898 printCurrentInstruction();
902 // Finish executing the function...
905 // Normal instruction, just step...
910 void Interpreter::run() {
911 if (ECStack.empty()) {
912 cout << "Error: no program running, cannot run!\n";
916 bool HitBreakpoint = false;
917 while (!ECStack.empty() && !HitBreakpoint) {
918 // Run an instruction...
919 HitBreakpoint = executeInstruction();
923 cout << "Breakpoint hit!\n";
925 // Print the next instruction to execute...
926 printCurrentInstruction();
929 void Interpreter::finish() {
930 if (ECStack.empty()) {
931 cout << "Error: no program running, cannot run!\n";
935 unsigned StackSize = ECStack.size();
936 bool HitBreakpoint = false;
937 while (ECStack.size() >= StackSize && !HitBreakpoint) {
938 // Run an instruction...
939 HitBreakpoint = executeInstruction();
943 cout << "Breakpoint hit!\n";
946 // Print the next instruction to execute...
947 printCurrentInstruction();
952 // printCurrentInstruction - Print out the instruction that the virtual PC is
953 // at, or fail silently if no program is running.
955 void Interpreter::printCurrentInstruction() {
956 if (!ECStack.empty()) {
957 Instruction *I = *ECStack.back().CurInst;
958 InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
959 assert(IN && "Instruction has no numbering annotation!");
960 cout << "#" << IN->InstNum << I;
964 void Interpreter::printValue(const Type *Ty, GenericValue V) {
965 switch (Ty->getPrimitiveID()) {
966 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
967 case Type::SByteTyID: cout << V.SByteVal; break;
968 case Type::UByteTyID: cout << V.UByteVal; break;
969 case Type::ShortTyID: cout << V.ShortVal; break;
970 case Type::UShortTyID: cout << V.UShortVal; break;
971 case Type::IntTyID: cout << V.IntVal; break;
972 case Type::UIntTyID: cout << V.UIntVal; break;
973 case Type::LongTyID: cout << V.LongVal; break;
974 case Type::ULongTyID: cout << V.ULongVal; break;
975 case Type::FloatTyID: cout << V.FloatVal; break;
976 case Type::DoubleTyID: cout << V.DoubleVal; break;
977 case Type::PointerTyID:cout << (void*)V.ULongVal; break;
979 cout << "- Don't know how to print value of this type!";
984 void Interpreter::print(const Type *Ty, GenericValue V) {
989 void Interpreter::print(const string &Name) {
990 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
991 if (!PickedVal) return;
993 if (const Method *M = dyn_cast<const Method>(PickedVal)) {
994 cout << M; // Print the method
995 } else { // Otherwise there should be an annotation for the slot#
996 print(PickedVal->getType(),
997 getOperandValue(PickedVal, ECStack[CurFrame]));
1003 void Interpreter::infoValue(const string &Name) {
1004 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1005 if (!PickedVal) return;
1008 print(PickedVal->getType(),
1009 getOperandValue(PickedVal, ECStack[CurFrame]));
1011 printOperandInfo(PickedVal, ECStack[CurFrame]);
1014 void Interpreter::list() {
1015 if (ECStack.empty())
1016 cout << "Error: No program executing!\n";
1018 cout << ECStack[CurFrame].CurMethod; // Just print the method out...
1021 void Interpreter::printStackTrace() {
1022 if (ECStack.empty()) cout << "No program executing!\n";
1024 for (unsigned i = 0; i < ECStack.size(); ++i) {
1025 cout << (((int)i == CurFrame) ? '>' : '-');
1026 cout << "#" << i << ". " << ECStack[i].CurMethod->getType() << " \""
1027 << ECStack[i].CurMethod->getName() << "\"(";
1029 cout << ")" << endl;
1030 cout << *ECStack[i].CurInst;