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 "llvm/GlobalVariable.h"
18 #include "Support/CommandLine.h"
19 #include <math.h> // For fmod
27 cl::Flag QuietMode ("quiet" , "Do not emit any non-program output");
28 cl::Alias QuietModeA("q" , "Alias for -quiet", cl::NoFlags, QuietMode);
29 cl::Flag ArrayChecksEnabled("array-checks", "Enable array bound checks");
30 cl::Flag AbortOnExceptions("abort-on-exception", "Halt execution on a machine exception");
32 // Create a TargetData structure to handle memory addressing and size/alignment
35 static TargetData TD("lli Interpreter");
36 CachedWriter CW; // Object to accelerate printing of LLVM
39 #ifdef PROFILE_STRUCTURE_FIELDS
40 static cl::Flag ProfileStructureFields("profilestructfields",
41 "Profile Structure Field Accesses");
43 static std::map<const StructType *, vector<unsigned> > FieldAccessCounts;
46 sigjmp_buf SignalRecoverBuffer;
47 static bool InInstruction = false;
50 static void SigHandler(int Signal) {
52 siglongjmp(SignalRecoverBuffer, Signal);
56 static void initializeSignalHandlers() {
57 struct sigaction Action;
58 Action.sa_handler = SigHandler;
59 Action.sa_flags = SA_SIGINFO;
60 sigemptyset(&Action.sa_mask);
61 sigaction(SIGSEGV, &Action, 0);
62 sigaction(SIGBUS, &Action, 0);
63 sigaction(SIGINT, &Action, 0);
64 sigaction(SIGFPE, &Action, 0);
68 //===----------------------------------------------------------------------===//
69 // Value Manipulation code
70 //===----------------------------------------------------------------------===//
72 static unsigned getOperandSlot(Value *V) {
73 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
74 assert(SN && "Operand does not have a slot number annotation!");
78 #define GET_CONST_VAL(TY, CLASS) \
79 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(CPV)->getValue(); break
81 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
82 if (Constant *CPV = dyn_cast<Constant>(V)) {
84 switch (CPV->getType()->getPrimitiveID()) {
85 GET_CONST_VAL(Bool , ConstantBool);
86 GET_CONST_VAL(UByte , ConstantUInt);
87 GET_CONST_VAL(SByte , ConstantSInt);
88 GET_CONST_VAL(UShort , ConstantUInt);
89 GET_CONST_VAL(Short , ConstantSInt);
90 GET_CONST_VAL(UInt , ConstantUInt);
91 GET_CONST_VAL(Int , ConstantSInt);
92 GET_CONST_VAL(ULong , ConstantUInt);
93 GET_CONST_VAL(Long , ConstantSInt);
94 GET_CONST_VAL(Float , ConstantFP);
95 GET_CONST_VAL(Double , ConstantFP);
96 case Type::PointerTyID:
97 if (isa<ConstantPointerNull>(CPV)) {
98 Result.PointerVal = 0;
99 } else if (isa<ConstantPointerRef>(CPV)) {
100 assert(0 && "Not implemented!");
102 assert(0 && "Unknown constant pointer type!");
106 cout << "ERROR: Constant unimp for type: " << CPV->getType() << "\n";
109 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
110 GlobalAddress *Address =
111 (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
113 Result.PointerVal = (PointerTy)(GenericValue*)Address->Ptr;
116 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
117 unsigned OpSlot = getOperandSlot(V);
118 assert(TyP < SF.Values.size() &&
119 OpSlot < SF.Values[TyP].size() && "Value out of range!");
120 return SF.Values[TyP][getOperandSlot(V)];
124 static void printOperandInfo(Value *V, ExecutionContext &SF) {
125 if (isa<Constant>(V)) {
126 cout << "Constant Pool Value\n";
127 } else if (isa<GlobalValue>(V)) {
128 cout << "Global Value\n";
130 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
131 unsigned Slot = getOperandSlot(V);
132 cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
133 << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF
136 const unsigned char *Buf = (const unsigned char*)&SF.Values[TyP][Slot];
137 for (unsigned i = 0; i < sizeof(GenericValue); ++i) {
138 unsigned char Cur = Buf[i];
139 cout << ( Cur >= 160? char((Cur>>4)+'A'-10) : char((Cur>>4) + '0'))
140 << ((Cur&15) >= 10? char((Cur&15)+'A'-10) : char((Cur&15) + '0'));
148 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
149 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
151 //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << "\n";
152 SF.Values[TyP][getOperandSlot(V)] = Val;
156 //===----------------------------------------------------------------------===//
157 // Annotation Wrangling code
158 //===----------------------------------------------------------------------===//
160 void Interpreter::initializeExecutionEngine() {
161 AnnotationManager::registerAnnotationFactory(MethodInfoAID,
162 &MethodInfo::Create);
163 AnnotationManager::registerAnnotationFactory(GlobalAddressAID,
164 &GlobalAddress::Create);
165 initializeSignalHandlers();
168 // InitializeMemory - Recursive function to apply a Constant value into the
169 // specified memory location...
171 static void InitializeMemory(Constant *Init, char *Addr) {
172 #define INITIALIZE_MEMORY(TYID, CLASS, TY) \
173 case Type::TYID##TyID: { \
174 TY Tmp = cast<CLASS>(Init)->getValue(); \
175 memcpy(Addr, &Tmp, sizeof(TY)); \
178 switch (Init->getType()->getPrimitiveID()) {
179 INITIALIZE_MEMORY(Bool , ConstantBool, bool);
180 INITIALIZE_MEMORY(UByte , ConstantUInt, unsigned char);
181 INITIALIZE_MEMORY(SByte , ConstantSInt, signed char);
182 INITIALIZE_MEMORY(UShort , ConstantUInt, unsigned short);
183 INITIALIZE_MEMORY(Short , ConstantSInt, signed short);
184 INITIALIZE_MEMORY(UInt , ConstantUInt, unsigned int);
185 INITIALIZE_MEMORY(Int , ConstantSInt, signed int);
186 INITIALIZE_MEMORY(ULong , ConstantUInt, uint64_t);
187 INITIALIZE_MEMORY(Long , ConstantSInt, int64_t);
188 INITIALIZE_MEMORY(Float , ConstantFP , float);
189 INITIALIZE_MEMORY(Double , ConstantFP , double);
190 #undef INITIALIZE_MEMORY
192 case Type::ArrayTyID: {
193 ConstantArray *CPA = cast<ConstantArray>(Init);
194 const vector<Use> &Val = CPA->getValues();
195 unsigned ElementSize =
196 TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
197 for (unsigned i = 0; i < Val.size(); ++i)
198 InitializeMemory(cast<Constant>(Val[i].get()), Addr+i*ElementSize);
202 case Type::StructTyID: {
203 ConstantStruct *CPS = cast<ConstantStruct>(Init);
204 const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
205 const vector<Use> &Val = CPS->getValues();
206 for (unsigned i = 0; i < Val.size(); ++i)
207 InitializeMemory(cast<Constant>(Val[i].get()),
208 Addr+SL->MemberOffsets[i]);
212 case Type::PointerTyID:
213 if (isa<ConstantPointerNull>(Init)) {
215 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Init)) {
216 GlobalAddress *Address =
217 (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
218 *(void**)Addr = (GenericValue*)Address->Ptr;
220 assert(0 && "Unknown Constant pointer type!");
225 CW << "Bad Type: " << Init->getType() << "\n";
226 assert(0 && "Unknown constant type to initialize memory with!");
230 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
231 assert(AID == GlobalAddressAID);
233 // This annotation will only be created on GlobalValue objects...
234 GlobalValue *GVal = cast<GlobalValue>((Value*)O);
236 if (isa<Function>(GVal)) {
237 // The GlobalAddress object for a function is just a pointer to function
238 // itself. Don't delete it when the annotation is gone though!
239 return new GlobalAddress(GVal, false);
242 // Handle the case of a global variable...
243 assert(isa<GlobalVariable>(GVal) &&
244 "Global value found that isn't a function or global variable!");
245 GlobalVariable *GV = cast<GlobalVariable>(GVal);
247 // First off, we must allocate space for the global variable to point at...
248 const Type *Ty = GV->getType()->getElementType(); // Type to be allocated
250 // Allocate enough memory to hold the type...
251 void *Addr = calloc(1, TD.getTypeSize(Ty));
252 assert(Addr != 0 && "Null pointer returned by malloc!");
254 // Initialize the memory if there is an initializer...
255 if (GV->hasInitializer())
256 InitializeMemory(GV->getInitializer(), (char*)Addr);
258 return new GlobalAddress(Addr, true); // Simply invoke the ctor
262 //===----------------------------------------------------------------------===//
263 // Unary Instruction Implementations
264 //===----------------------------------------------------------------------===//
266 #define IMPLEMENT_UNARY_OPERATOR(OP, TY) \
267 case Type::TY##TyID: Dest.TY##Val = OP Src.TY##Val; break
269 static void executeNotInst(UnaryOperator *I, ExecutionContext &SF) {
270 const Type *Ty = I->getOperand(0)->getType();
271 GenericValue Src = getOperandValue(I->getOperand(0), SF);
273 switch (Ty->getPrimitiveID()) {
274 IMPLEMENT_UNARY_OPERATOR(~, UByte);
275 IMPLEMENT_UNARY_OPERATOR(~, SByte);
276 IMPLEMENT_UNARY_OPERATOR(~, UShort);
277 IMPLEMENT_UNARY_OPERATOR(~, Short);
278 IMPLEMENT_UNARY_OPERATOR(~, UInt);
279 IMPLEMENT_UNARY_OPERATOR(~, Int);
280 IMPLEMENT_UNARY_OPERATOR(~, ULong);
281 IMPLEMENT_UNARY_OPERATOR(~, Long);
282 IMPLEMENT_UNARY_OPERATOR(~, Pointer);
284 cout << "Unhandled type for Not instruction: " << Ty << "\n";
286 SetValue(I, Dest, SF);
289 //===----------------------------------------------------------------------===//
290 // Binary Instruction Implementations
291 //===----------------------------------------------------------------------===//
293 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
294 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
296 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
297 const Type *Ty, ExecutionContext &SF) {
299 switch (Ty->getPrimitiveID()) {
300 IMPLEMENT_BINARY_OPERATOR(+, UByte);
301 IMPLEMENT_BINARY_OPERATOR(+, SByte);
302 IMPLEMENT_BINARY_OPERATOR(+, UShort);
303 IMPLEMENT_BINARY_OPERATOR(+, Short);
304 IMPLEMENT_BINARY_OPERATOR(+, UInt);
305 IMPLEMENT_BINARY_OPERATOR(+, Int);
306 IMPLEMENT_BINARY_OPERATOR(+, ULong);
307 IMPLEMENT_BINARY_OPERATOR(+, Long);
308 IMPLEMENT_BINARY_OPERATOR(+, Float);
309 IMPLEMENT_BINARY_OPERATOR(+, Double);
310 IMPLEMENT_BINARY_OPERATOR(+, Pointer);
312 cout << "Unhandled type for Add instruction: " << Ty << "\n";
317 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
318 const Type *Ty, ExecutionContext &SF) {
320 switch (Ty->getPrimitiveID()) {
321 IMPLEMENT_BINARY_OPERATOR(-, UByte);
322 IMPLEMENT_BINARY_OPERATOR(-, SByte);
323 IMPLEMENT_BINARY_OPERATOR(-, UShort);
324 IMPLEMENT_BINARY_OPERATOR(-, Short);
325 IMPLEMENT_BINARY_OPERATOR(-, UInt);
326 IMPLEMENT_BINARY_OPERATOR(-, Int);
327 IMPLEMENT_BINARY_OPERATOR(-, ULong);
328 IMPLEMENT_BINARY_OPERATOR(-, Long);
329 IMPLEMENT_BINARY_OPERATOR(-, Float);
330 IMPLEMENT_BINARY_OPERATOR(-, Double);
331 IMPLEMENT_BINARY_OPERATOR(-, Pointer);
333 cout << "Unhandled type for Sub instruction: " << Ty << "\n";
338 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
339 const Type *Ty, ExecutionContext &SF) {
341 switch (Ty->getPrimitiveID()) {
342 IMPLEMENT_BINARY_OPERATOR(*, UByte);
343 IMPLEMENT_BINARY_OPERATOR(*, SByte);
344 IMPLEMENT_BINARY_OPERATOR(*, UShort);
345 IMPLEMENT_BINARY_OPERATOR(*, Short);
346 IMPLEMENT_BINARY_OPERATOR(*, UInt);
347 IMPLEMENT_BINARY_OPERATOR(*, Int);
348 IMPLEMENT_BINARY_OPERATOR(*, ULong);
349 IMPLEMENT_BINARY_OPERATOR(*, Long);
350 IMPLEMENT_BINARY_OPERATOR(*, Float);
351 IMPLEMENT_BINARY_OPERATOR(*, Double);
352 IMPLEMENT_BINARY_OPERATOR(*, Pointer);
354 cout << "Unhandled type for Mul instruction: " << Ty << "\n";
359 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
360 const Type *Ty, ExecutionContext &SF) {
362 switch (Ty->getPrimitiveID()) {
363 IMPLEMENT_BINARY_OPERATOR(/, UByte);
364 IMPLEMENT_BINARY_OPERATOR(/, SByte);
365 IMPLEMENT_BINARY_OPERATOR(/, UShort);
366 IMPLEMENT_BINARY_OPERATOR(/, Short);
367 IMPLEMENT_BINARY_OPERATOR(/, UInt);
368 IMPLEMENT_BINARY_OPERATOR(/, Int);
369 IMPLEMENT_BINARY_OPERATOR(/, ULong);
370 IMPLEMENT_BINARY_OPERATOR(/, Long);
371 IMPLEMENT_BINARY_OPERATOR(/, Float);
372 IMPLEMENT_BINARY_OPERATOR(/, Double);
373 IMPLEMENT_BINARY_OPERATOR(/, Pointer);
375 cout << "Unhandled type for Div instruction: " << Ty << "\n";
380 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
381 const Type *Ty, ExecutionContext &SF) {
383 switch (Ty->getPrimitiveID()) {
384 IMPLEMENT_BINARY_OPERATOR(%, UByte);
385 IMPLEMENT_BINARY_OPERATOR(%, SByte);
386 IMPLEMENT_BINARY_OPERATOR(%, UShort);
387 IMPLEMENT_BINARY_OPERATOR(%, Short);
388 IMPLEMENT_BINARY_OPERATOR(%, UInt);
389 IMPLEMENT_BINARY_OPERATOR(%, Int);
390 IMPLEMENT_BINARY_OPERATOR(%, ULong);
391 IMPLEMENT_BINARY_OPERATOR(%, Long);
392 IMPLEMENT_BINARY_OPERATOR(%, Pointer);
393 case Type::FloatTyID:
394 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
396 case Type::DoubleTyID:
397 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
400 cout << "Unhandled type for Rem instruction: " << Ty << "\n";
405 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
406 const Type *Ty, ExecutionContext &SF) {
408 switch (Ty->getPrimitiveID()) {
409 IMPLEMENT_BINARY_OPERATOR(&, UByte);
410 IMPLEMENT_BINARY_OPERATOR(&, SByte);
411 IMPLEMENT_BINARY_OPERATOR(&, UShort);
412 IMPLEMENT_BINARY_OPERATOR(&, Short);
413 IMPLEMENT_BINARY_OPERATOR(&, UInt);
414 IMPLEMENT_BINARY_OPERATOR(&, Int);
415 IMPLEMENT_BINARY_OPERATOR(&, ULong);
416 IMPLEMENT_BINARY_OPERATOR(&, Long);
417 IMPLEMENT_BINARY_OPERATOR(&, Pointer);
419 cout << "Unhandled type for And instruction: " << Ty << "\n";
425 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
426 const Type *Ty, ExecutionContext &SF) {
428 switch (Ty->getPrimitiveID()) {
429 IMPLEMENT_BINARY_OPERATOR(|, UByte);
430 IMPLEMENT_BINARY_OPERATOR(|, SByte);
431 IMPLEMENT_BINARY_OPERATOR(|, UShort);
432 IMPLEMENT_BINARY_OPERATOR(|, Short);
433 IMPLEMENT_BINARY_OPERATOR(|, UInt);
434 IMPLEMENT_BINARY_OPERATOR(|, Int);
435 IMPLEMENT_BINARY_OPERATOR(|, ULong);
436 IMPLEMENT_BINARY_OPERATOR(|, Long);
437 IMPLEMENT_BINARY_OPERATOR(|, Pointer);
439 cout << "Unhandled type for Or instruction: " << Ty << "\n";
445 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
446 const Type *Ty, ExecutionContext &SF) {
448 switch (Ty->getPrimitiveID()) {
449 IMPLEMENT_BINARY_OPERATOR(^, UByte);
450 IMPLEMENT_BINARY_OPERATOR(^, SByte);
451 IMPLEMENT_BINARY_OPERATOR(^, UShort);
452 IMPLEMENT_BINARY_OPERATOR(^, Short);
453 IMPLEMENT_BINARY_OPERATOR(^, UInt);
454 IMPLEMENT_BINARY_OPERATOR(^, Int);
455 IMPLEMENT_BINARY_OPERATOR(^, ULong);
456 IMPLEMENT_BINARY_OPERATOR(^, Long);
457 IMPLEMENT_BINARY_OPERATOR(^, Pointer);
459 cout << "Unhandled type for Xor instruction: " << Ty << "\n";
465 #define IMPLEMENT_SETCC(OP, TY) \
466 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
468 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
469 const Type *Ty, ExecutionContext &SF) {
471 switch (Ty->getPrimitiveID()) {
472 IMPLEMENT_SETCC(==, UByte);
473 IMPLEMENT_SETCC(==, SByte);
474 IMPLEMENT_SETCC(==, UShort);
475 IMPLEMENT_SETCC(==, Short);
476 IMPLEMENT_SETCC(==, UInt);
477 IMPLEMENT_SETCC(==, Int);
478 IMPLEMENT_SETCC(==, ULong);
479 IMPLEMENT_SETCC(==, Long);
480 IMPLEMENT_SETCC(==, Float);
481 IMPLEMENT_SETCC(==, Double);
482 IMPLEMENT_SETCC(==, Pointer);
484 cout << "Unhandled type for SetEQ instruction: " << Ty << "\n";
489 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
490 const Type *Ty, ExecutionContext &SF) {
492 switch (Ty->getPrimitiveID()) {
493 IMPLEMENT_SETCC(!=, UByte);
494 IMPLEMENT_SETCC(!=, SByte);
495 IMPLEMENT_SETCC(!=, UShort);
496 IMPLEMENT_SETCC(!=, Short);
497 IMPLEMENT_SETCC(!=, UInt);
498 IMPLEMENT_SETCC(!=, Int);
499 IMPLEMENT_SETCC(!=, ULong);
500 IMPLEMENT_SETCC(!=, Long);
501 IMPLEMENT_SETCC(!=, Float);
502 IMPLEMENT_SETCC(!=, Double);
503 IMPLEMENT_SETCC(!=, Pointer);
506 cout << "Unhandled type for SetNE instruction: " << Ty << "\n";
511 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
512 const Type *Ty, ExecutionContext &SF) {
514 switch (Ty->getPrimitiveID()) {
515 IMPLEMENT_SETCC(<=, UByte);
516 IMPLEMENT_SETCC(<=, SByte);
517 IMPLEMENT_SETCC(<=, UShort);
518 IMPLEMENT_SETCC(<=, Short);
519 IMPLEMENT_SETCC(<=, UInt);
520 IMPLEMENT_SETCC(<=, Int);
521 IMPLEMENT_SETCC(<=, ULong);
522 IMPLEMENT_SETCC(<=, Long);
523 IMPLEMENT_SETCC(<=, Float);
524 IMPLEMENT_SETCC(<=, Double);
525 IMPLEMENT_SETCC(<=, Pointer);
527 cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
532 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
533 const Type *Ty, ExecutionContext &SF) {
535 switch (Ty->getPrimitiveID()) {
536 IMPLEMENT_SETCC(>=, UByte);
537 IMPLEMENT_SETCC(>=, SByte);
538 IMPLEMENT_SETCC(>=, UShort);
539 IMPLEMENT_SETCC(>=, Short);
540 IMPLEMENT_SETCC(>=, UInt);
541 IMPLEMENT_SETCC(>=, Int);
542 IMPLEMENT_SETCC(>=, ULong);
543 IMPLEMENT_SETCC(>=, Long);
544 IMPLEMENT_SETCC(>=, Float);
545 IMPLEMENT_SETCC(>=, Double);
546 IMPLEMENT_SETCC(>=, Pointer);
548 cout << "Unhandled type for SetGE instruction: " << Ty << "\n";
553 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
554 const Type *Ty, ExecutionContext &SF) {
556 switch (Ty->getPrimitiveID()) {
557 IMPLEMENT_SETCC(<, UByte);
558 IMPLEMENT_SETCC(<, SByte);
559 IMPLEMENT_SETCC(<, UShort);
560 IMPLEMENT_SETCC(<, Short);
561 IMPLEMENT_SETCC(<, UInt);
562 IMPLEMENT_SETCC(<, Int);
563 IMPLEMENT_SETCC(<, ULong);
564 IMPLEMENT_SETCC(<, Long);
565 IMPLEMENT_SETCC(<, Float);
566 IMPLEMENT_SETCC(<, Double);
567 IMPLEMENT_SETCC(<, Pointer);
569 cout << "Unhandled type for SetLT instruction: " << Ty << "\n";
574 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
575 const Type *Ty, ExecutionContext &SF) {
577 switch (Ty->getPrimitiveID()) {
578 IMPLEMENT_SETCC(>, UByte);
579 IMPLEMENT_SETCC(>, SByte);
580 IMPLEMENT_SETCC(>, UShort);
581 IMPLEMENT_SETCC(>, Short);
582 IMPLEMENT_SETCC(>, UInt);
583 IMPLEMENT_SETCC(>, Int);
584 IMPLEMENT_SETCC(>, ULong);
585 IMPLEMENT_SETCC(>, Long);
586 IMPLEMENT_SETCC(>, Float);
587 IMPLEMENT_SETCC(>, Double);
588 IMPLEMENT_SETCC(>, Pointer);
590 cout << "Unhandled type for SetGT instruction: " << Ty << "\n";
595 static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
596 const Type *Ty = I->getOperand(0)->getType();
597 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
598 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
599 GenericValue R; // Result
601 switch (I->getOpcode()) {
602 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty, SF); break;
603 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty, SF); break;
604 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty, SF); break;
605 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty, SF); break;
606 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty, SF); break;
607 case Instruction::And: R = executeAndInst (Src1, Src2, Ty, SF); break;
608 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty, SF); break;
609 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty, SF); break;
610 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
611 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
612 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
613 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
614 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
615 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
617 cout << "Don't know how to handle this binary operator!\n-->" << I;
624 //===----------------------------------------------------------------------===//
625 // Terminator Instruction Implementations
626 //===----------------------------------------------------------------------===//
628 static void PerformExitStuff() {
629 #ifdef PROFILE_STRUCTURE_FIELDS
630 // Print out structure field accounting information...
631 if (!FieldAccessCounts.empty()) {
632 CW << "Profile Field Access Counts:\n";
633 std::map<const StructType *, vector<unsigned> >::iterator
634 I = FieldAccessCounts.begin(), E = FieldAccessCounts.end();
635 for (; I != E; ++I) {
636 vector<unsigned> &OfC = I->second;
637 CW << " '" << (Value*)I->first << "'\t- Sum=";
640 for (unsigned i = 0; i < OfC.size(); ++i)
644 for (unsigned i = 0; i < OfC.size(); ++i) {
652 CW << "Profile Field Access Percentages:\n";
654 for (I = FieldAccessCounts.begin(); I != E; ++I) {
655 vector<unsigned> &OfC = I->second;
657 for (unsigned i = 0; i < OfC.size(); ++i)
660 CW << " '" << (Value*)I->first << "'\t- ";
661 for (unsigned i = 0; i < OfC.size(); ++i) {
663 CW << double(OfC[i])/Sum;
669 FieldAccessCounts.clear();
674 void Interpreter::exitCalled(GenericValue GV) {
676 cout << "Program returned ";
677 print(Type::IntTy, GV);
678 cout << " via 'void exit(int)'\n";
681 ExitCode = GV.SByteVal;
686 void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
687 const Type *RetTy = 0;
690 // Save away the return value... (if we are not 'ret void')
691 if (I->getNumOperands()) {
692 RetTy = I->getReturnValue()->getType();
693 Result = getOperandValue(I->getReturnValue(), SF);
696 // Save previously executing meth
697 const Function *M = ECStack.back().CurMethod;
699 // Pop the current stack frame... this invalidates SF
702 if (ECStack.empty()) { // Finished main. Put result into exit code...
703 if (RetTy) { // Nonvoid return type?
705 CW << "Function " << M->getType() << " \"" << M->getName()
707 print(RetTy, Result);
711 if (RetTy->isIntegral())
712 ExitCode = Result.IntVal; // Capture the exit code of the program
721 // If we have a previous stack frame, and we have a previous call, fill in
722 // the return value...
724 ExecutionContext &NewSF = ECStack.back();
726 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
727 SetValue(NewSF.Caller, Result, NewSF);
729 NewSF.Caller = 0; // We returned from the call...
730 } else if (!QuietMode) {
731 // This must be a function that is executing because of a user 'call'
733 CW << "Function " << M->getType() << " \"" << M->getName()
735 print(RetTy, Result);
740 void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
741 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
744 Dest = I->getSuccessor(0); // Uncond branches have a fixed dest...
745 if (!I->isUnconditional()) {
746 Value *Cond = I->getCondition();
747 GenericValue CondVal = getOperandValue(Cond, SF);
748 if (CondVal.BoolVal == 0) // If false cond...
749 Dest = I->getSuccessor(1);
751 SF.CurBB = Dest; // Update CurBB to branch destination
752 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
755 //===----------------------------------------------------------------------===//
756 // Memory Instruction Implementations
757 //===----------------------------------------------------------------------===//
759 void Interpreter::executeAllocInst(AllocationInst *I, ExecutionContext &SF) {
760 const Type *Ty = I->getType()->getElementType(); // Type to be allocated
762 // Get the number of elements being allocated by the array...
763 unsigned NumElements = getOperandValue(I->getOperand(0), SF).UIntVal;
765 // Allocate enough memory to hold the type...
766 // FIXME: Don't use CALLOC, use a tainted malloc.
767 void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
770 Result.PointerVal = (PointerTy)Memory;
771 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
772 SetValue(I, Result, SF);
774 if (I->getOpcode() == Instruction::Alloca)
775 ECStack.back().Allocas.add(Memory);
778 static void executeFreeInst(FreeInst *I, ExecutionContext &SF) {
779 assert(I->getOperand(0)->getType()->isPointerType() && "Freeing nonptr?");
780 GenericValue Value = getOperandValue(I->getOperand(0), SF);
781 // TODO: Check to make sure memory is allocated
782 free((void*)Value.PointerVal); // Free memory
786 // getElementOffset - The workhorse for getelementptr, load and store. This
787 // function returns the offset that arguments ArgOff+1 -> NumArgs specify for
788 // the pointer type specified by argument Arg.
790 static PointerTy getElementOffset(MemAccessInst *I, ExecutionContext &SF) {
791 assert(isa<PointerType>(I->getPointerOperand()->getType()) &&
792 "Cannot getElementOffset of a nonpointer type!");
795 const Type *Ty = I->getPointerOperand()->getType();
797 unsigned ArgOff = I->getFirstIndexOperandNumber();
798 while (ArgOff < I->getNumOperands()) {
799 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
800 const StructLayout *SLO = TD.getStructLayout(STy);
802 // Indicies must be ubyte constants...
803 const ConstantUInt *CPU = cast<ConstantUInt>(I->getOperand(ArgOff++));
804 assert(CPU->getType() == Type::UByteTy);
805 unsigned Index = CPU->getValue();
807 #ifdef PROFILE_STRUCTURE_FIELDS
808 if (ProfileStructureFields) {
809 // Do accounting for this field...
810 vector<unsigned> &OfC = FieldAccessCounts[STy];
811 if (OfC.size() == 0) OfC.resize(STy->getElementTypes().size());
816 Total += SLO->MemberOffsets[Index];
817 Ty = STy->getElementTypes()[Index];
818 } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
820 // Get the index number for the array... which must be uint type...
821 assert(I->getOperand(ArgOff)->getType() == Type::UIntTy);
822 unsigned Idx = getOperandValue(I->getOperand(ArgOff++), SF).UIntVal;
823 if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
824 if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
825 cerr << "Out of range memory access to element #" << Idx
826 << " of a " << AT->getNumElements() << " element array."
827 << " Subscript #" << (ArgOff-I->getFirstIndexOperandNumber())
830 siglongjmp(SignalRecoverBuffer, SIGTRAP);
833 Ty = ST->getElementType();
834 unsigned Size = TD.getTypeSize(Ty);
842 static void executeGEPInst(GetElementPtrInst *I, ExecutionContext &SF) {
843 GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
844 PointerTy SrcPtr = SRC.PointerVal;
847 Result.PointerVal = SrcPtr + getElementOffset(I, SF);
848 SetValue(I, Result, SF);
851 static void executeLoadInst(LoadInst *I, ExecutionContext &SF) {
852 GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
853 PointerTy SrcPtr = SRC.PointerVal;
854 PointerTy Offset = getElementOffset(I, SF); // Handle any structure indices
857 GenericValue *Ptr = (GenericValue*)SrcPtr;
860 switch (I->getType()->getPrimitiveID()) {
862 case Type::UByteTyID:
863 case Type::SByteTyID: Result.SByteVal = Ptr->SByteVal; break;
864 case Type::UShortTyID:
865 case Type::ShortTyID: Result.ShortVal = Ptr->ShortVal; break;
867 case Type::IntTyID: Result.IntVal = Ptr->IntVal; break;
868 case Type::ULongTyID:
869 case Type::LongTyID: Result.ULongVal = Ptr->ULongVal; break;
870 case Type::PointerTyID: Result.PointerVal = Ptr->PointerVal; break;
871 case Type::FloatTyID: Result.FloatVal = Ptr->FloatVal; break;
872 case Type::DoubleTyID: Result.DoubleVal = Ptr->DoubleVal; break;
874 cout << "Cannot load value of type " << I->getType() << "!\n";
877 SetValue(I, Result, SF);
880 static void executeStoreInst(StoreInst *I, ExecutionContext &SF) {
881 GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
882 PointerTy SrcPtr = SRC.PointerVal;
883 SrcPtr += getElementOffset(I, SF); // Handle any structure indices
885 GenericValue *Ptr = (GenericValue *)SrcPtr;
886 GenericValue Val = getOperandValue(I->getOperand(0), SF);
888 switch (I->getOperand(0)->getType()->getPrimitiveID()) {
890 case Type::UByteTyID:
891 case Type::SByteTyID: Ptr->SByteVal = Val.SByteVal; break;
892 case Type::UShortTyID:
893 case Type::ShortTyID: Ptr->ShortVal = Val.ShortVal; break;
895 case Type::IntTyID: Ptr->IntVal = Val.IntVal; break;
896 case Type::ULongTyID:
897 case Type::LongTyID: Ptr->LongVal = Val.LongVal; break;
898 case Type::PointerTyID: Ptr->PointerVal = Val.PointerVal; break;
899 case Type::FloatTyID: Ptr->FloatVal = Val.FloatVal; break;
900 case Type::DoubleTyID: Ptr->DoubleVal = Val.DoubleVal; break;
902 cout << "Cannot store value of type " << I->getType() << "!\n";
907 //===----------------------------------------------------------------------===//
908 // Miscellaneous Instruction Implementations
909 //===----------------------------------------------------------------------===//
911 void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
912 ECStack.back().Caller = I;
913 vector<GenericValue> ArgVals;
914 ArgVals.reserve(I->getNumOperands()-1);
915 for (unsigned i = 1; i < I->getNumOperands(); ++i)
916 ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
918 // To handle indirect calls, we must get the pointer value from the argument
919 // and treat it as a function pointer.
920 GenericValue SRC = getOperandValue(I->getCalledValue(), SF);
922 callMethod((Function*)SRC.PointerVal, ArgVals);
925 static void executePHINode(PHINode *I, ExecutionContext &SF) {
926 BasicBlock *PrevBB = SF.PrevBB;
927 Value *IncomingValue = 0;
929 // Search for the value corresponding to this previous bb...
930 for (unsigned i = I->getNumIncomingValues(); i > 0;) {
931 if (I->getIncomingBlock(--i) == PrevBB) {
932 IncomingValue = I->getIncomingValue(i);
936 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
938 // Found the value, set as the result...
939 SetValue(I, getOperandValue(IncomingValue, SF), SF);
942 #define IMPLEMENT_SHIFT(OP, TY) \
943 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
945 static void executeShlInst(ShiftInst *I, ExecutionContext &SF) {
946 const Type *Ty = I->getOperand(0)->getType();
947 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
948 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
951 switch (Ty->getPrimitiveID()) {
952 IMPLEMENT_SHIFT(<<, UByte);
953 IMPLEMENT_SHIFT(<<, SByte);
954 IMPLEMENT_SHIFT(<<, UShort);
955 IMPLEMENT_SHIFT(<<, Short);
956 IMPLEMENT_SHIFT(<<, UInt);
957 IMPLEMENT_SHIFT(<<, Int);
958 IMPLEMENT_SHIFT(<<, ULong);
959 IMPLEMENT_SHIFT(<<, Long);
961 cout << "Unhandled type for Shl instruction: " << Ty << "\n";
963 SetValue(I, Dest, SF);
966 static void executeShrInst(ShiftInst *I, ExecutionContext &SF) {
967 const Type *Ty = I->getOperand(0)->getType();
968 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
969 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
972 switch (Ty->getPrimitiveID()) {
973 IMPLEMENT_SHIFT(>>, UByte);
974 IMPLEMENT_SHIFT(>>, SByte);
975 IMPLEMENT_SHIFT(>>, UShort);
976 IMPLEMENT_SHIFT(>>, Short);
977 IMPLEMENT_SHIFT(>>, UInt);
978 IMPLEMENT_SHIFT(>>, Int);
979 IMPLEMENT_SHIFT(>>, ULong);
980 IMPLEMENT_SHIFT(>>, Long);
982 cout << "Unhandled type for Shr instruction: " << Ty << "\n";
984 SetValue(I, Dest, SF);
987 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
988 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
990 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
991 case Type::DESTTY##TyID: \
992 switch (SrcTy->getPrimitiveID()) { \
993 IMPLEMENT_CAST(DESTTY, DESTCTY, Bool); \
994 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
995 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
996 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
997 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
998 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
999 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
1000 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
1001 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
1002 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
1004 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
1005 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
1006 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
1008 #define IMPLEMENT_CAST_CASE_END() \
1009 default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
1014 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
1015 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
1016 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
1017 IMPLEMENT_CAST_CASE_END()
1019 static void executeCastInst(CastInst *I, ExecutionContext &SF) {
1020 const Type *Ty = I->getType();
1021 const Type *SrcTy = I->getOperand(0)->getType();
1022 GenericValue Src = getOperandValue(I->getOperand(0), SF);
1025 switch (Ty->getPrimitiveID()) {
1026 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
1027 IMPLEMENT_CAST_CASE(SByte , ( signed char));
1028 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1029 IMPLEMENT_CAST_CASE(Short , ( signed char));
1030 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
1031 IMPLEMENT_CAST_CASE(Int , ( signed int ));
1032 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
1033 IMPLEMENT_CAST_CASE(Long , ( int64_t));
1034 IMPLEMENT_CAST_CASE(Pointer, (PointerTy)(uint32_t));
1035 IMPLEMENT_CAST_CASE(Float , (float));
1036 IMPLEMENT_CAST_CASE(Double , (double));
1038 cout << "Unhandled dest type for cast instruction: " << Ty << "\n";
1040 SetValue(I, Dest, SF);
1046 //===----------------------------------------------------------------------===//
1047 // Dispatch and Execution Code
1048 //===----------------------------------------------------------------------===//
1050 MethodInfo::MethodInfo(Function *M) : Annotation(MethodInfoAID) {
1051 // Assign slot numbers to the function arguments...
1052 const Function::ArgumentListType &ArgList = M->getArgumentList();
1053 for (Function::ArgumentListType::const_iterator AI = ArgList.begin(),
1054 AE = ArgList.end(); AI != AE; ++AI)
1055 ((Value*)(*AI))->addAnnotation(new SlotNumber(getValueSlot((Value*)*AI)));
1057 // Iterate over all of the instructions...
1058 unsigned InstNum = 0;
1059 for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
1060 BasicBlock *BB = *MI;
1061 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
1062 Instruction *I = *II; // For each instruction... Add Annote
1063 I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I)));
1068 unsigned MethodInfo::getValueSlot(const Value *V) {
1069 unsigned Plane = V->getType()->getUniqueID();
1070 if (Plane >= NumPlaneElements.size())
1071 NumPlaneElements.resize(Plane+1, 0);
1072 return NumPlaneElements[Plane]++;
1076 //===----------------------------------------------------------------------===//
1077 // callMethod - Execute the specified function...
1079 void Interpreter::callMethod(Function *M, const vector<GenericValue> &ArgVals) {
1080 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
1081 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
1082 "Incorrect number of arguments passed into function call!");
1083 if (M->isExternal()) {
1084 GenericValue Result = callExternalMethod(M, ArgVals);
1085 const Type *RetTy = M->getReturnType();
1087 // Copy the result back into the result variable if we are not returning
1089 if (RetTy != Type::VoidTy) {
1090 if (!ECStack.empty() && ECStack.back().Caller) {
1091 ExecutionContext &SF = ECStack.back();
1092 SetValue(SF.Caller, Result, SF);
1094 SF.Caller = 0; // We returned from the call...
1095 } else if (!QuietMode) {
1097 CW << "Function " << M->getType() << " \"" << M->getName()
1099 print(RetTy, Result);
1102 if (RetTy->isIntegral())
1103 ExitCode = Result.SByteVal; // Capture the exit code of the program
1110 // Process the function, assigning instruction numbers to the instructions in
1111 // the function. Also calculate the number of values for each type slot
1114 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
1115 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
1117 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
1118 StackFrame.CurMethod = M;
1119 StackFrame.CurBB = M->front();
1120 StackFrame.CurInst = StackFrame.CurBB->begin();
1121 StackFrame.MethInfo = MethInfo;
1123 // Initialize the values to nothing...
1124 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
1125 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i) {
1126 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
1128 // Taint the initial values of stuff
1129 memset(&StackFrame.Values[i][0], 42,
1130 MethInfo->NumPlaneElements[i]*sizeof(GenericValue));
1133 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
1136 // Run through the function arguments and initialize their values...
1137 assert(ArgVals.size() == M->getArgumentList().size() &&
1138 "Invalid number of values passed to function invocation!");
1140 for (Function::ArgumentListType::iterator AI = M->getArgumentList().begin(),
1141 AE = M->getArgumentList().end(); AI != AE; ++AI, ++i) {
1142 SetValue((Value*)*AI, ArgVals[i], StackFrame);
1146 // executeInstruction - Interpret a single instruction, increment the "PC", and
1147 // return true if the next instruction is a breakpoint...
1149 bool Interpreter::executeInstruction() {
1150 assert(!ECStack.empty() && "No program running, cannot execute inst!");
1152 ExecutionContext &SF = ECStack.back(); // Current stack frame
1153 Instruction *I = *SF.CurInst++; // Increment before execute
1158 // Set a sigsetjmp buffer so that we can recover if an error happens during
1159 // instruction execution...
1161 if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1162 --SF.CurInst; // Back up to erroring instruction
1163 if (SigNo != SIGINT) {
1164 cout << "EXCEPTION OCCURRED [" << _sys_siglistp[SigNo] << "]:\n";
1166 // If -abort-on-exception was specified, terminate LLI instead of trying
1169 if (AbortOnExceptions) exit(1);
1170 } else if (SigNo == SIGINT) {
1171 cout << "CTRL-C Detected, execution halted.\n";
1173 InInstruction = false;
1177 InInstruction = true;
1178 if (I->isBinaryOp()) {
1179 executeBinaryInst(cast<BinaryOperator>(I), SF);
1181 switch (I->getOpcode()) {
1182 case Instruction::Not: executeNotInst(cast<UnaryOperator>(I),SF); break;
1184 case Instruction::Ret: executeRetInst (cast<ReturnInst>(I), SF); break;
1185 case Instruction::Br: executeBrInst (cast<BranchInst>(I), SF); break;
1186 // Memory Instructions
1187 case Instruction::Alloca:
1188 case Instruction::Malloc: executeAllocInst((AllocationInst*)I, SF); break;
1189 case Instruction::Free: executeFreeInst (cast<FreeInst> (I), SF); break;
1190 case Instruction::Load: executeLoadInst (cast<LoadInst> (I), SF); break;
1191 case Instruction::Store: executeStoreInst(cast<StoreInst>(I), SF); break;
1192 case Instruction::GetElementPtr:
1193 executeGEPInst(cast<GetElementPtrInst>(I), SF); break;
1195 // Miscellaneous Instructions
1196 case Instruction::Call: executeCallInst (cast<CallInst> (I), SF); break;
1197 case Instruction::PHINode: executePHINode (cast<PHINode> (I), SF); break;
1198 case Instruction::Shl: executeShlInst (cast<ShiftInst>(I), SF); break;
1199 case Instruction::Shr: executeShrInst (cast<ShiftInst>(I), SF); break;
1200 case Instruction::Cast: executeCastInst (cast<CastInst> (I), SF); break;
1202 cout << "Don't know how to execute this instruction!\n-->" << I;
1205 InInstruction = false;
1207 // Reset the current frame location to the top of stack
1208 CurFrame = ECStack.size()-1;
1210 if (CurFrame == -1) return false; // No breakpoint if no code
1212 // Return true if there is a breakpoint annotation on the instruction...
1213 return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
1216 void Interpreter::stepInstruction() { // Do the 'step' command
1217 if (ECStack.empty()) {
1218 cout << "Error: no program running, cannot step!\n";
1222 // Run an instruction...
1223 executeInstruction();
1225 // Print the next instruction to execute...
1226 printCurrentInstruction();
1230 void Interpreter::nextInstruction() { // Do the 'next' command
1231 if (ECStack.empty()) {
1232 cout << "Error: no program running, cannot 'next'!\n";
1236 // If this is a call instruction, step over the call instruction...
1237 // TODO: ICALL, CALL WITH, ...
1238 if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
1239 unsigned StackSize = ECStack.size();
1240 // Step into the function...
1241 if (executeInstruction()) {
1242 // Hit a breakpoint, print current instruction, then return to user...
1243 cout << "Breakpoint hit!\n";
1244 printCurrentInstruction();
1248 // If we we able to step into the function, finish it now. We might not be
1249 // able the step into a function, if it's external for example.
1250 if (ECStack.size() != StackSize)
1251 finish(); // Finish executing the function...
1253 printCurrentInstruction();
1256 // Normal instruction, just step...
1261 void Interpreter::run() {
1262 if (ECStack.empty()) {
1263 cout << "Error: no program running, cannot run!\n";
1267 bool HitBreakpoint = false;
1268 while (!ECStack.empty() && !HitBreakpoint) {
1269 // Run an instruction...
1270 HitBreakpoint = executeInstruction();
1273 if (HitBreakpoint) {
1274 cout << "Breakpoint hit!\n";
1276 // Print the next instruction to execute...
1277 printCurrentInstruction();
1280 void Interpreter::finish() {
1281 if (ECStack.empty()) {
1282 cout << "Error: no program running, cannot run!\n";
1286 unsigned StackSize = ECStack.size();
1287 bool HitBreakpoint = false;
1288 while (ECStack.size() >= StackSize && !HitBreakpoint) {
1289 // Run an instruction...
1290 HitBreakpoint = executeInstruction();
1293 if (HitBreakpoint) {
1294 cout << "Breakpoint hit!\n";
1297 // Print the next instruction to execute...
1298 printCurrentInstruction();
1303 // printCurrentInstruction - Print out the instruction that the virtual PC is
1304 // at, or fail silently if no program is running.
1306 void Interpreter::printCurrentInstruction() {
1307 if (!ECStack.empty()) {
1308 if (ECStack.back().CurBB->begin() == ECStack.back().CurInst) // print label
1309 WriteAsOperand(cout, ECStack.back().CurBB) << ":\n";
1311 Instruction *I = *ECStack.back().CurInst;
1312 InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
1313 assert(IN && "Instruction has no numbering annotation!");
1314 cout << "#" << IN->InstNum << I;
1318 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1319 switch (Ty->getPrimitiveID()) {
1320 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
1321 case Type::SByteTyID: cout << V.SByteVal; break;
1322 case Type::UByteTyID: cout << V.UByteVal; break;
1323 case Type::ShortTyID: cout << V.ShortVal; break;
1324 case Type::UShortTyID: cout << V.UShortVal; break;
1325 case Type::IntTyID: cout << V.IntVal; break;
1326 case Type::UIntTyID: cout << V.UIntVal; break;
1327 case Type::LongTyID: cout << (long)V.LongVal; break;
1328 case Type::ULongTyID: cout << (unsigned long)V.ULongVal; break;
1329 case Type::FloatTyID: cout << V.FloatVal; break;
1330 case Type::DoubleTyID: cout << V.DoubleVal; break;
1331 case Type::PointerTyID:cout << (void*)V.PointerVal; break;
1333 cout << "- Don't know how to print value of this type!";
1338 void Interpreter::print(const Type *Ty, GenericValue V) {
1343 void Interpreter::print(const std::string &Name) {
1344 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1345 if (!PickedVal) return;
1347 if (const Function *F = dyn_cast<const Function>(PickedVal)) {
1348 CW << F; // Print the function
1349 } else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
1350 CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
1351 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
1352 CW << BB; // Print the basic block
1353 } else { // Otherwise there should be an annotation for the slot#
1354 print(PickedVal->getType(),
1355 getOperandValue(PickedVal, ECStack[CurFrame]));
1360 void Interpreter::infoValue(const std::string &Name) {
1361 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1362 if (!PickedVal) return;
1365 print(PickedVal->getType(),
1366 getOperandValue(PickedVal, ECStack[CurFrame]));
1368 printOperandInfo(PickedVal, ECStack[CurFrame]);
1371 // printStackFrame - Print information about the specified stack frame, or -1
1372 // for the default one.
1374 void Interpreter::printStackFrame(int FrameNo = -1) {
1375 if (FrameNo == -1) FrameNo = CurFrame;
1376 Function *Func = ECStack[FrameNo].CurMethod;
1377 const Type *RetTy = Func->getReturnType();
1379 CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1380 << (Value*)RetTy << " \"" << Func->getName() << "\"(";
1382 Function::ArgumentListType &Args = Func->getArgumentList();
1383 for (unsigned i = 0; i < Args.size(); ++i) {
1384 if (i != 0) cout << ", ";
1385 CW << (Value*)Args[i] << "=";
1387 printValue(((Value*)Args[i])->getType(),
1388 getOperandValue((Value*)Args[i], ECStack[FrameNo]));
1392 CW << *(ECStack[FrameNo].CurInst-(FrameNo != int(ECStack.size()-1)));