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/iPHINode.h"
10 #include "llvm/iOther.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/Target/TargetData.h"
17 #include "Support/CommandLine.h"
18 #include "Support/Statistic.h"
19 #include <math.h> // For fmod
27 Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
30 QuietMode("quiet", cl::desc("Do not emit any non-program output"));
33 QuietModeA("q", cl::desc("Alias for -quiet"), cl::aliasopt(QuietMode));
36 ArrayChecksEnabled("array-checks", cl::desc("Enable array bound checks"));
39 AbortOnExceptions("abort-on-exception",
40 cl::desc("Halt execution on a machine exception"));
43 // Create a TargetData structure to handle memory addressing and size/alignment
46 TargetData TD("lli Interpreter");
47 CachedWriter CW; // Object to accelerate printing of LLVM
50 #ifdef PROFILE_STRUCTURE_FIELDS
52 ProfileStructureFields("profilestructfields",
53 cl::desc("Profile Structure Field Accesses"));
55 static std::map<const StructType *, vector<unsigned> > FieldAccessCounts;
58 sigjmp_buf SignalRecoverBuffer;
59 static bool InInstruction = false;
62 static void SigHandler(int Signal) {
64 siglongjmp(SignalRecoverBuffer, Signal);
68 static void initializeSignalHandlers() {
69 struct sigaction Action;
70 Action.sa_handler = SigHandler;
71 Action.sa_flags = SA_SIGINFO;
72 sigemptyset(&Action.sa_mask);
73 sigaction(SIGSEGV, &Action, 0);
74 sigaction(SIGBUS, &Action, 0);
75 sigaction(SIGINT, &Action, 0);
76 sigaction(SIGFPE, &Action, 0);
80 //===----------------------------------------------------------------------===//
81 // Value Manipulation code
82 //===----------------------------------------------------------------------===//
84 static unsigned getOperandSlot(Value *V) {
85 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
86 assert(SN && "Operand does not have a slot number annotation!");
90 #define GET_CONST_VAL(TY, CLASS) \
91 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
93 // Operations used by constant expr implementations...
94 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
95 ExecutionContext &SF);
96 static GenericValue executeGEPOperation(Value *Src, User::op_iterator IdxBegin,
97 User::op_iterator IdxEnd,
98 ExecutionContext &SF);
99 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
100 const Type *Ty, ExecutionContext &SF);
102 static GenericValue getConstantValue(const Constant *C) {
104 switch (C->getType()->getPrimitiveID()) {
105 GET_CONST_VAL(Bool , ConstantBool);
106 GET_CONST_VAL(UByte , ConstantUInt);
107 GET_CONST_VAL(SByte , ConstantSInt);
108 GET_CONST_VAL(UShort , ConstantUInt);
109 GET_CONST_VAL(Short , ConstantSInt);
110 GET_CONST_VAL(UInt , ConstantUInt);
111 GET_CONST_VAL(Int , ConstantSInt);
112 GET_CONST_VAL(ULong , ConstantUInt);
113 GET_CONST_VAL(Long , ConstantSInt);
114 GET_CONST_VAL(Float , ConstantFP);
115 GET_CONST_VAL(Double , ConstantFP);
116 case Type::PointerTyID:
117 if (isa<ConstantPointerNull>(C)) {
118 Result.PointerVal = 0;
119 } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
120 GlobalAddress *Address =
121 (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
122 Result.PointerVal = (PointerTy)Address->Ptr;
124 assert(0 && "Unknown constant pointer type!");
128 cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
133 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
134 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
135 switch (CE->getOpcode()) {
136 case Instruction::Cast:
137 return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
138 case Instruction::GetElementPtr:
139 return executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
141 case Instruction::Add:
142 return executeAddInst(getOperandValue(CE->getOperand(0), SF),
143 getOperandValue(CE->getOperand(1), SF),
146 cerr << "Unhandled ConstantExpr: " << CE << "\n";
148 { GenericValue V; return V; }
150 } else if (Constant *CPV = dyn_cast<Constant>(V)) {
151 return getConstantValue(CPV);
152 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
153 GlobalAddress *Address =
154 (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
156 Result.PointerVal = (PointerTy)(GenericValue*)Address->Ptr;
159 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
160 unsigned OpSlot = getOperandSlot(V);
161 assert(TyP < SF.Values.size() &&
162 OpSlot < SF.Values[TyP].size() && "Value out of range!");
163 return SF.Values[TyP][getOperandSlot(V)];
167 static void printOperandInfo(Value *V, ExecutionContext &SF) {
168 if (isa<Constant>(V)) {
169 cout << "Constant Pool Value\n";
170 } else if (isa<GlobalValue>(V)) {
171 cout << "Global Value\n";
173 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
174 unsigned Slot = getOperandSlot(V);
175 cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
176 << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF
179 const unsigned char *Buf = (const unsigned char*)&SF.Values[TyP][Slot];
180 for (unsigned i = 0; i < sizeof(GenericValue); ++i) {
181 unsigned char Cur = Buf[i];
182 cout << ( Cur >= 160? char((Cur>>4)+'A'-10) : char((Cur>>4) + '0'))
183 << ((Cur&15) >= 10? char((Cur&15)+'A'-10) : char((Cur&15) + '0'));
191 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
192 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
194 //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << "\n";
195 SF.Values[TyP][getOperandSlot(V)] = Val;
199 //===----------------------------------------------------------------------===//
200 // Annotation Wrangling code
201 //===----------------------------------------------------------------------===//
203 void Interpreter::initializeExecutionEngine() {
204 AnnotationManager::registerAnnotationFactory(MethodInfoAID,
205 &MethodInfo::Create);
206 AnnotationManager::registerAnnotationFactory(GlobalAddressAID,
207 &GlobalAddress::Create);
208 initializeSignalHandlers();
211 static void StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
214 // InitializeMemory - Recursive function to apply a Constant value into the
215 // specified memory location...
217 static void InitializeMemory(const Constant *Init, char *Addr) {
219 if (Init->getType()->isFirstClassType()) {
220 GenericValue Val = getConstantValue(Init);
221 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
225 switch (Init->getType()->getPrimitiveID()) {
226 case Type::ArrayTyID: {
227 const ConstantArray *CPA = cast<ConstantArray>(Init);
228 const vector<Use> &Val = CPA->getValues();
229 unsigned ElementSize =
230 TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
231 for (unsigned i = 0; i < Val.size(); ++i)
232 InitializeMemory(cast<Constant>(Val[i].get()), Addr+i*ElementSize);
236 case Type::StructTyID: {
237 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
238 const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
239 const vector<Use> &Val = CPS->getValues();
240 for (unsigned i = 0; i < Val.size(); ++i)
241 InitializeMemory(cast<Constant>(Val[i].get()),
242 Addr+SL->MemberOffsets[i]);
247 CW << "Bad Type: " << Init->getType() << "\n";
248 assert(0 && "Unknown constant type to initialize memory with!");
252 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
253 assert(AID == GlobalAddressAID);
255 // This annotation will only be created on GlobalValue objects...
256 GlobalValue *GVal = cast<GlobalValue>((Value*)O);
258 if (isa<Function>(GVal)) {
259 // The GlobalAddress object for a function is just a pointer to function
260 // itself. Don't delete it when the annotation is gone though!
261 return new GlobalAddress(GVal, false);
264 // Handle the case of a global variable...
265 assert(isa<GlobalVariable>(GVal) &&
266 "Global value found that isn't a function or global variable!");
267 GlobalVariable *GV = cast<GlobalVariable>(GVal);
269 // First off, we must allocate space for the global variable to point at...
270 const Type *Ty = GV->getType()->getElementType(); // Type to be allocated
272 // Allocate enough memory to hold the type...
273 void *Addr = calloc(1, TD.getTypeSize(Ty));
274 assert(Addr != 0 && "Null pointer returned by malloc!");
276 // Initialize the memory if there is an initializer...
277 if (GV->hasInitializer())
278 InitializeMemory(GV->getInitializer(), (char*)Addr);
280 return new GlobalAddress(Addr, true); // Simply invoke the ctor
283 //===----------------------------------------------------------------------===//
284 // Binary Instruction Implementations
285 //===----------------------------------------------------------------------===//
287 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
288 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
290 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
291 const Type *Ty, ExecutionContext &SF) {
293 switch (Ty->getPrimitiveID()) {
294 IMPLEMENT_BINARY_OPERATOR(+, UByte);
295 IMPLEMENT_BINARY_OPERATOR(+, SByte);
296 IMPLEMENT_BINARY_OPERATOR(+, UShort);
297 IMPLEMENT_BINARY_OPERATOR(+, Short);
298 IMPLEMENT_BINARY_OPERATOR(+, UInt);
299 IMPLEMENT_BINARY_OPERATOR(+, Int);
300 IMPLEMENT_BINARY_OPERATOR(+, ULong);
301 IMPLEMENT_BINARY_OPERATOR(+, Long);
302 IMPLEMENT_BINARY_OPERATOR(+, Float);
303 IMPLEMENT_BINARY_OPERATOR(+, Double);
304 IMPLEMENT_BINARY_OPERATOR(+, Pointer);
306 cout << "Unhandled type for Add instruction: " << Ty << "\n";
311 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
312 const Type *Ty, ExecutionContext &SF) {
314 switch (Ty->getPrimitiveID()) {
315 IMPLEMENT_BINARY_OPERATOR(-, UByte);
316 IMPLEMENT_BINARY_OPERATOR(-, SByte);
317 IMPLEMENT_BINARY_OPERATOR(-, UShort);
318 IMPLEMENT_BINARY_OPERATOR(-, Short);
319 IMPLEMENT_BINARY_OPERATOR(-, UInt);
320 IMPLEMENT_BINARY_OPERATOR(-, Int);
321 IMPLEMENT_BINARY_OPERATOR(-, ULong);
322 IMPLEMENT_BINARY_OPERATOR(-, Long);
323 IMPLEMENT_BINARY_OPERATOR(-, Float);
324 IMPLEMENT_BINARY_OPERATOR(-, Double);
325 IMPLEMENT_BINARY_OPERATOR(-, Pointer);
327 cout << "Unhandled type for Sub instruction: " << Ty << "\n";
332 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
333 const Type *Ty, ExecutionContext &SF) {
335 switch (Ty->getPrimitiveID()) {
336 IMPLEMENT_BINARY_OPERATOR(*, UByte);
337 IMPLEMENT_BINARY_OPERATOR(*, SByte);
338 IMPLEMENT_BINARY_OPERATOR(*, UShort);
339 IMPLEMENT_BINARY_OPERATOR(*, Short);
340 IMPLEMENT_BINARY_OPERATOR(*, UInt);
341 IMPLEMENT_BINARY_OPERATOR(*, Int);
342 IMPLEMENT_BINARY_OPERATOR(*, ULong);
343 IMPLEMENT_BINARY_OPERATOR(*, Long);
344 IMPLEMENT_BINARY_OPERATOR(*, Float);
345 IMPLEMENT_BINARY_OPERATOR(*, Double);
346 IMPLEMENT_BINARY_OPERATOR(*, Pointer);
348 cout << "Unhandled type for Mul instruction: " << Ty << "\n";
353 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
354 const Type *Ty, ExecutionContext &SF) {
356 switch (Ty->getPrimitiveID()) {
357 IMPLEMENT_BINARY_OPERATOR(/, UByte);
358 IMPLEMENT_BINARY_OPERATOR(/, SByte);
359 IMPLEMENT_BINARY_OPERATOR(/, UShort);
360 IMPLEMENT_BINARY_OPERATOR(/, Short);
361 IMPLEMENT_BINARY_OPERATOR(/, UInt);
362 IMPLEMENT_BINARY_OPERATOR(/, Int);
363 IMPLEMENT_BINARY_OPERATOR(/, ULong);
364 IMPLEMENT_BINARY_OPERATOR(/, Long);
365 IMPLEMENT_BINARY_OPERATOR(/, Float);
366 IMPLEMENT_BINARY_OPERATOR(/, Double);
367 IMPLEMENT_BINARY_OPERATOR(/, Pointer);
369 cout << "Unhandled type for Div instruction: " << Ty << "\n";
374 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
375 const Type *Ty, ExecutionContext &SF) {
377 switch (Ty->getPrimitiveID()) {
378 IMPLEMENT_BINARY_OPERATOR(%, UByte);
379 IMPLEMENT_BINARY_OPERATOR(%, SByte);
380 IMPLEMENT_BINARY_OPERATOR(%, UShort);
381 IMPLEMENT_BINARY_OPERATOR(%, Short);
382 IMPLEMENT_BINARY_OPERATOR(%, UInt);
383 IMPLEMENT_BINARY_OPERATOR(%, Int);
384 IMPLEMENT_BINARY_OPERATOR(%, ULong);
385 IMPLEMENT_BINARY_OPERATOR(%, Long);
386 IMPLEMENT_BINARY_OPERATOR(%, Pointer);
387 case Type::FloatTyID:
388 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
390 case Type::DoubleTyID:
391 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
394 cout << "Unhandled type for Rem instruction: " << Ty << "\n";
399 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
400 const Type *Ty, ExecutionContext &SF) {
402 switch (Ty->getPrimitiveID()) {
403 IMPLEMENT_BINARY_OPERATOR(&, UByte);
404 IMPLEMENT_BINARY_OPERATOR(&, SByte);
405 IMPLEMENT_BINARY_OPERATOR(&, UShort);
406 IMPLEMENT_BINARY_OPERATOR(&, Short);
407 IMPLEMENT_BINARY_OPERATOR(&, UInt);
408 IMPLEMENT_BINARY_OPERATOR(&, Int);
409 IMPLEMENT_BINARY_OPERATOR(&, ULong);
410 IMPLEMENT_BINARY_OPERATOR(&, Long);
411 IMPLEMENT_BINARY_OPERATOR(&, Pointer);
413 cout << "Unhandled type for And instruction: " << Ty << "\n";
419 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
420 const Type *Ty, ExecutionContext &SF) {
422 switch (Ty->getPrimitiveID()) {
423 IMPLEMENT_BINARY_OPERATOR(|, UByte);
424 IMPLEMENT_BINARY_OPERATOR(|, SByte);
425 IMPLEMENT_BINARY_OPERATOR(|, UShort);
426 IMPLEMENT_BINARY_OPERATOR(|, Short);
427 IMPLEMENT_BINARY_OPERATOR(|, UInt);
428 IMPLEMENT_BINARY_OPERATOR(|, Int);
429 IMPLEMENT_BINARY_OPERATOR(|, ULong);
430 IMPLEMENT_BINARY_OPERATOR(|, Long);
431 IMPLEMENT_BINARY_OPERATOR(|, Pointer);
433 cout << "Unhandled type for Or instruction: " << Ty << "\n";
439 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
440 const Type *Ty, ExecutionContext &SF) {
442 switch (Ty->getPrimitiveID()) {
443 IMPLEMENT_BINARY_OPERATOR(^, UByte);
444 IMPLEMENT_BINARY_OPERATOR(^, SByte);
445 IMPLEMENT_BINARY_OPERATOR(^, UShort);
446 IMPLEMENT_BINARY_OPERATOR(^, Short);
447 IMPLEMENT_BINARY_OPERATOR(^, UInt);
448 IMPLEMENT_BINARY_OPERATOR(^, Int);
449 IMPLEMENT_BINARY_OPERATOR(^, ULong);
450 IMPLEMENT_BINARY_OPERATOR(^, Long);
451 IMPLEMENT_BINARY_OPERATOR(^, Pointer);
453 cout << "Unhandled type for Xor instruction: " << Ty << "\n";
459 #define IMPLEMENT_SETCC(OP, TY) \
460 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
462 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
463 const Type *Ty, ExecutionContext &SF) {
465 switch (Ty->getPrimitiveID()) {
466 IMPLEMENT_SETCC(==, UByte);
467 IMPLEMENT_SETCC(==, SByte);
468 IMPLEMENT_SETCC(==, UShort);
469 IMPLEMENT_SETCC(==, Short);
470 IMPLEMENT_SETCC(==, UInt);
471 IMPLEMENT_SETCC(==, Int);
472 IMPLEMENT_SETCC(==, ULong);
473 IMPLEMENT_SETCC(==, Long);
474 IMPLEMENT_SETCC(==, Float);
475 IMPLEMENT_SETCC(==, Double);
476 IMPLEMENT_SETCC(==, Pointer);
478 cout << "Unhandled type for SetEQ instruction: " << Ty << "\n";
483 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
484 const Type *Ty, ExecutionContext &SF) {
486 switch (Ty->getPrimitiveID()) {
487 IMPLEMENT_SETCC(!=, UByte);
488 IMPLEMENT_SETCC(!=, SByte);
489 IMPLEMENT_SETCC(!=, UShort);
490 IMPLEMENT_SETCC(!=, Short);
491 IMPLEMENT_SETCC(!=, UInt);
492 IMPLEMENT_SETCC(!=, Int);
493 IMPLEMENT_SETCC(!=, ULong);
494 IMPLEMENT_SETCC(!=, Long);
495 IMPLEMENT_SETCC(!=, Float);
496 IMPLEMENT_SETCC(!=, Double);
497 IMPLEMENT_SETCC(!=, Pointer);
500 cout << "Unhandled type for SetNE instruction: " << Ty << "\n";
505 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
506 const Type *Ty, ExecutionContext &SF) {
508 switch (Ty->getPrimitiveID()) {
509 IMPLEMENT_SETCC(<=, UByte);
510 IMPLEMENT_SETCC(<=, SByte);
511 IMPLEMENT_SETCC(<=, UShort);
512 IMPLEMENT_SETCC(<=, Short);
513 IMPLEMENT_SETCC(<=, UInt);
514 IMPLEMENT_SETCC(<=, Int);
515 IMPLEMENT_SETCC(<=, ULong);
516 IMPLEMENT_SETCC(<=, Long);
517 IMPLEMENT_SETCC(<=, Float);
518 IMPLEMENT_SETCC(<=, Double);
519 IMPLEMENT_SETCC(<=, Pointer);
521 cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
526 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
527 const Type *Ty, ExecutionContext &SF) {
529 switch (Ty->getPrimitiveID()) {
530 IMPLEMENT_SETCC(>=, UByte);
531 IMPLEMENT_SETCC(>=, SByte);
532 IMPLEMENT_SETCC(>=, UShort);
533 IMPLEMENT_SETCC(>=, Short);
534 IMPLEMENT_SETCC(>=, UInt);
535 IMPLEMENT_SETCC(>=, Int);
536 IMPLEMENT_SETCC(>=, ULong);
537 IMPLEMENT_SETCC(>=, Long);
538 IMPLEMENT_SETCC(>=, Float);
539 IMPLEMENT_SETCC(>=, Double);
540 IMPLEMENT_SETCC(>=, Pointer);
542 cout << "Unhandled type for SetGE instruction: " << Ty << "\n";
547 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
548 const Type *Ty, ExecutionContext &SF) {
550 switch (Ty->getPrimitiveID()) {
551 IMPLEMENT_SETCC(<, UByte);
552 IMPLEMENT_SETCC(<, SByte);
553 IMPLEMENT_SETCC(<, UShort);
554 IMPLEMENT_SETCC(<, Short);
555 IMPLEMENT_SETCC(<, UInt);
556 IMPLEMENT_SETCC(<, Int);
557 IMPLEMENT_SETCC(<, ULong);
558 IMPLEMENT_SETCC(<, Long);
559 IMPLEMENT_SETCC(<, Float);
560 IMPLEMENT_SETCC(<, Double);
561 IMPLEMENT_SETCC(<, Pointer);
563 cout << "Unhandled type for SetLT instruction: " << Ty << "\n";
568 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
569 const Type *Ty, ExecutionContext &SF) {
571 switch (Ty->getPrimitiveID()) {
572 IMPLEMENT_SETCC(>, UByte);
573 IMPLEMENT_SETCC(>, SByte);
574 IMPLEMENT_SETCC(>, UShort);
575 IMPLEMENT_SETCC(>, Short);
576 IMPLEMENT_SETCC(>, UInt);
577 IMPLEMENT_SETCC(>, Int);
578 IMPLEMENT_SETCC(>, ULong);
579 IMPLEMENT_SETCC(>, Long);
580 IMPLEMENT_SETCC(>, Float);
581 IMPLEMENT_SETCC(>, Double);
582 IMPLEMENT_SETCC(>, Pointer);
584 cout << "Unhandled type for SetGT instruction: " << Ty << "\n";
589 static void executeBinaryInst(BinaryOperator &I, ExecutionContext &SF) {
590 const Type *Ty = I.getOperand(0)->getType();
591 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
592 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
593 GenericValue R; // Result
595 switch (I.getOpcode()) {
596 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty, SF); break;
597 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty, SF); break;
598 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty, SF); break;
599 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty, SF); break;
600 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty, SF); break;
601 case Instruction::And: R = executeAndInst (Src1, Src2, Ty, SF); break;
602 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty, SF); break;
603 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty, SF); break;
604 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
605 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
606 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
607 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
608 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
609 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
611 cout << "Don't know how to handle this binary operator!\n-->" << I;
618 //===----------------------------------------------------------------------===//
619 // Terminator Instruction Implementations
620 //===----------------------------------------------------------------------===//
622 static void PerformExitStuff() {
623 #ifdef PROFILE_STRUCTURE_FIELDS
624 // Print out structure field accounting information...
625 if (!FieldAccessCounts.empty()) {
626 CW << "Profile Field Access Counts:\n";
627 std::map<const StructType *, vector<unsigned> >::iterator
628 I = FieldAccessCounts.begin(), E = FieldAccessCounts.end();
629 for (; I != E; ++I) {
630 vector<unsigned> &OfC = I->second;
631 CW << " '" << (Value*)I->first << "'\t- Sum=";
634 for (unsigned i = 0; i < OfC.size(); ++i)
638 for (unsigned i = 0; i < OfC.size(); ++i) {
646 CW << "Profile Field Access Percentages:\n";
648 for (I = FieldAccessCounts.begin(); I != E; ++I) {
649 vector<unsigned> &OfC = I->second;
651 for (unsigned i = 0; i < OfC.size(); ++i)
654 CW << " '" << (Value*)I->first << "'\t- ";
655 for (unsigned i = 0; i < OfC.size(); ++i) {
657 CW << double(OfC[i])/Sum;
663 FieldAccessCounts.clear();
668 void Interpreter::exitCalled(GenericValue GV) {
670 cout << "Program returned ";
671 print(Type::IntTy, GV);
672 cout << " via 'void exit(int)'\n";
675 ExitCode = GV.SByteVal;
680 void Interpreter::executeRetInst(ReturnInst &I, ExecutionContext &SF) {
681 const Type *RetTy = 0;
684 // Save away the return value... (if we are not 'ret void')
685 if (I.getNumOperands()) {
686 RetTy = I.getReturnValue()->getType();
687 Result = getOperandValue(I.getReturnValue(), SF);
690 // Save previously executing meth
691 const Function *M = ECStack.back().CurMethod;
693 // Pop the current stack frame... this invalidates SF
696 if (ECStack.empty()) { // Finished main. Put result into exit code...
697 if (RetTy) { // Nonvoid return type?
699 CW << "Function " << M->getType() << " \"" << M->getName()
701 print(RetTy, Result);
705 if (RetTy->isIntegral())
706 ExitCode = Result.IntVal; // Capture the exit code of the program
715 // If we have a previous stack frame, and we have a previous call, fill in
716 // the return value...
718 ExecutionContext &NewSF = ECStack.back();
720 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
721 SetValue(NewSF.Caller, Result, NewSF);
723 NewSF.Caller = 0; // We returned from the call...
724 } else if (!QuietMode) {
725 // This must be a function that is executing because of a user 'call'
727 CW << "Function " << M->getType() << " \"" << M->getName()
729 print(RetTy, Result);
734 void Interpreter::executeBrInst(BranchInst &I, ExecutionContext &SF) {
735 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
738 Dest = I.getSuccessor(0); // Uncond branches have a fixed dest...
739 if (!I.isUnconditional()) {
740 Value *Cond = I.getCondition();
741 GenericValue CondVal = getOperandValue(Cond, SF);
742 if (CondVal.BoolVal == 0) // If false cond...
743 Dest = I.getSuccessor(1);
745 SF.CurBB = Dest; // Update CurBB to branch destination
746 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
749 //===----------------------------------------------------------------------===//
750 // Memory Instruction Implementations
751 //===----------------------------------------------------------------------===//
753 void Interpreter::executeAllocInst(AllocationInst &I, ExecutionContext &SF) {
754 const Type *Ty = I.getType()->getElementType(); // Type to be allocated
756 // Get the number of elements being allocated by the array...
757 unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
759 // Allocate enough memory to hold the type...
760 // FIXME: Don't use CALLOC, use a tainted malloc.
761 void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
764 Result.PointerVal = (PointerTy)Memory;
765 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
766 SetValue(&I, Result, SF);
768 if (I.getOpcode() == Instruction::Alloca)
769 ECStack.back().Allocas.add(Memory);
772 static void executeFreeInst(FreeInst &I, ExecutionContext &SF) {
773 assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
774 GenericValue Value = getOperandValue(I.getOperand(0), SF);
775 // TODO: Check to make sure memory is allocated
776 free((void*)Value.PointerVal); // Free memory
780 // getElementOffset - The workhorse for getelementptr.
782 static GenericValue executeGEPOperation(Value *Ptr, User::op_iterator I,
784 ExecutionContext &SF) {
785 assert(isa<PointerType>(Ptr->getType()) &&
786 "Cannot getElementOffset of a nonpointer type!");
789 const Type *Ty = Ptr->getType();
791 for (; I != E; ++I) {
792 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
793 const StructLayout *SLO = TD.getStructLayout(STy);
795 // Indicies must be ubyte constants...
796 const ConstantUInt *CPU = cast<ConstantUInt>(*I);
797 assert(CPU->getType() == Type::UByteTy);
798 unsigned Index = CPU->getValue();
800 #ifdef PROFILE_STRUCTURE_FIELDS
801 if (ProfileStructureFields) {
802 // Do accounting for this field...
803 vector<unsigned> &OfC = FieldAccessCounts[STy];
804 if (OfC.size() == 0) OfC.resize(STy->getElementTypes().size());
809 Total += SLO->MemberOffsets[Index];
810 Ty = STy->getElementTypes()[Index];
811 } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
813 // Get the index number for the array... which must be uint type...
814 assert((*I)->getType() == Type::LongTy);
815 unsigned Idx = getOperandValue(*I, SF).LongVal;
816 if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
817 if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
818 cerr << "Out of range memory access to element #" << Idx
819 << " of a " << AT->getNumElements() << " element array."
820 << " Subscript #" << *I << "\n";
822 siglongjmp(SignalRecoverBuffer, SIGTRAP);
825 Ty = ST->getElementType();
826 unsigned Size = TD.getTypeSize(Ty);
832 Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
836 static void executeGEPInst(GetElementPtrInst &I, ExecutionContext &SF) {
837 SetValue(&I, executeGEPOperation(I.getPointerOperand(),
838 I.idx_begin(), I.idx_end(), SF), SF);
841 static void executeLoadInst(LoadInst &I, ExecutionContext &SF) {
842 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
843 GenericValue *Ptr = (GenericValue*)SRC.PointerVal;
846 if (TD.isLittleEndian()) {
847 switch (I.getType()->getPrimitiveID()) {
849 case Type::UByteTyID:
850 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
851 case Type::UShortTyID:
852 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
853 ((unsigned)Ptr->Untyped[1] << 8);
855 case Type::FloatTyID:
857 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
858 ((unsigned)Ptr->Untyped[1] << 8) |
859 ((unsigned)Ptr->Untyped[2] << 16) |
860 ((unsigned)Ptr->Untyped[3] << 24);
862 case Type::DoubleTyID:
863 case Type::ULongTyID:
865 case Type::PointerTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
866 ((uint64_t)Ptr->Untyped[1] << 8) |
867 ((uint64_t)Ptr->Untyped[2] << 16) |
868 ((uint64_t)Ptr->Untyped[3] << 24) |
869 ((uint64_t)Ptr->Untyped[4] << 32) |
870 ((uint64_t)Ptr->Untyped[5] << 40) |
871 ((uint64_t)Ptr->Untyped[6] << 48) |
872 ((uint64_t)Ptr->Untyped[7] << 56);
875 cout << "Cannot load value of type " << I.getType() << "!\n";
878 switch (I.getType()->getPrimitiveID()) {
880 case Type::UByteTyID:
881 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
882 case Type::UShortTyID:
883 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
884 ((unsigned)Ptr->Untyped[0] << 8);
886 case Type::FloatTyID:
888 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
889 ((unsigned)Ptr->Untyped[2] << 8) |
890 ((unsigned)Ptr->Untyped[1] << 16) |
891 ((unsigned)Ptr->Untyped[0] << 24);
893 case Type::DoubleTyID:
894 case Type::ULongTyID:
896 case Type::PointerTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
897 ((uint64_t)Ptr->Untyped[6] << 8) |
898 ((uint64_t)Ptr->Untyped[5] << 16) |
899 ((uint64_t)Ptr->Untyped[4] << 24) |
900 ((uint64_t)Ptr->Untyped[3] << 32) |
901 ((uint64_t)Ptr->Untyped[2] << 40) |
902 ((uint64_t)Ptr->Untyped[1] << 48) |
903 ((uint64_t)Ptr->Untyped[0] << 56);
906 cout << "Cannot load value of type " << I.getType() << "!\n";
910 SetValue(&I, Result, SF);
913 static void StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
915 if (TD.isLittleEndian()) {
916 switch (Ty->getPrimitiveID()) {
918 case Type::UByteTyID:
919 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
920 case Type::UShortTyID:
921 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
922 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
924 case Type::FloatTyID:
926 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
927 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
928 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
929 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
931 case Type::DoubleTyID:
932 case Type::ULongTyID:
934 case Type::PointerTyID: Ptr->Untyped[0] = Val.ULongVal & 255;
935 Ptr->Untyped[1] = (Val.ULongVal >> 8) & 255;
936 Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
937 Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
938 Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
939 Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
940 Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
941 Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
944 cout << "Cannot store value of type " << Ty << "!\n";
947 switch (Ty->getPrimitiveID()) {
949 case Type::UByteTyID:
950 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
951 case Type::UShortTyID:
952 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
953 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
955 case Type::FloatTyID:
957 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
958 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
959 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
960 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
962 case Type::DoubleTyID:
963 case Type::ULongTyID:
965 case Type::PointerTyID: Ptr->Untyped[7] = Val.ULongVal & 255;
966 Ptr->Untyped[6] = (Val.ULongVal >> 8) & 255;
967 Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
968 Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
969 Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
970 Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
971 Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
972 Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
975 cout << "Cannot store value of type " << Ty << "!\n";
980 static void executeStoreInst(StoreInst &I, ExecutionContext &SF) {
981 GenericValue Val = getOperandValue(I.getOperand(0), SF);
982 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
983 StoreValueToMemory(Val, (GenericValue *)SRC.PointerVal,
984 I.getOperand(0)->getType());
988 GenericValue Interpreter::CreateArgv(const std::vector<std::string> &InputArgv){
989 // Pointers are 64 bits...
990 PointerTy *Result = new PointerTy[InputArgv.size()+1]; // 64 bit assumption
992 for (unsigned i = 0; i < InputArgv.size(); ++i) {
993 unsigned Size = InputArgv[i].size()+1;
994 char *Dest = new char[Size];
995 copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
998 GenericValue GV; GV.PointerVal = (PointerTy)Dest;
999 // Endian safe: Result[i] = (PointerTy)Dest;
1000 StoreValueToMemory(GV, (GenericValue*)(Result+i),
1001 Type::LongTy); // 64 bit assumption
1004 Result[InputArgv.size()] = 0;
1005 GenericValue GV; GV.PointerVal = (PointerTy)Result;
1010 //===----------------------------------------------------------------------===//
1011 // Miscellaneous Instruction Implementations
1012 //===----------------------------------------------------------------------===//
1014 void Interpreter::executeCallInst(CallInst &I, ExecutionContext &SF) {
1015 ECStack.back().Caller = &I;
1016 vector<GenericValue> ArgVals;
1017 ArgVals.reserve(I.getNumOperands()-1);
1018 for (unsigned i = 1; i < I.getNumOperands(); ++i)
1019 ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
1021 // To handle indirect calls, we must get the pointer value from the argument
1022 // and treat it as a function pointer.
1023 GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
1025 callMethod((Function*)SRC.PointerVal, ArgVals);
1028 static void executePHINode(PHINode &I, ExecutionContext &SF) {
1029 BasicBlock *PrevBB = SF.PrevBB;
1030 Value *IncomingValue = 0;
1032 // Search for the value corresponding to this previous bb...
1033 for (unsigned i = I.getNumIncomingValues(); i > 0;) {
1034 if (I.getIncomingBlock(--i) == PrevBB) {
1035 IncomingValue = I.getIncomingValue(i);
1039 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
1041 // Found the value, set as the result...
1042 SetValue(&I, getOperandValue(IncomingValue, SF), SF);
1045 #define IMPLEMENT_SHIFT(OP, TY) \
1046 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
1048 static void executeShlInst(ShiftInst &I, ExecutionContext &SF) {
1049 const Type *Ty = I.getOperand(0)->getType();
1050 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1051 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1054 switch (Ty->getPrimitiveID()) {
1055 IMPLEMENT_SHIFT(<<, UByte);
1056 IMPLEMENT_SHIFT(<<, SByte);
1057 IMPLEMENT_SHIFT(<<, UShort);
1058 IMPLEMENT_SHIFT(<<, Short);
1059 IMPLEMENT_SHIFT(<<, UInt);
1060 IMPLEMENT_SHIFT(<<, Int);
1061 IMPLEMENT_SHIFT(<<, ULong);
1062 IMPLEMENT_SHIFT(<<, Long);
1063 IMPLEMENT_SHIFT(<<, Pointer);
1065 cout << "Unhandled type for Shl instruction: " << Ty << "\n";
1067 SetValue(&I, Dest, SF);
1070 static void executeShrInst(ShiftInst &I, ExecutionContext &SF) {
1071 const Type *Ty = I.getOperand(0)->getType();
1072 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1073 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1076 switch (Ty->getPrimitiveID()) {
1077 IMPLEMENT_SHIFT(>>, UByte);
1078 IMPLEMENT_SHIFT(>>, SByte);
1079 IMPLEMENT_SHIFT(>>, UShort);
1080 IMPLEMENT_SHIFT(>>, Short);
1081 IMPLEMENT_SHIFT(>>, UInt);
1082 IMPLEMENT_SHIFT(>>, Int);
1083 IMPLEMENT_SHIFT(>>, ULong);
1084 IMPLEMENT_SHIFT(>>, Long);
1085 IMPLEMENT_SHIFT(>>, Pointer);
1087 cout << "Unhandled type for Shr instruction: " << Ty << "\n";
1089 SetValue(&I, Dest, SF);
1092 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
1093 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
1095 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
1096 case Type::DESTTY##TyID: \
1097 switch (SrcTy->getPrimitiveID()) { \
1098 IMPLEMENT_CAST(DESTTY, DESTCTY, Bool); \
1099 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
1100 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
1101 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
1102 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
1103 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
1104 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
1105 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
1106 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
1107 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
1109 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
1110 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
1111 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
1113 #define IMPLEMENT_CAST_CASE_END() \
1114 default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
1119 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
1120 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
1121 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
1122 IMPLEMENT_CAST_CASE_END()
1124 static GenericValue executeCastOperation(Value *SrcVal, const Type *Ty,
1125 ExecutionContext &SF) {
1126 const Type *SrcTy = SrcVal->getType();
1127 GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1129 switch (Ty->getPrimitiveID()) {
1130 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
1131 IMPLEMENT_CAST_CASE(SByte , ( signed char));
1132 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1133 IMPLEMENT_CAST_CASE(Short , ( signed short));
1134 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
1135 IMPLEMENT_CAST_CASE(Int , ( signed int ));
1136 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
1137 IMPLEMENT_CAST_CASE(Long , ( int64_t));
1138 IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
1139 IMPLEMENT_CAST_CASE(Float , (float));
1140 IMPLEMENT_CAST_CASE(Double , (double));
1142 cout << "Unhandled dest type for cast instruction: " << Ty << "\n";
1149 static void executeCastInst(CastInst &I, ExecutionContext &SF) {
1150 SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
1154 //===----------------------------------------------------------------------===//
1155 // Dispatch and Execution Code
1156 //===----------------------------------------------------------------------===//
1158 MethodInfo::MethodInfo(Function *F) : Annotation(MethodInfoAID) {
1159 // Assign slot numbers to the function arguments...
1160 for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1161 AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
1163 // Iterate over all of the instructions...
1164 unsigned InstNum = 0;
1165 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
1166 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
1167 // For each instruction... Add Annote
1168 II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
1171 unsigned MethodInfo::getValueSlot(const Value *V) {
1172 unsigned Plane = V->getType()->getUniqueID();
1173 if (Plane >= NumPlaneElements.size())
1174 NumPlaneElements.resize(Plane+1, 0);
1175 return NumPlaneElements[Plane]++;
1179 //===----------------------------------------------------------------------===//
1180 // callMethod - Execute the specified function...
1182 void Interpreter::callMethod(Function *M, const vector<GenericValue> &ArgVals) {
1183 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
1184 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
1185 "Incorrect number of arguments passed into function call!");
1186 if (M->isExternal()) {
1187 GenericValue Result = callExternalMethod(M, ArgVals);
1188 const Type *RetTy = M->getReturnType();
1190 // Copy the result back into the result variable if we are not returning
1192 if (RetTy != Type::VoidTy) {
1193 if (!ECStack.empty() && ECStack.back().Caller) {
1194 ExecutionContext &SF = ECStack.back();
1195 SetValue(SF.Caller, Result, SF);
1197 SF.Caller = 0; // We returned from the call...
1198 } else if (!QuietMode) {
1200 CW << "Function " << M->getType() << " \"" << M->getName()
1202 print(RetTy, Result);
1205 if (RetTy->isIntegral())
1206 ExitCode = Result.IntVal; // Capture the exit code of the program
1213 // Process the function, assigning instruction numbers to the instructions in
1214 // the function. Also calculate the number of values for each type slot
1217 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
1218 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
1220 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
1221 StackFrame.CurMethod = M;
1222 StackFrame.CurBB = M->begin();
1223 StackFrame.CurInst = StackFrame.CurBB->begin();
1224 StackFrame.MethInfo = MethInfo;
1226 // Initialize the values to nothing...
1227 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
1228 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i) {
1229 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
1231 // Taint the initial values of stuff
1232 memset(&StackFrame.Values[i][0], 42,
1233 MethInfo->NumPlaneElements[i]*sizeof(GenericValue));
1236 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
1239 // Run through the function arguments and initialize their values...
1240 assert(ArgVals.size() == M->asize() &&
1241 "Invalid number of values passed to function invocation!");
1243 for (Function::aiterator AI = M->abegin(), E = M->aend(); AI != E; ++AI, ++i)
1244 SetValue(AI, ArgVals[i], StackFrame);
1247 // executeInstruction - Interpret a single instruction, increment the "PC", and
1248 // return true if the next instruction is a breakpoint...
1250 bool Interpreter::executeInstruction() {
1251 assert(!ECStack.empty() && "No program running, cannot execute inst!");
1253 ExecutionContext &SF = ECStack.back(); // Current stack frame
1254 Instruction &I = *SF.CurInst++; // Increment before execute
1259 // Track the number of dynamic instructions executed.
1262 // Set a sigsetjmp buffer so that we can recover if an error happens during
1263 // instruction execution...
1265 if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1266 --SF.CurInst; // Back up to erroring instruction
1267 if (SigNo != SIGINT) {
1268 cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]:\n";
1270 // If -abort-on-exception was specified, terminate LLI instead of trying
1273 if (AbortOnExceptions) exit(1);
1274 } else if (SigNo == SIGINT) {
1275 cout << "CTRL-C Detected, execution halted.\n";
1277 InInstruction = false;
1281 InInstruction = true;
1282 if (I.isBinaryOp()) {
1283 executeBinaryInst(cast<BinaryOperator>(I), SF);
1285 switch (I.getOpcode()) {
1287 case Instruction::Ret: executeRetInst (cast<ReturnInst>(I), SF); break;
1288 case Instruction::Br: executeBrInst (cast<BranchInst>(I), SF); break;
1289 // Memory Instructions
1290 case Instruction::Alloca:
1291 case Instruction::Malloc: executeAllocInst((AllocationInst&)I, SF); break;
1292 case Instruction::Free: executeFreeInst (cast<FreeInst> (I), SF); break;
1293 case Instruction::Load: executeLoadInst (cast<LoadInst> (I), SF); break;
1294 case Instruction::Store: executeStoreInst(cast<StoreInst>(I), SF); break;
1295 case Instruction::GetElementPtr:
1296 executeGEPInst(cast<GetElementPtrInst>(I), SF); break;
1298 // Miscellaneous Instructions
1299 case Instruction::Call: executeCallInst (cast<CallInst> (I), SF); break;
1300 case Instruction::PHINode: executePHINode (cast<PHINode> (I), SF); break;
1301 case Instruction::Shl: executeShlInst (cast<ShiftInst>(I), SF); break;
1302 case Instruction::Shr: executeShrInst (cast<ShiftInst>(I), SF); break;
1303 case Instruction::Cast: executeCastInst (cast<CastInst> (I), SF); break;
1305 cout << "Don't know how to execute this instruction!\n-->" << I;
1308 InInstruction = false;
1310 // Reset the current frame location to the top of stack
1311 CurFrame = ECStack.size()-1;
1313 if (CurFrame == -1) return false; // No breakpoint if no code
1315 // Return true if there is a breakpoint annotation on the instruction...
1316 return ECStack[CurFrame].CurInst->getAnnotation(BreakpointAID) != 0;
1319 void Interpreter::stepInstruction() { // Do the 'step' command
1320 if (ECStack.empty()) {
1321 cout << "Error: no program running, cannot step!\n";
1325 // Run an instruction...
1326 executeInstruction();
1328 // Print the next instruction to execute...
1329 printCurrentInstruction();
1333 void Interpreter::nextInstruction() { // Do the 'next' command
1334 if (ECStack.empty()) {
1335 cout << "Error: no program running, cannot 'next'!\n";
1339 // If this is a call instruction, step over the call instruction...
1340 // TODO: ICALL, CALL WITH, ...
1341 if (ECStack.back().CurInst->getOpcode() == Instruction::Call) {
1342 unsigned StackSize = ECStack.size();
1343 // Step into the function...
1344 if (executeInstruction()) {
1345 // Hit a breakpoint, print current instruction, then return to user...
1346 cout << "Breakpoint hit!\n";
1347 printCurrentInstruction();
1351 // If we we able to step into the function, finish it now. We might not be
1352 // able the step into a function, if it's external for example.
1353 if (ECStack.size() != StackSize)
1354 finish(); // Finish executing the function...
1356 printCurrentInstruction();
1359 // Normal instruction, just step...
1364 void Interpreter::run() {
1365 if (ECStack.empty()) {
1366 cout << "Error: no program running, cannot run!\n";
1370 bool HitBreakpoint = false;
1371 while (!ECStack.empty() && !HitBreakpoint) {
1372 // Run an instruction...
1373 HitBreakpoint = executeInstruction();
1376 if (HitBreakpoint) {
1377 cout << "Breakpoint hit!\n";
1379 // Print the next instruction to execute...
1380 printCurrentInstruction();
1383 void Interpreter::finish() {
1384 if (ECStack.empty()) {
1385 cout << "Error: no program running, cannot run!\n";
1389 unsigned StackSize = ECStack.size();
1390 bool HitBreakpoint = false;
1391 while (ECStack.size() >= StackSize && !HitBreakpoint) {
1392 // Run an instruction...
1393 HitBreakpoint = executeInstruction();
1396 if (HitBreakpoint) {
1397 cout << "Breakpoint hit!\n";
1400 // Print the next instruction to execute...
1401 printCurrentInstruction();
1406 // printCurrentInstruction - Print out the instruction that the virtual PC is
1407 // at, or fail silently if no program is running.
1409 void Interpreter::printCurrentInstruction() {
1410 if (!ECStack.empty()) {
1411 if (ECStack.back().CurBB->begin() == ECStack.back().CurInst) // print label
1412 WriteAsOperand(cout, ECStack.back().CurBB) << ":\n";
1414 Instruction &I = *ECStack.back().CurInst;
1415 InstNumber *IN = (InstNumber*)I.getAnnotation(SlotNumberAID);
1416 assert(IN && "Instruction has no numbering annotation!");
1417 cout << "#" << IN->InstNum << I;
1421 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1422 switch (Ty->getPrimitiveID()) {
1423 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
1424 case Type::SByteTyID:
1425 cout << (int)V.SByteVal << " '" << V.SByteVal << "'"; break;
1426 case Type::UByteTyID:
1427 cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'"; break;
1428 case Type::ShortTyID: cout << V.ShortVal; break;
1429 case Type::UShortTyID: cout << V.UShortVal; break;
1430 case Type::IntTyID: cout << V.IntVal; break;
1431 case Type::UIntTyID: cout << V.UIntVal; break;
1432 case Type::LongTyID: cout << (long)V.LongVal; break;
1433 case Type::ULongTyID: cout << (unsigned long)V.ULongVal; break;
1434 case Type::FloatTyID: cout << V.FloatVal; break;
1435 case Type::DoubleTyID: cout << V.DoubleVal; break;
1436 case Type::PointerTyID:cout << (void*)V.PointerVal; break;
1438 cout << "- Don't know how to print value of this type!";
1443 void Interpreter::print(const Type *Ty, GenericValue V) {
1448 void Interpreter::print(const std::string &Name) {
1449 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1450 if (!PickedVal) return;
1452 if (const Function *F = dyn_cast<const Function>(PickedVal)) {
1453 CW << F; // Print the function
1454 } else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
1455 CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
1456 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
1457 CW << BB; // Print the basic block
1458 } else { // Otherwise there should be an annotation for the slot#
1459 print(PickedVal->getType(),
1460 getOperandValue(PickedVal, ECStack[CurFrame]));
1465 void Interpreter::infoValue(const std::string &Name) {
1466 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1467 if (!PickedVal) return;
1470 print(PickedVal->getType(),
1471 getOperandValue(PickedVal, ECStack[CurFrame]));
1473 printOperandInfo(PickedVal, ECStack[CurFrame]);
1476 // printStackFrame - Print information about the specified stack frame, or -1
1477 // for the default one.
1479 void Interpreter::printStackFrame(int FrameNo) {
1480 if (FrameNo == -1) FrameNo = CurFrame;
1481 Function *F = ECStack[FrameNo].CurMethod;
1482 const Type *RetTy = F->getReturnType();
1484 CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1485 << (Value*)RetTy << " \"" << F->getName() << "\"(";
1488 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++i) {
1489 if (i != 0) cout << ", ";
1492 printValue(I->getType(), getOperandValue(I, ECStack[FrameNo]));
1497 if (FrameNo != int(ECStack.size()-1)) {
1498 BasicBlock::iterator I = ECStack[FrameNo].CurInst;
1501 CW << *ECStack[FrameNo].CurInst;