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/Module.h"
10 #include "llvm/Instructions.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Constants.h"
13 #include "llvm/Assembly/Writer.h"
14 #include "Support/CommandLine.h"
15 #include "Support/Statistic.h"
16 #include <math.h> // For fmod
20 Interpreter *TheEE = 0;
23 Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
26 QuietMode("quiet", cl::desc("Do not emit any non-program output"),
30 QuietModeA("q", cl::desc("Alias for -quiet"), cl::aliasopt(QuietMode));
33 ArrayChecksEnabled("array-checks", cl::desc("Enable array bound checks"));
36 // Create a TargetData structure to handle memory addressing and size/alignment
39 CachedWriter CW; // Object to accelerate printing of LLVM
41 sigjmp_buf SignalRecoverBuffer;
42 static bool InInstruction = false;
45 static void SigHandler(int Signal) {
47 siglongjmp(SignalRecoverBuffer, Signal);
51 static void initializeSignalHandlers() {
52 struct sigaction Action;
53 Action.sa_handler = SigHandler;
54 Action.sa_flags = SA_SIGINFO;
55 sigemptyset(&Action.sa_mask);
56 sigaction(SIGSEGV, &Action, 0);
57 sigaction(SIGBUS, &Action, 0);
58 sigaction(SIGINT, &Action, 0);
59 sigaction(SIGFPE, &Action, 0);
63 //===----------------------------------------------------------------------===//
64 // Value Manipulation code
65 //===----------------------------------------------------------------------===//
67 static unsigned getOperandSlot(Value *V) {
68 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
69 assert(SN && "Operand does not have a slot number annotation!");
73 // Operations used by constant expr implementations...
74 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
75 ExecutionContext &SF);
76 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
80 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
81 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
82 switch (CE->getOpcode()) {
83 case Instruction::Cast:
84 return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
85 case Instruction::GetElementPtr:
86 return TheEE->executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
88 case Instruction::Add:
89 return executeAddInst(getOperandValue(CE->getOperand(0), SF),
90 getOperandValue(CE->getOperand(1), SF),
93 std::cerr << "Unhandled ConstantExpr: " << CE << "\n";
95 return GenericValue();
97 } else if (Constant *CPV = dyn_cast<Constant>(V)) {
98 return TheEE->getConstantValue(CPV);
99 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
100 return PTOGV(TheEE->getPointerToGlobal(GV));
102 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
103 unsigned OpSlot = getOperandSlot(V);
104 assert(TyP < SF.Values.size() &&
105 OpSlot < SF.Values[TyP].size() && "Value out of range!");
106 return SF.Values[TyP][getOperandSlot(V)];
110 static void printOperandInfo(Value *V, ExecutionContext &SF) {
111 if (isa<Constant>(V)) {
112 std::cout << "Constant Pool Value\n";
113 } else if (isa<GlobalValue>(V)) {
114 std::cout << "Global Value\n";
116 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
117 unsigned Slot = getOperandSlot(V);
118 std::cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
119 << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF
122 const unsigned char *Buf = (const unsigned char*)&SF.Values[TyP][Slot];
123 for (unsigned i = 0; i < sizeof(GenericValue); ++i) {
124 unsigned char Cur = Buf[i];
125 std::cout << ( Cur >= 160?char((Cur>>4)+'A'-10):char((Cur>>4) + '0'))
126 << ((Cur&15) >= 10?char((Cur&15)+'A'-10):char((Cur&15) + '0'));
134 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
135 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
137 //std::cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)]<< "\n";
138 SF.Values[TyP][getOperandSlot(V)] = Val;
142 //===----------------------------------------------------------------------===//
143 // Annotation Wrangling code
144 //===----------------------------------------------------------------------===//
146 void Interpreter::initializeExecutionEngine() {
148 AnnotationManager::registerAnnotationFactory(FunctionInfoAID,
149 &FunctionInfo::Create);
150 initializeSignalHandlers();
153 //===----------------------------------------------------------------------===//
154 // Binary Instruction Implementations
155 //===----------------------------------------------------------------------===//
157 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
158 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
160 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
163 switch (Ty->getPrimitiveID()) {
164 IMPLEMENT_BINARY_OPERATOR(+, UByte);
165 IMPLEMENT_BINARY_OPERATOR(+, SByte);
166 IMPLEMENT_BINARY_OPERATOR(+, UShort);
167 IMPLEMENT_BINARY_OPERATOR(+, Short);
168 IMPLEMENT_BINARY_OPERATOR(+, UInt);
169 IMPLEMENT_BINARY_OPERATOR(+, Int);
170 IMPLEMENT_BINARY_OPERATOR(+, ULong);
171 IMPLEMENT_BINARY_OPERATOR(+, Long);
172 IMPLEMENT_BINARY_OPERATOR(+, Float);
173 IMPLEMENT_BINARY_OPERATOR(+, Double);
175 std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
181 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
184 switch (Ty->getPrimitiveID()) {
185 IMPLEMENT_BINARY_OPERATOR(-, UByte);
186 IMPLEMENT_BINARY_OPERATOR(-, SByte);
187 IMPLEMENT_BINARY_OPERATOR(-, UShort);
188 IMPLEMENT_BINARY_OPERATOR(-, Short);
189 IMPLEMENT_BINARY_OPERATOR(-, UInt);
190 IMPLEMENT_BINARY_OPERATOR(-, Int);
191 IMPLEMENT_BINARY_OPERATOR(-, ULong);
192 IMPLEMENT_BINARY_OPERATOR(-, Long);
193 IMPLEMENT_BINARY_OPERATOR(-, Float);
194 IMPLEMENT_BINARY_OPERATOR(-, Double);
196 std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
202 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
205 switch (Ty->getPrimitiveID()) {
206 IMPLEMENT_BINARY_OPERATOR(*, UByte);
207 IMPLEMENT_BINARY_OPERATOR(*, SByte);
208 IMPLEMENT_BINARY_OPERATOR(*, UShort);
209 IMPLEMENT_BINARY_OPERATOR(*, Short);
210 IMPLEMENT_BINARY_OPERATOR(*, UInt);
211 IMPLEMENT_BINARY_OPERATOR(*, Int);
212 IMPLEMENT_BINARY_OPERATOR(*, ULong);
213 IMPLEMENT_BINARY_OPERATOR(*, Long);
214 IMPLEMENT_BINARY_OPERATOR(*, Float);
215 IMPLEMENT_BINARY_OPERATOR(*, Double);
217 std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
223 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
226 switch (Ty->getPrimitiveID()) {
227 IMPLEMENT_BINARY_OPERATOR(/, UByte);
228 IMPLEMENT_BINARY_OPERATOR(/, SByte);
229 IMPLEMENT_BINARY_OPERATOR(/, UShort);
230 IMPLEMENT_BINARY_OPERATOR(/, Short);
231 IMPLEMENT_BINARY_OPERATOR(/, UInt);
232 IMPLEMENT_BINARY_OPERATOR(/, Int);
233 IMPLEMENT_BINARY_OPERATOR(/, ULong);
234 IMPLEMENT_BINARY_OPERATOR(/, Long);
235 IMPLEMENT_BINARY_OPERATOR(/, Float);
236 IMPLEMENT_BINARY_OPERATOR(/, Double);
238 std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
244 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
247 switch (Ty->getPrimitiveID()) {
248 IMPLEMENT_BINARY_OPERATOR(%, UByte);
249 IMPLEMENT_BINARY_OPERATOR(%, SByte);
250 IMPLEMENT_BINARY_OPERATOR(%, UShort);
251 IMPLEMENT_BINARY_OPERATOR(%, Short);
252 IMPLEMENT_BINARY_OPERATOR(%, UInt);
253 IMPLEMENT_BINARY_OPERATOR(%, Int);
254 IMPLEMENT_BINARY_OPERATOR(%, ULong);
255 IMPLEMENT_BINARY_OPERATOR(%, Long);
256 case Type::FloatTyID:
257 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
259 case Type::DoubleTyID:
260 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
263 std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
269 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
272 switch (Ty->getPrimitiveID()) {
273 IMPLEMENT_BINARY_OPERATOR(&, Bool);
274 IMPLEMENT_BINARY_OPERATOR(&, UByte);
275 IMPLEMENT_BINARY_OPERATOR(&, SByte);
276 IMPLEMENT_BINARY_OPERATOR(&, UShort);
277 IMPLEMENT_BINARY_OPERATOR(&, Short);
278 IMPLEMENT_BINARY_OPERATOR(&, UInt);
279 IMPLEMENT_BINARY_OPERATOR(&, Int);
280 IMPLEMENT_BINARY_OPERATOR(&, ULong);
281 IMPLEMENT_BINARY_OPERATOR(&, Long);
283 std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
290 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
293 switch (Ty->getPrimitiveID()) {
294 IMPLEMENT_BINARY_OPERATOR(|, Bool);
295 IMPLEMENT_BINARY_OPERATOR(|, UByte);
296 IMPLEMENT_BINARY_OPERATOR(|, SByte);
297 IMPLEMENT_BINARY_OPERATOR(|, UShort);
298 IMPLEMENT_BINARY_OPERATOR(|, Short);
299 IMPLEMENT_BINARY_OPERATOR(|, UInt);
300 IMPLEMENT_BINARY_OPERATOR(|, Int);
301 IMPLEMENT_BINARY_OPERATOR(|, ULong);
302 IMPLEMENT_BINARY_OPERATOR(|, Long);
304 std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
311 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
314 switch (Ty->getPrimitiveID()) {
315 IMPLEMENT_BINARY_OPERATOR(^, Bool);
316 IMPLEMENT_BINARY_OPERATOR(^, UByte);
317 IMPLEMENT_BINARY_OPERATOR(^, SByte);
318 IMPLEMENT_BINARY_OPERATOR(^, UShort);
319 IMPLEMENT_BINARY_OPERATOR(^, Short);
320 IMPLEMENT_BINARY_OPERATOR(^, UInt);
321 IMPLEMENT_BINARY_OPERATOR(^, Int);
322 IMPLEMENT_BINARY_OPERATOR(^, ULong);
323 IMPLEMENT_BINARY_OPERATOR(^, Long);
325 std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
332 #define IMPLEMENT_SETCC(OP, TY) \
333 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
335 // Handle pointers specially because they must be compared with only as much
336 // width as the host has. We _do not_ want to be comparing 64 bit values when
337 // running on a 32-bit target, otherwise the upper 32 bits might mess up
338 // comparisons if they contain garbage.
339 #define IMPLEMENT_POINTERSETCC(OP) \
340 case Type::PointerTyID: \
341 Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
342 (void*)(intptr_t)Src2.PointerVal; break
344 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
347 switch (Ty->getPrimitiveID()) {
348 IMPLEMENT_SETCC(==, UByte);
349 IMPLEMENT_SETCC(==, SByte);
350 IMPLEMENT_SETCC(==, UShort);
351 IMPLEMENT_SETCC(==, Short);
352 IMPLEMENT_SETCC(==, UInt);
353 IMPLEMENT_SETCC(==, Int);
354 IMPLEMENT_SETCC(==, ULong);
355 IMPLEMENT_SETCC(==, Long);
356 IMPLEMENT_SETCC(==, Float);
357 IMPLEMENT_SETCC(==, Double);
358 IMPLEMENT_POINTERSETCC(==);
360 std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
366 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
369 switch (Ty->getPrimitiveID()) {
370 IMPLEMENT_SETCC(!=, UByte);
371 IMPLEMENT_SETCC(!=, SByte);
372 IMPLEMENT_SETCC(!=, UShort);
373 IMPLEMENT_SETCC(!=, Short);
374 IMPLEMENT_SETCC(!=, UInt);
375 IMPLEMENT_SETCC(!=, Int);
376 IMPLEMENT_SETCC(!=, ULong);
377 IMPLEMENT_SETCC(!=, Long);
378 IMPLEMENT_SETCC(!=, Float);
379 IMPLEMENT_SETCC(!=, Double);
380 IMPLEMENT_POINTERSETCC(!=);
383 std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
389 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
392 switch (Ty->getPrimitiveID()) {
393 IMPLEMENT_SETCC(<=, UByte);
394 IMPLEMENT_SETCC(<=, SByte);
395 IMPLEMENT_SETCC(<=, UShort);
396 IMPLEMENT_SETCC(<=, Short);
397 IMPLEMENT_SETCC(<=, UInt);
398 IMPLEMENT_SETCC(<=, Int);
399 IMPLEMENT_SETCC(<=, ULong);
400 IMPLEMENT_SETCC(<=, Long);
401 IMPLEMENT_SETCC(<=, Float);
402 IMPLEMENT_SETCC(<=, Double);
403 IMPLEMENT_POINTERSETCC(<=);
405 std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
411 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
414 switch (Ty->getPrimitiveID()) {
415 IMPLEMENT_SETCC(>=, UByte);
416 IMPLEMENT_SETCC(>=, SByte);
417 IMPLEMENT_SETCC(>=, UShort);
418 IMPLEMENT_SETCC(>=, Short);
419 IMPLEMENT_SETCC(>=, UInt);
420 IMPLEMENT_SETCC(>=, Int);
421 IMPLEMENT_SETCC(>=, ULong);
422 IMPLEMENT_SETCC(>=, Long);
423 IMPLEMENT_SETCC(>=, Float);
424 IMPLEMENT_SETCC(>=, Double);
425 IMPLEMENT_POINTERSETCC(>=);
427 std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
433 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
436 switch (Ty->getPrimitiveID()) {
437 IMPLEMENT_SETCC(<, UByte);
438 IMPLEMENT_SETCC(<, SByte);
439 IMPLEMENT_SETCC(<, UShort);
440 IMPLEMENT_SETCC(<, Short);
441 IMPLEMENT_SETCC(<, UInt);
442 IMPLEMENT_SETCC(<, Int);
443 IMPLEMENT_SETCC(<, ULong);
444 IMPLEMENT_SETCC(<, Long);
445 IMPLEMENT_SETCC(<, Float);
446 IMPLEMENT_SETCC(<, Double);
447 IMPLEMENT_POINTERSETCC(<);
449 std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
455 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
458 switch (Ty->getPrimitiveID()) {
459 IMPLEMENT_SETCC(>, UByte);
460 IMPLEMENT_SETCC(>, SByte);
461 IMPLEMENT_SETCC(>, UShort);
462 IMPLEMENT_SETCC(>, Short);
463 IMPLEMENT_SETCC(>, UInt);
464 IMPLEMENT_SETCC(>, Int);
465 IMPLEMENT_SETCC(>, ULong);
466 IMPLEMENT_SETCC(>, Long);
467 IMPLEMENT_SETCC(>, Float);
468 IMPLEMENT_SETCC(>, Double);
469 IMPLEMENT_POINTERSETCC(>);
471 std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
477 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
478 ExecutionContext &SF = ECStack.back();
479 const Type *Ty = I.getOperand(0)->getType();
480 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
481 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
482 GenericValue R; // Result
484 switch (I.getOpcode()) {
485 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty); break;
486 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty); break;
487 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty); break;
488 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty); break;
489 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty); break;
490 case Instruction::And: R = executeAndInst (Src1, Src2, Ty); break;
491 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty); break;
492 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty); break;
493 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
494 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
495 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
496 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
497 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
498 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
500 std::cout << "Don't know how to handle this binary operator!\n-->" << I;
507 //===----------------------------------------------------------------------===//
508 // Terminator Instruction Implementations
509 //===----------------------------------------------------------------------===//
511 void Interpreter::exitCalled(GenericValue GV) {
513 std::cout << "Program returned ";
514 print(Type::IntTy, GV);
515 std::cout << " via 'void exit(int)'\n";
518 ExitCode = GV.SByteVal;
522 void Interpreter::visitReturnInst(ReturnInst &I) {
523 ExecutionContext &SF = ECStack.back();
524 const Type *RetTy = 0;
527 // Save away the return value... (if we are not 'ret void')
528 if (I.getNumOperands()) {
529 RetTy = I.getReturnValue()->getType();
530 Result = getOperandValue(I.getReturnValue(), SF);
533 // Save previously executing meth
534 const Function *M = ECStack.back().CurFunction;
536 // Pop the current stack frame... this invalidates SF
539 if (ECStack.empty()) { // Finished main. Put result into exit code...
540 if (RetTy) { // Nonvoid return type?
542 CW << "Function " << M->getType() << " \"" << M->getName()
544 print(RetTy, Result);
548 if (RetTy->isIntegral())
549 ExitCode = Result.IntVal; // Capture the exit code of the program
556 // If we have a previous stack frame, and we have a previous call, fill in
557 // the return value...
559 ExecutionContext &NewSF = ECStack.back();
561 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
562 SetValue(NewSF.Caller, Result, NewSF);
564 NewSF.Caller = 0; // We returned from the call...
565 } else if (!QuietMode) {
566 // This must be a function that is executing because of a user 'call'
568 CW << "Function " << M->getType() << " \"" << M->getName()
570 print(RetTy, Result);
575 void Interpreter::visitBranchInst(BranchInst &I) {
576 ExecutionContext &SF = ECStack.back();
579 Dest = I.getSuccessor(0); // Uncond branches have a fixed dest...
580 if (!I.isUnconditional()) {
581 Value *Cond = I.getCondition();
582 if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
583 Dest = I.getSuccessor(1);
585 SwitchToNewBasicBlock(Dest, SF);
588 void Interpreter::visitSwitchInst(SwitchInst &I) {
589 ExecutionContext &SF = ECStack.back();
590 GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
591 const Type *ElTy = I.getOperand(0)->getType();
593 // Check to see if any of the cases match...
594 BasicBlock *Dest = 0;
595 for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
596 if (executeSetEQInst(CondVal,
597 getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
598 Dest = cast<BasicBlock>(I.getOperand(i+1));
602 if (!Dest) Dest = I.getDefaultDest(); // No cases matched: use default
603 SwitchToNewBasicBlock(Dest, SF);
606 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
607 // This function handles the actual updating of block and instruction iterators
608 // as well as execution of all of the PHI nodes in the destination block.
610 // This method does this because all of the PHI nodes must be executed
611 // atomically, reading their inputs before any of the results are updated. Not
612 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
613 // their inputs. If the input PHI node is updated before it is read, incorrect
614 // results can happen. Thus we use a two phase approach.
616 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
617 BasicBlock *PrevBB = SF.CurBB; // Remember where we came from...
618 SF.CurBB = Dest; // Update CurBB to branch destination
619 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
621 if (!isa<PHINode>(SF.CurInst)) return; // Nothing fancy to do
623 // Loop over all of the PHI nodes in the current block, reading their inputs.
624 std::vector<GenericValue> ResultValues;
626 for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
627 if (Trace) CW << "Run:" << PN;
629 // Search for the value corresponding to this previous bb...
630 int i = PN->getBasicBlockIndex(PrevBB);
631 assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
632 Value *IncomingValue = PN->getIncomingValue(i);
634 // Save the incoming value for this PHI node...
635 ResultValues.push_back(getOperandValue(IncomingValue, SF));
638 // Now loop over all of the PHI nodes setting their values...
639 SF.CurInst = SF.CurBB->begin();
640 for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
642 SetValue(PN, ResultValues[i], SF);
646 //===----------------------------------------------------------------------===//
647 // Memory Instruction Implementations
648 //===----------------------------------------------------------------------===//
650 void Interpreter::visitAllocationInst(AllocationInst &I) {
651 ExecutionContext &SF = ECStack.back();
653 const Type *Ty = I.getType()->getElementType(); // Type to be allocated
655 // Get the number of elements being allocated by the array...
656 unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
658 // Allocate enough memory to hold the type...
659 // FIXME: Don't use CALLOC, use a tainted malloc.
660 void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
662 GenericValue Result = PTOGV(Memory);
663 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
664 SetValue(&I, Result, SF);
666 if (I.getOpcode() == Instruction::Alloca)
667 ECStack.back().Allocas.add(Memory);
670 void Interpreter::visitFreeInst(FreeInst &I) {
671 ExecutionContext &SF = ECStack.back();
672 assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
673 GenericValue Value = getOperandValue(I.getOperand(0), SF);
674 // TODO: Check to make sure memory is allocated
675 free(GVTOP(Value)); // Free memory
679 // getElementOffset - The workhorse for getelementptr.
681 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
683 ExecutionContext &SF) {
684 assert(isa<PointerType>(Ptr->getType()) &&
685 "Cannot getElementOffset of a nonpointer type!");
688 const Type *Ty = Ptr->getType();
690 for (; I != E; ++I) {
691 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
692 const StructLayout *SLO = TD.getStructLayout(STy);
694 // Indicies must be ubyte constants...
695 const ConstantUInt *CPU = cast<ConstantUInt>(*I);
696 assert(CPU->getType() == Type::UByteTy);
697 unsigned Index = CPU->getValue();
699 Total += SLO->MemberOffsets[Index];
700 Ty = STy->getElementTypes()[Index];
701 } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
703 // Get the index number for the array... which must be long type...
704 assert((*I)->getType() == Type::LongTy);
705 unsigned Idx = getOperandValue(*I, SF).LongVal;
706 if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
707 if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
708 std::cerr << "Out of range memory access to element #" << Idx
709 << " of a " << AT->getNumElements() << " element array."
710 << " Subscript #" << *I << "\n";
712 siglongjmp(SignalRecoverBuffer, SIGTRAP);
715 Ty = ST->getElementType();
716 unsigned Size = TD.getTypeSize(Ty);
722 Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
726 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
727 ExecutionContext &SF = ECStack.back();
728 SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
729 I.idx_begin(), I.idx_end(), SF), SF);
732 void Interpreter::visitLoadInst(LoadInst &I) {
733 ExecutionContext &SF = ECStack.back();
734 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
735 GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
736 GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
737 SetValue(&I, Result, SF);
740 void Interpreter::visitStoreInst(StoreInst &I) {
741 ExecutionContext &SF = ECStack.back();
742 GenericValue Val = getOperandValue(I.getOperand(0), SF);
743 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
744 StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
745 I.getOperand(0)->getType());
750 //===----------------------------------------------------------------------===//
751 // Miscellaneous Instruction Implementations
752 //===----------------------------------------------------------------------===//
754 void Interpreter::visitCallInst(CallInst &I) {
755 ExecutionContext &SF = ECStack.back();
757 std::vector<GenericValue> ArgVals;
758 ArgVals.reserve(I.getNumOperands()-1);
759 for (unsigned i = 1; i < I.getNumOperands(); ++i) {
760 ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
761 // Promote all integral types whose size is < sizeof(int) into ints. We do
762 // this by zero or sign extending the value as appropriate according to the
764 if (I.getOperand(i)->getType()->isIntegral() &&
765 I.getOperand(i)->getType()->getPrimitiveSize() < 4) {
766 const Type *Ty = I.getOperand(i)->getType();
767 if (Ty == Type::ShortTy)
768 ArgVals.back().IntVal = ArgVals.back().ShortVal;
769 else if (Ty == Type::UShortTy)
770 ArgVals.back().UIntVal = ArgVals.back().UShortVal;
771 else if (Ty == Type::SByteTy)
772 ArgVals.back().IntVal = ArgVals.back().SByteVal;
773 else if (Ty == Type::UByteTy)
774 ArgVals.back().UIntVal = ArgVals.back().UByteVal;
775 else if (Ty == Type::BoolTy)
776 ArgVals.back().UIntVal = ArgVals.back().BoolVal;
778 assert(0 && "Unknown type!");
782 // To handle indirect calls, we must get the pointer value from the argument
783 // and treat it as a function pointer.
784 GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
785 callFunction((Function*)GVTOP(SRC), ArgVals);
788 #define IMPLEMENT_SHIFT(OP, TY) \
789 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
791 void Interpreter::visitShl(ShiftInst &I) {
792 ExecutionContext &SF = ECStack.back();
793 const Type *Ty = I.getOperand(0)->getType();
794 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
795 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
798 switch (Ty->getPrimitiveID()) {
799 IMPLEMENT_SHIFT(<<, UByte);
800 IMPLEMENT_SHIFT(<<, SByte);
801 IMPLEMENT_SHIFT(<<, UShort);
802 IMPLEMENT_SHIFT(<<, Short);
803 IMPLEMENT_SHIFT(<<, UInt);
804 IMPLEMENT_SHIFT(<<, Int);
805 IMPLEMENT_SHIFT(<<, ULong);
806 IMPLEMENT_SHIFT(<<, Long);
808 std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
810 SetValue(&I, Dest, SF);
813 void Interpreter::visitShr(ShiftInst &I) {
814 ExecutionContext &SF = ECStack.back();
815 const Type *Ty = I.getOperand(0)->getType();
816 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
817 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
820 switch (Ty->getPrimitiveID()) {
821 IMPLEMENT_SHIFT(>>, UByte);
822 IMPLEMENT_SHIFT(>>, SByte);
823 IMPLEMENT_SHIFT(>>, UShort);
824 IMPLEMENT_SHIFT(>>, Short);
825 IMPLEMENT_SHIFT(>>, UInt);
826 IMPLEMENT_SHIFT(>>, Int);
827 IMPLEMENT_SHIFT(>>, ULong);
828 IMPLEMENT_SHIFT(>>, Long);
830 std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
833 SetValue(&I, Dest, SF);
836 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
837 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
839 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
840 case Type::DESTTY##TyID: \
841 switch (SrcTy->getPrimitiveID()) { \
842 IMPLEMENT_CAST(DESTTY, DESTCTY, Bool); \
843 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
844 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
845 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
846 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
847 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
848 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
849 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
850 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
851 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
853 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
854 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
855 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
857 #define IMPLEMENT_CAST_CASE_END() \
858 default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
863 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
864 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
865 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
866 IMPLEMENT_CAST_CASE_END()
868 static GenericValue executeCastOperation(Value *SrcVal, const Type *Ty,
869 ExecutionContext &SF) {
870 const Type *SrcTy = SrcVal->getType();
871 GenericValue Dest, Src = getOperandValue(SrcVal, SF);
873 switch (Ty->getPrimitiveID()) {
874 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
875 IMPLEMENT_CAST_CASE(SByte , ( signed char));
876 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
877 IMPLEMENT_CAST_CASE(Short , ( signed short));
878 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
879 IMPLEMENT_CAST_CASE(Int , ( signed int ));
880 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
881 IMPLEMENT_CAST_CASE(Long , ( int64_t));
882 IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
883 IMPLEMENT_CAST_CASE(Float , (float));
884 IMPLEMENT_CAST_CASE(Double , (double));
885 IMPLEMENT_CAST_CASE(Bool , (bool));
887 std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
895 void Interpreter::visitCastInst(CastInst &I) {
896 ExecutionContext &SF = ECStack.back();
897 SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
900 void Interpreter::visitVarArgInst(VarArgInst &I) {
901 ExecutionContext &SF = ECStack.back();
903 // Get the pointer to the valist element. LLI treats the valist in memory as
905 GenericValue VAListPtr = getOperandValue(I.getOperand(0), SF);
908 GenericValue VAList =
909 TheEE->LoadValueFromMemory((GenericValue *)GVTOP(VAListPtr), Type::UIntTy);
911 unsigned Argument = VAList.IntVal++;
913 // Update the valist to point to the next argument...
914 TheEE->StoreValueToMemory(VAList, (GenericValue *)GVTOP(VAListPtr),
918 assert(Argument < SF.VarArgs.size() &&
919 "Accessing past the last vararg argument!");
920 SetValue(&I, SF.VarArgs[Argument], SF);
923 //===----------------------------------------------------------------------===//
924 // Dispatch and Execution Code
925 //===----------------------------------------------------------------------===//
927 FunctionInfo::FunctionInfo(Function *F) : Annotation(FunctionInfoAID) {
928 // Assign slot numbers to the function arguments...
929 for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
930 AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
932 // Iterate over all of the instructions...
933 unsigned InstNum = 0;
934 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
935 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
936 // For each instruction... Add Annote
937 II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
940 unsigned FunctionInfo::getValueSlot(const Value *V) {
941 unsigned Plane = V->getType()->getUniqueID();
942 if (Plane >= NumPlaneElements.size())
943 NumPlaneElements.resize(Plane+1, 0);
944 return NumPlaneElements[Plane]++;
948 //===----------------------------------------------------------------------===//
949 // callFunction - Execute the specified function...
951 void Interpreter::callFunction(Function *F,
952 const std::vector<GenericValue> &ArgVals) {
953 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
954 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
955 "Incorrect number of arguments passed into function call!");
956 if (F->isExternal()) {
957 GenericValue Result = callExternalFunction(F, ArgVals);
958 const Type *RetTy = F->getReturnType();
960 // Copy the result back into the result variable if we are not returning
962 if (RetTy != Type::VoidTy) {
963 if (!ECStack.empty() && ECStack.back().Caller) {
964 ExecutionContext &SF = ECStack.back();
965 SetValue(SF.Caller, Result, SF);
967 SF.Caller = 0; // We returned from the call...
968 } else if (!QuietMode) {
970 CW << "Function " << F->getType() << " \"" << F->getName()
972 print(RetTy, Result);
975 if (RetTy->isIntegral())
976 ExitCode = Result.IntVal; // Capture the exit code of the program
983 // Process the function, assigning instruction numbers to the instructions in
984 // the function. Also calculate the number of values for each type slot
987 FunctionInfo *FuncInfo =
988 (FunctionInfo*)F->getOrCreateAnnotation(FunctionInfoAID);
989 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
991 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
992 StackFrame.CurFunction = F;
993 StackFrame.CurBB = F->begin();
994 StackFrame.CurInst = StackFrame.CurBB->begin();
995 StackFrame.FuncInfo = FuncInfo;
997 // Initialize the values to nothing...
998 StackFrame.Values.resize(FuncInfo->NumPlaneElements.size());
999 for (unsigned i = 0; i < FuncInfo->NumPlaneElements.size(); ++i) {
1000 StackFrame.Values[i].resize(FuncInfo->NumPlaneElements[i]);
1002 // Taint the initial values of stuff
1003 memset(&StackFrame.Values[i][0], 42,
1004 FuncInfo->NumPlaneElements[i]*sizeof(GenericValue));
1008 // Run through the function arguments and initialize their values...
1009 assert((ArgVals.size() == F->asize() ||
1010 (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
1011 "Invalid number of values passed to function invocation!");
1013 // Handle non-varargs arguments...
1015 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
1016 SetValue(AI, ArgVals[i], StackFrame);
1018 // Handle varargs arguments...
1019 StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
1022 // executeInstruction - Interpret a single instruction, increment the "PC", and
1023 // return true if the next instruction is a breakpoint...
1025 bool Interpreter::executeInstruction() {
1026 assert(!ECStack.empty() && "No program running, cannot execute inst!");
1028 ExecutionContext &SF = ECStack.back(); // Current stack frame
1029 Instruction &I = *SF.CurInst++; // Increment before execute
1031 if (Trace) CW << "Run:" << I;
1033 // Track the number of dynamic instructions executed.
1036 // Set a sigsetjmp buffer so that we can recover if an error happens during
1037 // instruction execution...
1039 if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1040 --SF.CurInst; // Back up to erroring instruction
1041 std::cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]\n";
1043 InInstruction = false;
1047 InInstruction = true;
1048 visit(I); // Dispatch to one of the visit* methods...
1049 InInstruction = false;
1051 // Reset the current frame location to the top of stack
1052 CurFrame = ECStack.size()-1;
1054 if (CurFrame == -1) return false; // No breakpoint if no code
1056 // Return true if there is a breakpoint annotation on the instruction...
1057 return ECStack[CurFrame].CurInst->getAnnotation(BreakpointAID) != 0;
1060 void Interpreter::stepInstruction() { // Do the 'step' command
1061 if (ECStack.empty()) {
1062 std::cout << "Error: no program running, cannot step!\n";
1066 // Run an instruction...
1067 executeInstruction();
1069 // Print the next instruction to execute...
1070 printCurrentInstruction();
1074 void Interpreter::nextInstruction() { // Do the 'next' command
1075 if (ECStack.empty()) {
1076 std::cout << "Error: no program running, cannot 'next'!\n";
1080 // If this is a call instruction, step over the call instruction...
1081 // TODO: ICALL, CALL WITH, ...
1082 if (ECStack.back().CurInst->getOpcode() == Instruction::Call) {
1083 unsigned StackSize = ECStack.size();
1084 // Step into the function...
1085 if (executeInstruction()) {
1086 // Hit a breakpoint, print current instruction, then return to user...
1087 std::cout << "Breakpoint hit!\n";
1088 printCurrentInstruction();
1092 // If we we able to step into the function, finish it now. We might not be
1093 // able the step into a function, if it's external for example.
1094 if (ECStack.size() != StackSize)
1095 finish(); // Finish executing the function...
1097 printCurrentInstruction();
1100 // Normal instruction, just step...
1105 void Interpreter::run() {
1106 if (ECStack.empty()) {
1107 std::cout << "Error: no program running, cannot run!\n";
1111 bool HitBreakpoint = false;
1112 while (!ECStack.empty() && !HitBreakpoint) {
1113 // Run an instruction...
1114 HitBreakpoint = executeInstruction();
1118 std::cout << "Breakpoint hit!\n";
1120 // Print the next instruction to execute...
1121 printCurrentInstruction();
1124 void Interpreter::finish() {
1125 if (ECStack.empty()) {
1126 std::cout << "Error: no program running, cannot run!\n";
1130 unsigned StackSize = ECStack.size();
1131 bool HitBreakpoint = false;
1132 while (ECStack.size() >= StackSize && !HitBreakpoint) {
1133 // Run an instruction...
1134 HitBreakpoint = executeInstruction();
1138 std::cout << "Breakpoint hit!\n";
1140 // Print the next instruction to execute...
1141 printCurrentInstruction();
1146 // printCurrentInstruction - Print out the instruction that the virtual PC is
1147 // at, or fail silently if no program is running.
1149 void Interpreter::printCurrentInstruction() {
1150 if (!ECStack.empty()) {
1151 if (ECStack.back().CurBB->begin() == ECStack.back().CurInst) // print label
1152 WriteAsOperand(std::cout, ECStack.back().CurBB) << ":\n";
1154 Instruction &I = *ECStack.back().CurInst;
1155 InstNumber *IN = (InstNumber*)I.getAnnotation(SlotNumberAID);
1156 assert(IN && "Instruction has no numbering annotation!");
1157 std::cout << "#" << IN->InstNum << I;
1161 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1162 switch (Ty->getPrimitiveID()) {
1163 case Type::BoolTyID: std::cout << (V.BoolVal?"true":"false"); break;
1164 case Type::SByteTyID:
1165 std::cout << (int)V.SByteVal << " '" << V.SByteVal << "'"; break;
1166 case Type::UByteTyID:
1167 std::cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'"; break;
1168 case Type::ShortTyID: std::cout << V.ShortVal; break;
1169 case Type::UShortTyID: std::cout << V.UShortVal; break;
1170 case Type::IntTyID: std::cout << V.IntVal; break;
1171 case Type::UIntTyID: std::cout << V.UIntVal; break;
1172 case Type::LongTyID: std::cout << (long)V.LongVal; break;
1173 case Type::ULongTyID: std::cout << (unsigned long)V.ULongVal; break;
1174 case Type::FloatTyID: std::cout << V.FloatVal; break;
1175 case Type::DoubleTyID: std::cout << V.DoubleVal; break;
1176 case Type::PointerTyID:std::cout << (void*)GVTOP(V); break;
1178 std::cout << "- Don't know how to print value of this type!";
1183 void Interpreter::print(const Type *Ty, GenericValue V) {
1188 void Interpreter::print(const std::string &Name) {
1189 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1190 if (!PickedVal) return;
1192 if (const Function *F = dyn_cast<Function>(PickedVal)) {
1193 CW << F; // Print the function
1194 } else if (const Type *Ty = dyn_cast<Type>(PickedVal)) {
1195 CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
1196 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(PickedVal)) {
1197 CW << BB; // Print the basic block
1198 } else { // Otherwise there should be an annotation for the slot#
1199 print(PickedVal->getType(),
1200 getOperandValue(PickedVal, ECStack[CurFrame]));
1205 void Interpreter::infoValue(const std::string &Name) {
1206 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1207 if (!PickedVal) return;
1209 std::cout << "Value: ";
1210 print(PickedVal->getType(),
1211 getOperandValue(PickedVal, ECStack[CurFrame]));
1213 printOperandInfo(PickedVal, ECStack[CurFrame]);
1216 // printStackFrame - Print information about the specified stack frame, or -1
1217 // for the default one.
1219 void Interpreter::printStackFrame(int FrameNo) {
1220 if (FrameNo == -1) FrameNo = CurFrame;
1221 Function *F = ECStack[FrameNo].CurFunction;
1222 const Type *RetTy = F->getReturnType();
1224 CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1225 << (Value*)RetTy << " \"" << F->getName() << "\"(";
1228 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++i) {
1229 if (i != 0) std::cout << ", ";
1232 printValue(I->getType(), getOperandValue(I, ECStack[FrameNo]));
1237 if (FrameNo != int(ECStack.size()-1)) {
1238 BasicBlock::iterator I = ECStack[FrameNo].CurInst;
1241 CW << *ECStack[FrameNo].CurInst;