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 <cmath> // For fmod
18 Interpreter *TheEE = 0;
21 Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
24 QuietMode("quiet", cl::desc("Do not emit any non-program output"),
28 QuietModeA("q", cl::desc("Alias for -quiet"), cl::aliasopt(QuietMode));
31 ArrayChecksEnabled("array-checks", cl::desc("Enable array bound checks"));
34 // Create a TargetData structure to handle memory addressing and size/alignment
37 CachedWriter CW; // Object to accelerate printing of LLVM
40 //===----------------------------------------------------------------------===//
41 // Value Manipulation code
42 //===----------------------------------------------------------------------===//
44 static unsigned getOperandSlot(Value *V) {
45 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
46 assert(SN && "Operand does not have a slot number annotation!");
50 // Operations used by constant expr implementations...
51 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
52 ExecutionContext &SF);
53 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
57 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
58 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
59 switch (CE->getOpcode()) {
60 case Instruction::Cast:
61 return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
62 case Instruction::GetElementPtr:
63 return TheEE->executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
65 case Instruction::Add:
66 return executeAddInst(getOperandValue(CE->getOperand(0), SF),
67 getOperandValue(CE->getOperand(1), SF),
70 std::cerr << "Unhandled ConstantExpr: " << CE << "\n";
72 return GenericValue();
74 } else if (Constant *CPV = dyn_cast<Constant>(V)) {
75 return TheEE->getConstantValue(CPV);
76 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
77 return PTOGV(TheEE->getPointerToGlobal(GV));
79 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
80 unsigned OpSlot = getOperandSlot(V);
81 assert(TyP < SF.Values.size() &&
82 OpSlot < SF.Values[TyP].size() && "Value out of range!");
83 return SF.Values[TyP][getOperandSlot(V)];
87 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
88 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
90 //std::cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)]<< "\n";
91 SF.Values[TyP][getOperandSlot(V)] = Val;
94 //===----------------------------------------------------------------------===//
95 // Annotation Wrangling code
96 //===----------------------------------------------------------------------===//
98 void Interpreter::initializeExecutionEngine() {
102 //===----------------------------------------------------------------------===//
103 // Binary Instruction Implementations
104 //===----------------------------------------------------------------------===//
106 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
107 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
109 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
112 switch (Ty->getPrimitiveID()) {
113 IMPLEMENT_BINARY_OPERATOR(+, UByte);
114 IMPLEMENT_BINARY_OPERATOR(+, SByte);
115 IMPLEMENT_BINARY_OPERATOR(+, UShort);
116 IMPLEMENT_BINARY_OPERATOR(+, Short);
117 IMPLEMENT_BINARY_OPERATOR(+, UInt);
118 IMPLEMENT_BINARY_OPERATOR(+, Int);
119 IMPLEMENT_BINARY_OPERATOR(+, ULong);
120 IMPLEMENT_BINARY_OPERATOR(+, Long);
121 IMPLEMENT_BINARY_OPERATOR(+, Float);
122 IMPLEMENT_BINARY_OPERATOR(+, Double);
124 std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
130 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
133 switch (Ty->getPrimitiveID()) {
134 IMPLEMENT_BINARY_OPERATOR(-, UByte);
135 IMPLEMENT_BINARY_OPERATOR(-, SByte);
136 IMPLEMENT_BINARY_OPERATOR(-, UShort);
137 IMPLEMENT_BINARY_OPERATOR(-, Short);
138 IMPLEMENT_BINARY_OPERATOR(-, UInt);
139 IMPLEMENT_BINARY_OPERATOR(-, Int);
140 IMPLEMENT_BINARY_OPERATOR(-, ULong);
141 IMPLEMENT_BINARY_OPERATOR(-, Long);
142 IMPLEMENT_BINARY_OPERATOR(-, Float);
143 IMPLEMENT_BINARY_OPERATOR(-, Double);
145 std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
151 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
154 switch (Ty->getPrimitiveID()) {
155 IMPLEMENT_BINARY_OPERATOR(*, UByte);
156 IMPLEMENT_BINARY_OPERATOR(*, SByte);
157 IMPLEMENT_BINARY_OPERATOR(*, UShort);
158 IMPLEMENT_BINARY_OPERATOR(*, Short);
159 IMPLEMENT_BINARY_OPERATOR(*, UInt);
160 IMPLEMENT_BINARY_OPERATOR(*, Int);
161 IMPLEMENT_BINARY_OPERATOR(*, ULong);
162 IMPLEMENT_BINARY_OPERATOR(*, Long);
163 IMPLEMENT_BINARY_OPERATOR(*, Float);
164 IMPLEMENT_BINARY_OPERATOR(*, Double);
166 std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
172 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
175 switch (Ty->getPrimitiveID()) {
176 IMPLEMENT_BINARY_OPERATOR(/, UByte);
177 IMPLEMENT_BINARY_OPERATOR(/, SByte);
178 IMPLEMENT_BINARY_OPERATOR(/, UShort);
179 IMPLEMENT_BINARY_OPERATOR(/, Short);
180 IMPLEMENT_BINARY_OPERATOR(/, UInt);
181 IMPLEMENT_BINARY_OPERATOR(/, Int);
182 IMPLEMENT_BINARY_OPERATOR(/, ULong);
183 IMPLEMENT_BINARY_OPERATOR(/, Long);
184 IMPLEMENT_BINARY_OPERATOR(/, Float);
185 IMPLEMENT_BINARY_OPERATOR(/, Double);
187 std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
193 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
196 switch (Ty->getPrimitiveID()) {
197 IMPLEMENT_BINARY_OPERATOR(%, UByte);
198 IMPLEMENT_BINARY_OPERATOR(%, SByte);
199 IMPLEMENT_BINARY_OPERATOR(%, UShort);
200 IMPLEMENT_BINARY_OPERATOR(%, Short);
201 IMPLEMENT_BINARY_OPERATOR(%, UInt);
202 IMPLEMENT_BINARY_OPERATOR(%, Int);
203 IMPLEMENT_BINARY_OPERATOR(%, ULong);
204 IMPLEMENT_BINARY_OPERATOR(%, Long);
205 case Type::FloatTyID:
206 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
208 case Type::DoubleTyID:
209 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
212 std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
218 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
221 switch (Ty->getPrimitiveID()) {
222 IMPLEMENT_BINARY_OPERATOR(&, Bool);
223 IMPLEMENT_BINARY_OPERATOR(&, UByte);
224 IMPLEMENT_BINARY_OPERATOR(&, SByte);
225 IMPLEMENT_BINARY_OPERATOR(&, UShort);
226 IMPLEMENT_BINARY_OPERATOR(&, Short);
227 IMPLEMENT_BINARY_OPERATOR(&, UInt);
228 IMPLEMENT_BINARY_OPERATOR(&, Int);
229 IMPLEMENT_BINARY_OPERATOR(&, ULong);
230 IMPLEMENT_BINARY_OPERATOR(&, Long);
232 std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
239 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
242 switch (Ty->getPrimitiveID()) {
243 IMPLEMENT_BINARY_OPERATOR(|, Bool);
244 IMPLEMENT_BINARY_OPERATOR(|, UByte);
245 IMPLEMENT_BINARY_OPERATOR(|, SByte);
246 IMPLEMENT_BINARY_OPERATOR(|, UShort);
247 IMPLEMENT_BINARY_OPERATOR(|, Short);
248 IMPLEMENT_BINARY_OPERATOR(|, UInt);
249 IMPLEMENT_BINARY_OPERATOR(|, Int);
250 IMPLEMENT_BINARY_OPERATOR(|, ULong);
251 IMPLEMENT_BINARY_OPERATOR(|, Long);
253 std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
260 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
263 switch (Ty->getPrimitiveID()) {
264 IMPLEMENT_BINARY_OPERATOR(^, Bool);
265 IMPLEMENT_BINARY_OPERATOR(^, UByte);
266 IMPLEMENT_BINARY_OPERATOR(^, SByte);
267 IMPLEMENT_BINARY_OPERATOR(^, UShort);
268 IMPLEMENT_BINARY_OPERATOR(^, Short);
269 IMPLEMENT_BINARY_OPERATOR(^, UInt);
270 IMPLEMENT_BINARY_OPERATOR(^, Int);
271 IMPLEMENT_BINARY_OPERATOR(^, ULong);
272 IMPLEMENT_BINARY_OPERATOR(^, Long);
274 std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
281 #define IMPLEMENT_SETCC(OP, TY) \
282 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
284 // Handle pointers specially because they must be compared with only as much
285 // width as the host has. We _do not_ want to be comparing 64 bit values when
286 // running on a 32-bit target, otherwise the upper 32 bits might mess up
287 // comparisons if they contain garbage.
288 #define IMPLEMENT_POINTERSETCC(OP) \
289 case Type::PointerTyID: \
290 Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
291 (void*)(intptr_t)Src2.PointerVal; break
293 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
296 switch (Ty->getPrimitiveID()) {
297 IMPLEMENT_SETCC(==, UByte);
298 IMPLEMENT_SETCC(==, SByte);
299 IMPLEMENT_SETCC(==, UShort);
300 IMPLEMENT_SETCC(==, Short);
301 IMPLEMENT_SETCC(==, UInt);
302 IMPLEMENT_SETCC(==, Int);
303 IMPLEMENT_SETCC(==, ULong);
304 IMPLEMENT_SETCC(==, Long);
305 IMPLEMENT_SETCC(==, Float);
306 IMPLEMENT_SETCC(==, Double);
307 IMPLEMENT_POINTERSETCC(==);
309 std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
315 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
318 switch (Ty->getPrimitiveID()) {
319 IMPLEMENT_SETCC(!=, UByte);
320 IMPLEMENT_SETCC(!=, SByte);
321 IMPLEMENT_SETCC(!=, UShort);
322 IMPLEMENT_SETCC(!=, Short);
323 IMPLEMENT_SETCC(!=, UInt);
324 IMPLEMENT_SETCC(!=, Int);
325 IMPLEMENT_SETCC(!=, ULong);
326 IMPLEMENT_SETCC(!=, Long);
327 IMPLEMENT_SETCC(!=, Float);
328 IMPLEMENT_SETCC(!=, Double);
329 IMPLEMENT_POINTERSETCC(!=);
332 std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
338 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
341 switch (Ty->getPrimitiveID()) {
342 IMPLEMENT_SETCC(<=, UByte);
343 IMPLEMENT_SETCC(<=, SByte);
344 IMPLEMENT_SETCC(<=, UShort);
345 IMPLEMENT_SETCC(<=, Short);
346 IMPLEMENT_SETCC(<=, UInt);
347 IMPLEMENT_SETCC(<=, Int);
348 IMPLEMENT_SETCC(<=, ULong);
349 IMPLEMENT_SETCC(<=, Long);
350 IMPLEMENT_SETCC(<=, Float);
351 IMPLEMENT_SETCC(<=, Double);
352 IMPLEMENT_POINTERSETCC(<=);
354 std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
360 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
363 switch (Ty->getPrimitiveID()) {
364 IMPLEMENT_SETCC(>=, UByte);
365 IMPLEMENT_SETCC(>=, SByte);
366 IMPLEMENT_SETCC(>=, UShort);
367 IMPLEMENT_SETCC(>=, Short);
368 IMPLEMENT_SETCC(>=, UInt);
369 IMPLEMENT_SETCC(>=, Int);
370 IMPLEMENT_SETCC(>=, ULong);
371 IMPLEMENT_SETCC(>=, Long);
372 IMPLEMENT_SETCC(>=, Float);
373 IMPLEMENT_SETCC(>=, Double);
374 IMPLEMENT_POINTERSETCC(>=);
376 std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
382 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
385 switch (Ty->getPrimitiveID()) {
386 IMPLEMENT_SETCC(<, UByte);
387 IMPLEMENT_SETCC(<, SByte);
388 IMPLEMENT_SETCC(<, UShort);
389 IMPLEMENT_SETCC(<, Short);
390 IMPLEMENT_SETCC(<, UInt);
391 IMPLEMENT_SETCC(<, Int);
392 IMPLEMENT_SETCC(<, ULong);
393 IMPLEMENT_SETCC(<, Long);
394 IMPLEMENT_SETCC(<, Float);
395 IMPLEMENT_SETCC(<, Double);
396 IMPLEMENT_POINTERSETCC(<);
398 std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
404 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
407 switch (Ty->getPrimitiveID()) {
408 IMPLEMENT_SETCC(>, UByte);
409 IMPLEMENT_SETCC(>, SByte);
410 IMPLEMENT_SETCC(>, UShort);
411 IMPLEMENT_SETCC(>, Short);
412 IMPLEMENT_SETCC(>, UInt);
413 IMPLEMENT_SETCC(>, Int);
414 IMPLEMENT_SETCC(>, ULong);
415 IMPLEMENT_SETCC(>, Long);
416 IMPLEMENT_SETCC(>, Float);
417 IMPLEMENT_SETCC(>, Double);
418 IMPLEMENT_POINTERSETCC(>);
420 std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
426 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
427 ExecutionContext &SF = ECStack.back();
428 const Type *Ty = I.getOperand(0)->getType();
429 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
430 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
431 GenericValue R; // Result
433 switch (I.getOpcode()) {
434 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty); break;
435 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty); break;
436 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty); break;
437 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty); break;
438 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty); break;
439 case Instruction::And: R = executeAndInst (Src1, Src2, Ty); break;
440 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty); break;
441 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty); break;
442 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
443 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
444 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
445 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
446 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
447 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
449 std::cout << "Don't know how to handle this binary operator!\n-->" << I;
456 //===----------------------------------------------------------------------===//
457 // Terminator Instruction Implementations
458 //===----------------------------------------------------------------------===//
460 void Interpreter::exitCalled(GenericValue GV) {
462 std::cout << "Program returned ";
463 print(Type::IntTy, GV);
464 std::cout << " via 'void exit(int)'\n";
467 ExitCode = GV.SByteVal;
471 void Interpreter::visitReturnInst(ReturnInst &I) {
472 ExecutionContext &SF = ECStack.back();
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 Function *M = ECStack.back().CurFunction;
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?
491 CW << "Function " << M->getType() << " \"" << M->getName()
493 print(RetTy, Result);
497 if (RetTy->isIntegral())
498 ExitCode = Result.IntVal; // Capture the exit code of the program
505 // If we have a previous stack frame, and we have a previous call, fill in
506 // the return value...
508 ExecutionContext &NewSF = ECStack.back();
510 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
511 SetValue(NewSF.Caller, Result, NewSF);
513 NewSF.Caller = 0; // We returned from the call...
514 } else if (!QuietMode) {
515 // This must be a function that is executing because of a user 'call'
517 CW << "Function " << M->getType() << " \"" << M->getName()
519 print(RetTy, Result);
524 void Interpreter::visitBranchInst(BranchInst &I) {
525 ExecutionContext &SF = ECStack.back();
528 Dest = I.getSuccessor(0); // Uncond branches have a fixed dest...
529 if (!I.isUnconditional()) {
530 Value *Cond = I.getCondition();
531 if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
532 Dest = I.getSuccessor(1);
534 SwitchToNewBasicBlock(Dest, SF);
537 void Interpreter::visitSwitchInst(SwitchInst &I) {
538 ExecutionContext &SF = ECStack.back();
539 GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
540 const Type *ElTy = I.getOperand(0)->getType();
542 // Check to see if any of the cases match...
543 BasicBlock *Dest = 0;
544 for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
545 if (executeSetEQInst(CondVal,
546 getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
547 Dest = cast<BasicBlock>(I.getOperand(i+1));
551 if (!Dest) Dest = I.getDefaultDest(); // No cases matched: use default
552 SwitchToNewBasicBlock(Dest, SF);
555 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
556 // This function handles the actual updating of block and instruction iterators
557 // as well as execution of all of the PHI nodes in the destination block.
559 // This method does this because all of the PHI nodes must be executed
560 // atomically, reading their inputs before any of the results are updated. Not
561 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
562 // their inputs. If the input PHI node is updated before it is read, incorrect
563 // results can happen. Thus we use a two phase approach.
565 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
566 BasicBlock *PrevBB = SF.CurBB; // Remember where we came from...
567 SF.CurBB = Dest; // Update CurBB to branch destination
568 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
570 if (!isa<PHINode>(SF.CurInst)) return; // Nothing fancy to do
572 // Loop over all of the PHI nodes in the current block, reading their inputs.
573 std::vector<GenericValue> ResultValues;
575 for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
576 if (Trace) CW << "Run:" << PN;
578 // Search for the value corresponding to this previous bb...
579 int i = PN->getBasicBlockIndex(PrevBB);
580 assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
581 Value *IncomingValue = PN->getIncomingValue(i);
583 // Save the incoming value for this PHI node...
584 ResultValues.push_back(getOperandValue(IncomingValue, SF));
587 // Now loop over all of the PHI nodes setting their values...
588 SF.CurInst = SF.CurBB->begin();
589 for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
591 SetValue(PN, ResultValues[i], SF);
595 //===----------------------------------------------------------------------===//
596 // Memory Instruction Implementations
597 //===----------------------------------------------------------------------===//
599 void Interpreter::visitAllocationInst(AllocationInst &I) {
600 ExecutionContext &SF = ECStack.back();
602 const Type *Ty = I.getType()->getElementType(); // Type to be allocated
604 // Get the number of elements being allocated by the array...
605 unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
607 // Allocate enough memory to hold the type...
608 // FIXME: Don't use CALLOC, use a tainted malloc.
609 void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
611 GenericValue Result = PTOGV(Memory);
612 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
613 SetValue(&I, Result, SF);
615 if (I.getOpcode() == Instruction::Alloca)
616 ECStack.back().Allocas.add(Memory);
619 void Interpreter::visitFreeInst(FreeInst &I) {
620 ExecutionContext &SF = ECStack.back();
621 assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
622 GenericValue Value = getOperandValue(I.getOperand(0), SF);
623 // TODO: Check to make sure memory is allocated
624 free(GVTOP(Value)); // Free memory
628 // getElementOffset - The workhorse for getelementptr.
630 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
632 ExecutionContext &SF) {
633 assert(isa<PointerType>(Ptr->getType()) &&
634 "Cannot getElementOffset of a nonpointer type!");
637 const Type *Ty = Ptr->getType();
639 for (; I != E; ++I) {
640 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
641 const StructLayout *SLO = TD.getStructLayout(STy);
643 // Indicies must be ubyte constants...
644 const ConstantUInt *CPU = cast<ConstantUInt>(*I);
645 assert(CPU->getType() == Type::UByteTy);
646 unsigned Index = CPU->getValue();
648 Total += SLO->MemberOffsets[Index];
649 Ty = STy->getElementTypes()[Index];
650 } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
652 // Get the index number for the array... which must be long type...
653 assert((*I)->getType() == Type::LongTy);
654 unsigned Idx = getOperandValue(*I, SF).LongVal;
655 if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
656 if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
657 std::cerr << "Out of range memory access to element #" << Idx
658 << " of a " << AT->getNumElements() << " element array."
659 << " Subscript #" << *I << "\n";
663 Ty = ST->getElementType();
664 unsigned Size = TD.getTypeSize(Ty);
670 Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
674 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
675 ExecutionContext &SF = ECStack.back();
676 SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
677 I.idx_begin(), I.idx_end(), SF), SF);
680 void Interpreter::visitLoadInst(LoadInst &I) {
681 ExecutionContext &SF = ECStack.back();
682 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
683 GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
684 GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
685 SetValue(&I, Result, SF);
688 void Interpreter::visitStoreInst(StoreInst &I) {
689 ExecutionContext &SF = ECStack.back();
690 GenericValue Val = getOperandValue(I.getOperand(0), SF);
691 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
692 StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
693 I.getOperand(0)->getType());
698 //===----------------------------------------------------------------------===//
699 // Miscellaneous Instruction Implementations
700 //===----------------------------------------------------------------------===//
702 void Interpreter::visitCallInst(CallInst &I) {
703 ExecutionContext &SF = ECStack.back();
705 std::vector<GenericValue> ArgVals;
706 ArgVals.reserve(I.getNumOperands()-1);
707 for (unsigned i = 1; i < I.getNumOperands(); ++i) {
708 ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
709 // Promote all integral types whose size is < sizeof(int) into ints. We do
710 // this by zero or sign extending the value as appropriate according to the
712 if (I.getOperand(i)->getType()->isIntegral() &&
713 I.getOperand(i)->getType()->getPrimitiveSize() < 4) {
714 const Type *Ty = I.getOperand(i)->getType();
715 if (Ty == Type::ShortTy)
716 ArgVals.back().IntVal = ArgVals.back().ShortVal;
717 else if (Ty == Type::UShortTy)
718 ArgVals.back().UIntVal = ArgVals.back().UShortVal;
719 else if (Ty == Type::SByteTy)
720 ArgVals.back().IntVal = ArgVals.back().SByteVal;
721 else if (Ty == Type::UByteTy)
722 ArgVals.back().UIntVal = ArgVals.back().UByteVal;
723 else if (Ty == Type::BoolTy)
724 ArgVals.back().UIntVal = ArgVals.back().BoolVal;
726 assert(0 && "Unknown type!");
730 // To handle indirect calls, we must get the pointer value from the argument
731 // and treat it as a function pointer.
732 GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
733 callFunction((Function*)GVTOP(SRC), ArgVals);
736 #define IMPLEMENT_SHIFT(OP, TY) \
737 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
739 void Interpreter::visitShl(ShiftInst &I) {
740 ExecutionContext &SF = ECStack.back();
741 const Type *Ty = I.getOperand(0)->getType();
742 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
743 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
746 switch (Ty->getPrimitiveID()) {
747 IMPLEMENT_SHIFT(<<, UByte);
748 IMPLEMENT_SHIFT(<<, SByte);
749 IMPLEMENT_SHIFT(<<, UShort);
750 IMPLEMENT_SHIFT(<<, Short);
751 IMPLEMENT_SHIFT(<<, UInt);
752 IMPLEMENT_SHIFT(<<, Int);
753 IMPLEMENT_SHIFT(<<, ULong);
754 IMPLEMENT_SHIFT(<<, Long);
756 std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
758 SetValue(&I, Dest, SF);
761 void Interpreter::visitShr(ShiftInst &I) {
762 ExecutionContext &SF = ECStack.back();
763 const Type *Ty = I.getOperand(0)->getType();
764 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
765 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
768 switch (Ty->getPrimitiveID()) {
769 IMPLEMENT_SHIFT(>>, UByte);
770 IMPLEMENT_SHIFT(>>, SByte);
771 IMPLEMENT_SHIFT(>>, UShort);
772 IMPLEMENT_SHIFT(>>, Short);
773 IMPLEMENT_SHIFT(>>, UInt);
774 IMPLEMENT_SHIFT(>>, Int);
775 IMPLEMENT_SHIFT(>>, ULong);
776 IMPLEMENT_SHIFT(>>, Long);
778 std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
781 SetValue(&I, Dest, SF);
784 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
785 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
787 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
788 case Type::DESTTY##TyID: \
789 switch (SrcTy->getPrimitiveID()) { \
790 IMPLEMENT_CAST(DESTTY, DESTCTY, Bool); \
791 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
792 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
793 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
794 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
795 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
796 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
797 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
798 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
799 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
801 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
802 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
803 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
805 #define IMPLEMENT_CAST_CASE_END() \
806 default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
811 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
812 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
813 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
814 IMPLEMENT_CAST_CASE_END()
816 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
817 ExecutionContext &SF) {
818 const Type *SrcTy = SrcVal->getType();
819 GenericValue Dest, Src = getOperandValue(SrcVal, SF);
821 switch (Ty->getPrimitiveID()) {
822 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
823 IMPLEMENT_CAST_CASE(SByte , ( signed char));
824 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
825 IMPLEMENT_CAST_CASE(Short , ( signed short));
826 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
827 IMPLEMENT_CAST_CASE(Int , ( signed int ));
828 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
829 IMPLEMENT_CAST_CASE(Long , ( int64_t));
830 IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
831 IMPLEMENT_CAST_CASE(Float , (float));
832 IMPLEMENT_CAST_CASE(Double , (double));
833 IMPLEMENT_CAST_CASE(Bool , (bool));
835 std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
843 void Interpreter::visitCastInst(CastInst &I) {
844 ExecutionContext &SF = ECStack.back();
845 SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
848 void Interpreter::visitVarArgInst(VarArgInst &I) {
849 ExecutionContext &SF = ECStack.back();
851 // Get the pointer to the valist element. LLI treats the valist in memory as
853 GenericValue VAListPtr = getOperandValue(I.getOperand(0), SF);
856 GenericValue VAList =
857 TheEE->LoadValueFromMemory((GenericValue *)GVTOP(VAListPtr), Type::UIntTy);
859 unsigned Argument = VAList.IntVal++;
861 // Update the valist to point to the next argument...
862 TheEE->StoreValueToMemory(VAList, (GenericValue *)GVTOP(VAListPtr),
866 assert(Argument < SF.VarArgs.size() &&
867 "Accessing past the last vararg argument!");
868 SetValue(&I, SF.VarArgs[Argument], SF);
871 //===----------------------------------------------------------------------===//
872 // Dispatch and Execution Code
873 //===----------------------------------------------------------------------===//
875 FunctionInfo::FunctionInfo(Function *F) {
876 // Assign slot numbers to the function arguments...
877 for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
878 AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
880 // Iterate over all of the instructions...
881 unsigned InstNum = 0;
882 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
883 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
884 // For each instruction... Add Annote
885 II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
888 unsigned FunctionInfo::getValueSlot(const Value *V) {
889 unsigned Plane = V->getType()->getUniqueID();
890 if (Plane >= NumPlaneElements.size())
891 NumPlaneElements.resize(Plane+1, 0);
892 return NumPlaneElements[Plane]++;
896 //===----------------------------------------------------------------------===//
897 // callFunction - Execute the specified function...
899 void Interpreter::callFunction(Function *F,
900 const std::vector<GenericValue> &ArgVals) {
901 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
902 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
903 "Incorrect number of arguments passed into function call!");
904 if (F->isExternal()) {
905 GenericValue Result = callExternalFunction(F, ArgVals);
906 const Type *RetTy = F->getReturnType();
908 // Copy the result back into the result variable if we are not returning
910 if (RetTy != Type::VoidTy) {
911 if (!ECStack.empty() && ECStack.back().Caller) {
912 ExecutionContext &SF = ECStack.back();
913 SetValue(SF.Caller, Result, SF);
915 SF.Caller = 0; // We returned from the call...
916 } else if (!QuietMode) {
918 CW << "Function " << F->getType() << " \"" << F->getName()
920 print(RetTy, Result);
923 if (RetTy->isIntegral())
924 ExitCode = Result.IntVal; // Capture the exit code of the program
931 // Process the function, assigning instruction numbers to the instructions in
932 // the function. Also calculate the number of values for each type slot
935 FunctionInfo *&FuncInfo = FunctionInfoMap[F];
936 if (!FuncInfo) FuncInfo = new FunctionInfo(F);
938 // Make a new stack frame... and fill it in.
939 ECStack.push_back(ExecutionContext());
940 ExecutionContext &StackFrame = ECStack.back();
941 StackFrame.CurFunction = F;
942 StackFrame.CurBB = F->begin();
943 StackFrame.CurInst = StackFrame.CurBB->begin();
944 StackFrame.FuncInfo = FuncInfo;
946 // Initialize the values to nothing...
947 StackFrame.Values.resize(FuncInfo->NumPlaneElements.size());
948 for (unsigned i = 0; i < FuncInfo->NumPlaneElements.size(); ++i) {
949 StackFrame.Values[i].resize(FuncInfo->NumPlaneElements[i]);
951 // Taint the initial values of stuff
952 memset(&StackFrame.Values[i][0], 42,
953 FuncInfo->NumPlaneElements[i]*sizeof(GenericValue));
957 // Run through the function arguments and initialize their values...
958 assert((ArgVals.size() == F->asize() ||
959 (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
960 "Invalid number of values passed to function invocation!");
962 // Handle non-varargs arguments...
964 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
965 SetValue(AI, ArgVals[i], StackFrame);
967 // Handle varargs arguments...
968 StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
971 // executeInstruction - Interpret a single instruction & increment the "PC".
973 void Interpreter::executeInstruction() {
974 assert(!ECStack.empty() && "No program running, cannot execute inst!");
976 ExecutionContext &SF = ECStack.back(); // Current stack frame
977 Instruction &I = *SF.CurInst++; // Increment before execute
979 if (Trace) CW << "Run:" << I;
981 // Track the number of dynamic instructions executed.
984 visit(I); // Dispatch to one of the visit* methods...
986 // Reset the current frame location to the top of stack
987 CurFrame = ECStack.size()-1;
990 void Interpreter::run() {
991 while (!ECStack.empty()) {
992 // Run an instruction...
993 executeInstruction();
997 void Interpreter::printValue(const Type *Ty, GenericValue V) {
998 switch (Ty->getPrimitiveID()) {
999 case Type::BoolTyID: std::cout << (V.BoolVal?"true":"false"); break;
1000 case Type::SByteTyID:
1001 std::cout << (int)V.SByteVal << " '" << V.SByteVal << "'"; break;
1002 case Type::UByteTyID:
1003 std::cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'"; break;
1004 case Type::ShortTyID: std::cout << V.ShortVal; break;
1005 case Type::UShortTyID: std::cout << V.UShortVal; break;
1006 case Type::IntTyID: std::cout << V.IntVal; break;
1007 case Type::UIntTyID: std::cout << V.UIntVal; break;
1008 case Type::LongTyID: std::cout << (long)V.LongVal; break;
1009 case Type::ULongTyID: std::cout << (unsigned long)V.ULongVal; break;
1010 case Type::FloatTyID: std::cout << V.FloatVal; break;
1011 case Type::DoubleTyID: std::cout << V.DoubleVal; break;
1012 case Type::PointerTyID:std::cout << (void*)GVTOP(V); break;
1014 std::cout << "- Don't know how to print value of this type!";
1019 void Interpreter::print(const Type *Ty, GenericValue V) {