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 <math.h> // For fmod
26 QuietMode("quiet", cl::desc("Do not emit any non-program output"));
29 QuietModeA("q", cl::desc("Alias for -quiet"), cl::aliasopt(QuietMode));
32 ArrayChecksEnabled("array-checks", cl::desc("Enable array bound checks"));
35 AbortOnExceptions("abort-on-exception",
36 cl::desc("Halt execution on a machine exception"));
38 // Create a TargetData structure to handle memory addressing and size/alignment
41 TargetData TD("lli Interpreter");
42 CachedWriter CW; // Object to accelerate printing of LLVM
45 #ifdef PROFILE_STRUCTURE_FIELDS
47 ProfileStructureFields("profilestructfields",
48 cl::desc("Profile Structure Field Accesses"));
50 static std::map<const StructType *, vector<unsigned> > FieldAccessCounts;
53 sigjmp_buf SignalRecoverBuffer;
54 static bool InInstruction = false;
57 static void SigHandler(int Signal) {
59 siglongjmp(SignalRecoverBuffer, Signal);
63 static void initializeSignalHandlers() {
64 struct sigaction Action;
65 Action.sa_handler = SigHandler;
66 Action.sa_flags = SA_SIGINFO;
67 sigemptyset(&Action.sa_mask);
68 sigaction(SIGSEGV, &Action, 0);
69 sigaction(SIGBUS, &Action, 0);
70 sigaction(SIGINT, &Action, 0);
71 sigaction(SIGFPE, &Action, 0);
75 //===----------------------------------------------------------------------===//
76 // Value Manipulation code
77 //===----------------------------------------------------------------------===//
79 static unsigned getOperandSlot(Value *V) {
80 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
81 assert(SN && "Operand does not have a slot number annotation!");
85 #define GET_CONST_VAL(TY, CLASS) \
86 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
88 // Operations used by constant expr implementations...
89 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
90 ExecutionContext &SF);
91 static GenericValue executeGEPOperation(Value *Src, User::op_iterator IdxBegin,
92 User::op_iterator IdxEnd,
93 ExecutionContext &SF);
94 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
95 const Type *Ty, ExecutionContext &SF);
97 static GenericValue getConstantValue(const Constant *C) {
99 switch (C->getType()->getPrimitiveID()) {
100 GET_CONST_VAL(Bool , ConstantBool);
101 GET_CONST_VAL(UByte , ConstantUInt);
102 GET_CONST_VAL(SByte , ConstantSInt);
103 GET_CONST_VAL(UShort , ConstantUInt);
104 GET_CONST_VAL(Short , ConstantSInt);
105 GET_CONST_VAL(UInt , ConstantUInt);
106 GET_CONST_VAL(Int , ConstantSInt);
107 GET_CONST_VAL(ULong , ConstantUInt);
108 GET_CONST_VAL(Long , ConstantSInt);
109 GET_CONST_VAL(Float , ConstantFP);
110 GET_CONST_VAL(Double , ConstantFP);
111 case Type::PointerTyID:
112 if (isa<ConstantPointerNull>(C)) {
113 Result.PointerVal = 0;
114 } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
115 GlobalAddress *Address =
116 (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
117 Result.PointerVal = (PointerTy)Address->Ptr;
119 assert(0 && "Unknown constant pointer type!");
123 cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
128 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
129 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
130 switch (CE->getOpcode()) {
131 case Instruction::Cast:
132 return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
133 case Instruction::GetElementPtr:
134 return executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
136 case Instruction::Add:
137 return executeAddInst(getOperandValue(CE->getOperand(0), SF),
138 getOperandValue(CE->getOperand(1), SF),
141 cerr << "Unhandled ConstantExpr: " << CE << "\n";
143 { GenericValue V; return V; }
145 } else if (Constant *CPV = dyn_cast<Constant>(V)) {
146 return getConstantValue(CPV);
147 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
148 GlobalAddress *Address =
149 (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
151 Result.PointerVal = (PointerTy)(GenericValue*)Address->Ptr;
154 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
155 unsigned OpSlot = getOperandSlot(V);
156 assert(TyP < SF.Values.size() &&
157 OpSlot < SF.Values[TyP].size() && "Value out of range!");
158 return SF.Values[TyP][getOperandSlot(V)];
162 static void printOperandInfo(Value *V, ExecutionContext &SF) {
163 if (isa<Constant>(V)) {
164 cout << "Constant Pool Value\n";
165 } else if (isa<GlobalValue>(V)) {
166 cout << "Global Value\n";
168 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
169 unsigned Slot = getOperandSlot(V);
170 cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
171 << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF
174 const unsigned char *Buf = (const unsigned char*)&SF.Values[TyP][Slot];
175 for (unsigned i = 0; i < sizeof(GenericValue); ++i) {
176 unsigned char Cur = Buf[i];
177 cout << ( Cur >= 160? char((Cur>>4)+'A'-10) : char((Cur>>4) + '0'))
178 << ((Cur&15) >= 10? char((Cur&15)+'A'-10) : char((Cur&15) + '0'));
186 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
187 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
189 //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << "\n";
190 SF.Values[TyP][getOperandSlot(V)] = Val;
194 //===----------------------------------------------------------------------===//
195 // Annotation Wrangling code
196 //===----------------------------------------------------------------------===//
198 void Interpreter::initializeExecutionEngine() {
199 AnnotationManager::registerAnnotationFactory(MethodInfoAID,
200 &MethodInfo::Create);
201 AnnotationManager::registerAnnotationFactory(GlobalAddressAID,
202 &GlobalAddress::Create);
203 initializeSignalHandlers();
206 static void StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
209 // InitializeMemory - Recursive function to apply a Constant value into the
210 // specified memory location...
212 static void InitializeMemory(const Constant *Init, char *Addr) {
214 if (Init->getType()->isFirstClassType()) {
215 GenericValue Val = getConstantValue(Init);
216 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
220 switch (Init->getType()->getPrimitiveID()) {
221 case Type::ArrayTyID: {
222 const ConstantArray *CPA = cast<ConstantArray>(Init);
223 const vector<Use> &Val = CPA->getValues();
224 unsigned ElementSize =
225 TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
226 for (unsigned i = 0; i < Val.size(); ++i)
227 InitializeMemory(cast<Constant>(Val[i].get()), Addr+i*ElementSize);
231 case Type::StructTyID: {
232 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
233 const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
234 const vector<Use> &Val = CPS->getValues();
235 for (unsigned i = 0; i < Val.size(); ++i)
236 InitializeMemory(cast<Constant>(Val[i].get()),
237 Addr+SL->MemberOffsets[i]);
242 CW << "Bad Type: " << Init->getType() << "\n";
243 assert(0 && "Unknown constant type to initialize memory with!");
247 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
248 assert(AID == GlobalAddressAID);
250 // This annotation will only be created on GlobalValue objects...
251 GlobalValue *GVal = cast<GlobalValue>((Value*)O);
253 if (isa<Function>(GVal)) {
254 // The GlobalAddress object for a function is just a pointer to function
255 // itself. Don't delete it when the annotation is gone though!
256 return new GlobalAddress(GVal, false);
259 // Handle the case of a global variable...
260 assert(isa<GlobalVariable>(GVal) &&
261 "Global value found that isn't a function or global variable!");
262 GlobalVariable *GV = cast<GlobalVariable>(GVal);
264 // First off, we must allocate space for the global variable to point at...
265 const Type *Ty = GV->getType()->getElementType(); // Type to be allocated
267 // Allocate enough memory to hold the type...
268 void *Addr = calloc(1, TD.getTypeSize(Ty));
269 assert(Addr != 0 && "Null pointer returned by malloc!");
271 // Initialize the memory if there is an initializer...
272 if (GV->hasInitializer())
273 InitializeMemory(GV->getInitializer(), (char*)Addr);
275 return new GlobalAddress(Addr, true); // Simply invoke the ctor
278 //===----------------------------------------------------------------------===//
279 // Binary Instruction Implementations
280 //===----------------------------------------------------------------------===//
282 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
283 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
285 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
286 const Type *Ty, ExecutionContext &SF) {
288 switch (Ty->getPrimitiveID()) {
289 IMPLEMENT_BINARY_OPERATOR(+, UByte);
290 IMPLEMENT_BINARY_OPERATOR(+, SByte);
291 IMPLEMENT_BINARY_OPERATOR(+, UShort);
292 IMPLEMENT_BINARY_OPERATOR(+, Short);
293 IMPLEMENT_BINARY_OPERATOR(+, UInt);
294 IMPLEMENT_BINARY_OPERATOR(+, Int);
295 IMPLEMENT_BINARY_OPERATOR(+, ULong);
296 IMPLEMENT_BINARY_OPERATOR(+, Long);
297 IMPLEMENT_BINARY_OPERATOR(+, Float);
298 IMPLEMENT_BINARY_OPERATOR(+, Double);
299 IMPLEMENT_BINARY_OPERATOR(+, Pointer);
301 cout << "Unhandled type for Add instruction: " << Ty << "\n";
306 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
307 const Type *Ty, ExecutionContext &SF) {
309 switch (Ty->getPrimitiveID()) {
310 IMPLEMENT_BINARY_OPERATOR(-, UByte);
311 IMPLEMENT_BINARY_OPERATOR(-, SByte);
312 IMPLEMENT_BINARY_OPERATOR(-, UShort);
313 IMPLEMENT_BINARY_OPERATOR(-, Short);
314 IMPLEMENT_BINARY_OPERATOR(-, UInt);
315 IMPLEMENT_BINARY_OPERATOR(-, Int);
316 IMPLEMENT_BINARY_OPERATOR(-, ULong);
317 IMPLEMENT_BINARY_OPERATOR(-, Long);
318 IMPLEMENT_BINARY_OPERATOR(-, Float);
319 IMPLEMENT_BINARY_OPERATOR(-, Double);
320 IMPLEMENT_BINARY_OPERATOR(-, Pointer);
322 cout << "Unhandled type for Sub instruction: " << Ty << "\n";
327 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
328 const Type *Ty, ExecutionContext &SF) {
330 switch (Ty->getPrimitiveID()) {
331 IMPLEMENT_BINARY_OPERATOR(*, UByte);
332 IMPLEMENT_BINARY_OPERATOR(*, SByte);
333 IMPLEMENT_BINARY_OPERATOR(*, UShort);
334 IMPLEMENT_BINARY_OPERATOR(*, Short);
335 IMPLEMENT_BINARY_OPERATOR(*, UInt);
336 IMPLEMENT_BINARY_OPERATOR(*, Int);
337 IMPLEMENT_BINARY_OPERATOR(*, ULong);
338 IMPLEMENT_BINARY_OPERATOR(*, Long);
339 IMPLEMENT_BINARY_OPERATOR(*, Float);
340 IMPLEMENT_BINARY_OPERATOR(*, Double);
341 IMPLEMENT_BINARY_OPERATOR(*, Pointer);
343 cout << "Unhandled type for Mul instruction: " << Ty << "\n";
348 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
349 const Type *Ty, ExecutionContext &SF) {
351 switch (Ty->getPrimitiveID()) {
352 IMPLEMENT_BINARY_OPERATOR(/, UByte);
353 IMPLEMENT_BINARY_OPERATOR(/, SByte);
354 IMPLEMENT_BINARY_OPERATOR(/, UShort);
355 IMPLEMENT_BINARY_OPERATOR(/, Short);
356 IMPLEMENT_BINARY_OPERATOR(/, UInt);
357 IMPLEMENT_BINARY_OPERATOR(/, Int);
358 IMPLEMENT_BINARY_OPERATOR(/, ULong);
359 IMPLEMENT_BINARY_OPERATOR(/, Long);
360 IMPLEMENT_BINARY_OPERATOR(/, Float);
361 IMPLEMENT_BINARY_OPERATOR(/, Double);
362 IMPLEMENT_BINARY_OPERATOR(/, Pointer);
364 cout << "Unhandled type for Div instruction: " << Ty << "\n";
369 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
370 const Type *Ty, ExecutionContext &SF) {
372 switch (Ty->getPrimitiveID()) {
373 IMPLEMENT_BINARY_OPERATOR(%, UByte);
374 IMPLEMENT_BINARY_OPERATOR(%, SByte);
375 IMPLEMENT_BINARY_OPERATOR(%, UShort);
376 IMPLEMENT_BINARY_OPERATOR(%, Short);
377 IMPLEMENT_BINARY_OPERATOR(%, UInt);
378 IMPLEMENT_BINARY_OPERATOR(%, Int);
379 IMPLEMENT_BINARY_OPERATOR(%, ULong);
380 IMPLEMENT_BINARY_OPERATOR(%, Long);
381 IMPLEMENT_BINARY_OPERATOR(%, Pointer);
382 case Type::FloatTyID:
383 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
385 case Type::DoubleTyID:
386 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
389 cout << "Unhandled type for Rem instruction: " << Ty << "\n";
394 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
395 const Type *Ty, ExecutionContext &SF) {
397 switch (Ty->getPrimitiveID()) {
398 IMPLEMENT_BINARY_OPERATOR(&, UByte);
399 IMPLEMENT_BINARY_OPERATOR(&, SByte);
400 IMPLEMENT_BINARY_OPERATOR(&, UShort);
401 IMPLEMENT_BINARY_OPERATOR(&, Short);
402 IMPLEMENT_BINARY_OPERATOR(&, UInt);
403 IMPLEMENT_BINARY_OPERATOR(&, Int);
404 IMPLEMENT_BINARY_OPERATOR(&, ULong);
405 IMPLEMENT_BINARY_OPERATOR(&, Long);
406 IMPLEMENT_BINARY_OPERATOR(&, Pointer);
408 cout << "Unhandled type for And instruction: " << Ty << "\n";
414 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
415 const Type *Ty, ExecutionContext &SF) {
417 switch (Ty->getPrimitiveID()) {
418 IMPLEMENT_BINARY_OPERATOR(|, UByte);
419 IMPLEMENT_BINARY_OPERATOR(|, SByte);
420 IMPLEMENT_BINARY_OPERATOR(|, UShort);
421 IMPLEMENT_BINARY_OPERATOR(|, Short);
422 IMPLEMENT_BINARY_OPERATOR(|, UInt);
423 IMPLEMENT_BINARY_OPERATOR(|, Int);
424 IMPLEMENT_BINARY_OPERATOR(|, ULong);
425 IMPLEMENT_BINARY_OPERATOR(|, Long);
426 IMPLEMENT_BINARY_OPERATOR(|, Pointer);
428 cout << "Unhandled type for Or instruction: " << Ty << "\n";
434 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
435 const Type *Ty, ExecutionContext &SF) {
437 switch (Ty->getPrimitiveID()) {
438 IMPLEMENT_BINARY_OPERATOR(^, UByte);
439 IMPLEMENT_BINARY_OPERATOR(^, SByte);
440 IMPLEMENT_BINARY_OPERATOR(^, UShort);
441 IMPLEMENT_BINARY_OPERATOR(^, Short);
442 IMPLEMENT_BINARY_OPERATOR(^, UInt);
443 IMPLEMENT_BINARY_OPERATOR(^, Int);
444 IMPLEMENT_BINARY_OPERATOR(^, ULong);
445 IMPLEMENT_BINARY_OPERATOR(^, Long);
446 IMPLEMENT_BINARY_OPERATOR(^, Pointer);
448 cout << "Unhandled type for Xor instruction: " << Ty << "\n";
454 #define IMPLEMENT_SETCC(OP, TY) \
455 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
457 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
458 const Type *Ty, ExecutionContext &SF) {
460 switch (Ty->getPrimitiveID()) {
461 IMPLEMENT_SETCC(==, UByte);
462 IMPLEMENT_SETCC(==, SByte);
463 IMPLEMENT_SETCC(==, UShort);
464 IMPLEMENT_SETCC(==, Short);
465 IMPLEMENT_SETCC(==, UInt);
466 IMPLEMENT_SETCC(==, Int);
467 IMPLEMENT_SETCC(==, ULong);
468 IMPLEMENT_SETCC(==, Long);
469 IMPLEMENT_SETCC(==, Float);
470 IMPLEMENT_SETCC(==, Double);
471 IMPLEMENT_SETCC(==, Pointer);
473 cout << "Unhandled type for SetEQ instruction: " << Ty << "\n";
478 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
479 const Type *Ty, ExecutionContext &SF) {
481 switch (Ty->getPrimitiveID()) {
482 IMPLEMENT_SETCC(!=, UByte);
483 IMPLEMENT_SETCC(!=, SByte);
484 IMPLEMENT_SETCC(!=, UShort);
485 IMPLEMENT_SETCC(!=, Short);
486 IMPLEMENT_SETCC(!=, UInt);
487 IMPLEMENT_SETCC(!=, Int);
488 IMPLEMENT_SETCC(!=, ULong);
489 IMPLEMENT_SETCC(!=, Long);
490 IMPLEMENT_SETCC(!=, Float);
491 IMPLEMENT_SETCC(!=, Double);
492 IMPLEMENT_SETCC(!=, Pointer);
495 cout << "Unhandled type for SetNE instruction: " << Ty << "\n";
500 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
501 const Type *Ty, ExecutionContext &SF) {
503 switch (Ty->getPrimitiveID()) {
504 IMPLEMENT_SETCC(<=, UByte);
505 IMPLEMENT_SETCC(<=, SByte);
506 IMPLEMENT_SETCC(<=, UShort);
507 IMPLEMENT_SETCC(<=, Short);
508 IMPLEMENT_SETCC(<=, UInt);
509 IMPLEMENT_SETCC(<=, Int);
510 IMPLEMENT_SETCC(<=, ULong);
511 IMPLEMENT_SETCC(<=, Long);
512 IMPLEMENT_SETCC(<=, Float);
513 IMPLEMENT_SETCC(<=, Double);
514 IMPLEMENT_SETCC(<=, Pointer);
516 cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
521 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
522 const Type *Ty, ExecutionContext &SF) {
524 switch (Ty->getPrimitiveID()) {
525 IMPLEMENT_SETCC(>=, UByte);
526 IMPLEMENT_SETCC(>=, SByte);
527 IMPLEMENT_SETCC(>=, UShort);
528 IMPLEMENT_SETCC(>=, Short);
529 IMPLEMENT_SETCC(>=, UInt);
530 IMPLEMENT_SETCC(>=, Int);
531 IMPLEMENT_SETCC(>=, ULong);
532 IMPLEMENT_SETCC(>=, Long);
533 IMPLEMENT_SETCC(>=, Float);
534 IMPLEMENT_SETCC(>=, Double);
535 IMPLEMENT_SETCC(>=, Pointer);
537 cout << "Unhandled type for SetGE instruction: " << Ty << "\n";
542 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
543 const Type *Ty, ExecutionContext &SF) {
545 switch (Ty->getPrimitiveID()) {
546 IMPLEMENT_SETCC(<, UByte);
547 IMPLEMENT_SETCC(<, SByte);
548 IMPLEMENT_SETCC(<, UShort);
549 IMPLEMENT_SETCC(<, Short);
550 IMPLEMENT_SETCC(<, UInt);
551 IMPLEMENT_SETCC(<, Int);
552 IMPLEMENT_SETCC(<, ULong);
553 IMPLEMENT_SETCC(<, Long);
554 IMPLEMENT_SETCC(<, Float);
555 IMPLEMENT_SETCC(<, Double);
556 IMPLEMENT_SETCC(<, Pointer);
558 cout << "Unhandled type for SetLT instruction: " << Ty << "\n";
563 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
564 const Type *Ty, ExecutionContext &SF) {
566 switch (Ty->getPrimitiveID()) {
567 IMPLEMENT_SETCC(>, UByte);
568 IMPLEMENT_SETCC(>, SByte);
569 IMPLEMENT_SETCC(>, UShort);
570 IMPLEMENT_SETCC(>, Short);
571 IMPLEMENT_SETCC(>, UInt);
572 IMPLEMENT_SETCC(>, Int);
573 IMPLEMENT_SETCC(>, ULong);
574 IMPLEMENT_SETCC(>, Long);
575 IMPLEMENT_SETCC(>, Float);
576 IMPLEMENT_SETCC(>, Double);
577 IMPLEMENT_SETCC(>, Pointer);
579 cout << "Unhandled type for SetGT instruction: " << Ty << "\n";
584 static void executeBinaryInst(BinaryOperator &I, ExecutionContext &SF) {
585 const Type *Ty = I.getOperand(0)->getType();
586 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
587 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
588 GenericValue R; // Result
590 switch (I.getOpcode()) {
591 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty, SF); break;
592 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty, SF); break;
593 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty, SF); break;
594 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty, SF); break;
595 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty, SF); break;
596 case Instruction::And: R = executeAndInst (Src1, Src2, Ty, SF); break;
597 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty, SF); break;
598 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty, SF); break;
599 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
600 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
601 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
602 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
603 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
604 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
606 cout << "Don't know how to handle this binary operator!\n-->" << I;
613 //===----------------------------------------------------------------------===//
614 // Terminator Instruction Implementations
615 //===----------------------------------------------------------------------===//
617 static void PerformExitStuff() {
618 #ifdef PROFILE_STRUCTURE_FIELDS
619 // Print out structure field accounting information...
620 if (!FieldAccessCounts.empty()) {
621 CW << "Profile Field Access Counts:\n";
622 std::map<const StructType *, vector<unsigned> >::iterator
623 I = FieldAccessCounts.begin(), E = FieldAccessCounts.end();
624 for (; I != E; ++I) {
625 vector<unsigned> &OfC = I->second;
626 CW << " '" << (Value*)I->first << "'\t- Sum=";
629 for (unsigned i = 0; i < OfC.size(); ++i)
633 for (unsigned i = 0; i < OfC.size(); ++i) {
641 CW << "Profile Field Access Percentages:\n";
643 for (I = FieldAccessCounts.begin(); I != E; ++I) {
644 vector<unsigned> &OfC = I->second;
646 for (unsigned i = 0; i < OfC.size(); ++i)
649 CW << " '" << (Value*)I->first << "'\t- ";
650 for (unsigned i = 0; i < OfC.size(); ++i) {
652 CW << double(OfC[i])/Sum;
658 FieldAccessCounts.clear();
663 void Interpreter::exitCalled(GenericValue GV) {
665 cout << "Program returned ";
666 print(Type::IntTy, GV);
667 cout << " via 'void exit(int)'\n";
670 ExitCode = GV.SByteVal;
675 void Interpreter::executeRetInst(ReturnInst &I, ExecutionContext &SF) {
676 const Type *RetTy = 0;
679 // Save away the return value... (if we are not 'ret void')
680 if (I.getNumOperands()) {
681 RetTy = I.getReturnValue()->getType();
682 Result = getOperandValue(I.getReturnValue(), SF);
685 // Save previously executing meth
686 const Function *M = ECStack.back().CurMethod;
688 // Pop the current stack frame... this invalidates SF
691 if (ECStack.empty()) { // Finished main. Put result into exit code...
692 if (RetTy) { // Nonvoid return type?
694 CW << "Function " << M->getType() << " \"" << M->getName()
696 print(RetTy, Result);
700 if (RetTy->isIntegral())
701 ExitCode = Result.IntVal; // Capture the exit code of the program
710 // If we have a previous stack frame, and we have a previous call, fill in
711 // the return value...
713 ExecutionContext &NewSF = ECStack.back();
715 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
716 SetValue(NewSF.Caller, Result, NewSF);
718 NewSF.Caller = 0; // We returned from the call...
719 } else if (!QuietMode) {
720 // This must be a function that is executing because of a user 'call'
722 CW << "Function " << M->getType() << " \"" << M->getName()
724 print(RetTy, Result);
729 void Interpreter::executeBrInst(BranchInst &I, ExecutionContext &SF) {
730 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
733 Dest = I.getSuccessor(0); // Uncond branches have a fixed dest...
734 if (!I.isUnconditional()) {
735 Value *Cond = I.getCondition();
736 GenericValue CondVal = getOperandValue(Cond, SF);
737 if (CondVal.BoolVal == 0) // If false cond...
738 Dest = I.getSuccessor(1);
740 SF.CurBB = Dest; // Update CurBB to branch destination
741 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
744 //===----------------------------------------------------------------------===//
745 // Memory Instruction Implementations
746 //===----------------------------------------------------------------------===//
748 void Interpreter::executeAllocInst(AllocationInst &I, ExecutionContext &SF) {
749 const Type *Ty = I.getType()->getElementType(); // Type to be allocated
751 // Get the number of elements being allocated by the array...
752 unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
754 // Allocate enough memory to hold the type...
755 // FIXME: Don't use CALLOC, use a tainted malloc.
756 void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
759 Result.PointerVal = (PointerTy)Memory;
760 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
761 SetValue(&I, Result, SF);
763 if (I.getOpcode() == Instruction::Alloca)
764 ECStack.back().Allocas.add(Memory);
767 static void executeFreeInst(FreeInst &I, ExecutionContext &SF) {
768 assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
769 GenericValue Value = getOperandValue(I.getOperand(0), SF);
770 // TODO: Check to make sure memory is allocated
771 free((void*)Value.PointerVal); // Free memory
775 // getElementOffset - The workhorse for getelementptr.
777 static GenericValue executeGEPOperation(Value *Ptr, User::op_iterator I,
779 ExecutionContext &SF) {
780 assert(isa<PointerType>(Ptr->getType()) &&
781 "Cannot getElementOffset of a nonpointer type!");
784 const Type *Ty = Ptr->getType();
786 for (; I != E; ++I) {
787 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
788 const StructLayout *SLO = TD.getStructLayout(STy);
790 // Indicies must be ubyte constants...
791 const ConstantUInt *CPU = cast<ConstantUInt>(*I);
792 assert(CPU->getType() == Type::UByteTy);
793 unsigned Index = CPU->getValue();
795 #ifdef PROFILE_STRUCTURE_FIELDS
796 if (ProfileStructureFields) {
797 // Do accounting for this field...
798 vector<unsigned> &OfC = FieldAccessCounts[STy];
799 if (OfC.size() == 0) OfC.resize(STy->getElementTypes().size());
804 Total += SLO->MemberOffsets[Index];
805 Ty = STy->getElementTypes()[Index];
806 } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
808 // Get the index number for the array... which must be uint type...
809 assert((*I)->getType() == Type::LongTy);
810 unsigned Idx = getOperandValue(*I, SF).LongVal;
811 if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
812 if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
813 cerr << "Out of range memory access to element #" << Idx
814 << " of a " << AT->getNumElements() << " element array."
815 << " Subscript #" << *I << "\n";
817 siglongjmp(SignalRecoverBuffer, SIGTRAP);
820 Ty = ST->getElementType();
821 unsigned Size = TD.getTypeSize(Ty);
827 Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
831 static void executeGEPInst(GetElementPtrInst &I, ExecutionContext &SF) {
832 SetValue(&I, executeGEPOperation(I.getPointerOperand(),
833 I.idx_begin(), I.idx_end(), SF), SF);
836 static void executeLoadInst(LoadInst &I, ExecutionContext &SF) {
837 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
838 GenericValue *Ptr = (GenericValue*)SRC.PointerVal;
841 if (TD.isLittleEndian()) {
842 switch (I.getType()->getPrimitiveID()) {
844 case Type::UByteTyID:
845 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
846 case Type::UShortTyID:
847 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
848 ((unsigned)Ptr->Untyped[1] << 8);
850 case Type::FloatTyID:
852 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
853 ((unsigned)Ptr->Untyped[1] << 8) |
854 ((unsigned)Ptr->Untyped[2] << 16) |
855 ((unsigned)Ptr->Untyped[3] << 24);
857 case Type::DoubleTyID:
858 case Type::ULongTyID:
860 case Type::PointerTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
861 ((uint64_t)Ptr->Untyped[1] << 8) |
862 ((uint64_t)Ptr->Untyped[2] << 16) |
863 ((uint64_t)Ptr->Untyped[3] << 24) |
864 ((uint64_t)Ptr->Untyped[4] << 32) |
865 ((uint64_t)Ptr->Untyped[5] << 40) |
866 ((uint64_t)Ptr->Untyped[6] << 48) |
867 ((uint64_t)Ptr->Untyped[7] << 56);
870 cout << "Cannot load value of type " << I.getType() << "!\n";
873 switch (I.getType()->getPrimitiveID()) {
875 case Type::UByteTyID:
876 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
877 case Type::UShortTyID:
878 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
879 ((unsigned)Ptr->Untyped[0] << 8);
881 case Type::FloatTyID:
883 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
884 ((unsigned)Ptr->Untyped[2] << 8) |
885 ((unsigned)Ptr->Untyped[1] << 16) |
886 ((unsigned)Ptr->Untyped[0] << 24);
888 case Type::DoubleTyID:
889 case Type::ULongTyID:
891 case Type::PointerTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
892 ((uint64_t)Ptr->Untyped[6] << 8) |
893 ((uint64_t)Ptr->Untyped[5] << 16) |
894 ((uint64_t)Ptr->Untyped[4] << 24) |
895 ((uint64_t)Ptr->Untyped[3] << 32) |
896 ((uint64_t)Ptr->Untyped[2] << 40) |
897 ((uint64_t)Ptr->Untyped[1] << 48) |
898 ((uint64_t)Ptr->Untyped[0] << 56);
901 cout << "Cannot load value of type " << I.getType() << "!\n";
905 SetValue(&I, Result, SF);
908 static void StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
910 if (TD.isLittleEndian()) {
911 switch (Ty->getPrimitiveID()) {
913 case Type::UByteTyID:
914 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
915 case Type::UShortTyID:
916 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
917 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
919 case Type::FloatTyID:
921 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
922 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
923 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
924 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
926 case Type::DoubleTyID:
927 case Type::ULongTyID:
929 case Type::PointerTyID: Ptr->Untyped[0] = Val.ULongVal & 255;
930 Ptr->Untyped[1] = (Val.ULongVal >> 8) & 255;
931 Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
932 Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
933 Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
934 Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
935 Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
936 Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
939 cout << "Cannot store value of type " << Ty << "!\n";
942 switch (Ty->getPrimitiveID()) {
944 case Type::UByteTyID:
945 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
946 case Type::UShortTyID:
947 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
948 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
950 case Type::FloatTyID:
952 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
953 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
954 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
955 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
957 case Type::DoubleTyID:
958 case Type::ULongTyID:
960 case Type::PointerTyID: Ptr->Untyped[7] = Val.ULongVal & 255;
961 Ptr->Untyped[6] = (Val.ULongVal >> 8) & 255;
962 Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
963 Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
964 Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
965 Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
966 Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
967 Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
970 cout << "Cannot store value of type " << Ty << "!\n";
975 static void executeStoreInst(StoreInst &I, ExecutionContext &SF) {
976 GenericValue Val = getOperandValue(I.getOperand(0), SF);
977 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
978 StoreValueToMemory(Val, (GenericValue *)SRC.PointerVal,
979 I.getOperand(0)->getType());
983 GenericValue Interpreter::CreateArgv(const std::vector<std::string> &InputArgv){
984 // Pointers are 64 bits...
985 PointerTy *Result = new PointerTy[InputArgv.size()+1]; // 64 bit assumption
987 for (unsigned i = 0; i < InputArgv.size(); ++i) {
988 unsigned Size = InputArgv[i].size()+1;
989 char *Dest = new char[Size];
990 copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
993 GenericValue GV; GV.PointerVal = (PointerTy)Dest;
994 // Endian safe: Result[i] = (PointerTy)Dest;
995 StoreValueToMemory(GV, (GenericValue*)(Result+i),
996 Type::LongTy); // 64 bit assumption
999 Result[InputArgv.size()] = 0;
1000 GenericValue GV; GV.PointerVal = (PointerTy)Result;
1005 //===----------------------------------------------------------------------===//
1006 // Miscellaneous Instruction Implementations
1007 //===----------------------------------------------------------------------===//
1009 void Interpreter::executeCallInst(CallInst &I, ExecutionContext &SF) {
1010 ECStack.back().Caller = &I;
1011 vector<GenericValue> ArgVals;
1012 ArgVals.reserve(I.getNumOperands()-1);
1013 for (unsigned i = 1; i < I.getNumOperands(); ++i)
1014 ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
1016 // To handle indirect calls, we must get the pointer value from the argument
1017 // and treat it as a function pointer.
1018 GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
1020 callMethod((Function*)SRC.PointerVal, ArgVals);
1023 static void executePHINode(PHINode &I, ExecutionContext &SF) {
1024 BasicBlock *PrevBB = SF.PrevBB;
1025 Value *IncomingValue = 0;
1027 // Search for the value corresponding to this previous bb...
1028 for (unsigned i = I.getNumIncomingValues(); i > 0;) {
1029 if (I.getIncomingBlock(--i) == PrevBB) {
1030 IncomingValue = I.getIncomingValue(i);
1034 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
1036 // Found the value, set as the result...
1037 SetValue(&I, getOperandValue(IncomingValue, SF), SF);
1040 #define IMPLEMENT_SHIFT(OP, TY) \
1041 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
1043 static void executeShlInst(ShiftInst &I, ExecutionContext &SF) {
1044 const Type *Ty = I.getOperand(0)->getType();
1045 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1046 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1049 switch (Ty->getPrimitiveID()) {
1050 IMPLEMENT_SHIFT(<<, UByte);
1051 IMPLEMENT_SHIFT(<<, SByte);
1052 IMPLEMENT_SHIFT(<<, UShort);
1053 IMPLEMENT_SHIFT(<<, Short);
1054 IMPLEMENT_SHIFT(<<, UInt);
1055 IMPLEMENT_SHIFT(<<, Int);
1056 IMPLEMENT_SHIFT(<<, ULong);
1057 IMPLEMENT_SHIFT(<<, Long);
1058 IMPLEMENT_SHIFT(<<, Pointer);
1060 cout << "Unhandled type for Shl instruction: " << Ty << "\n";
1062 SetValue(&I, Dest, SF);
1065 static void executeShrInst(ShiftInst &I, ExecutionContext &SF) {
1066 const Type *Ty = I.getOperand(0)->getType();
1067 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1068 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1071 switch (Ty->getPrimitiveID()) {
1072 IMPLEMENT_SHIFT(>>, UByte);
1073 IMPLEMENT_SHIFT(>>, SByte);
1074 IMPLEMENT_SHIFT(>>, UShort);
1075 IMPLEMENT_SHIFT(>>, Short);
1076 IMPLEMENT_SHIFT(>>, UInt);
1077 IMPLEMENT_SHIFT(>>, Int);
1078 IMPLEMENT_SHIFT(>>, ULong);
1079 IMPLEMENT_SHIFT(>>, Long);
1080 IMPLEMENT_SHIFT(>>, Pointer);
1082 cout << "Unhandled type for Shr instruction: " << Ty << "\n";
1084 SetValue(&I, Dest, SF);
1087 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
1088 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
1090 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
1091 case Type::DESTTY##TyID: \
1092 switch (SrcTy->getPrimitiveID()) { \
1093 IMPLEMENT_CAST(DESTTY, DESTCTY, Bool); \
1094 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
1095 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
1096 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
1097 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
1098 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
1099 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
1100 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
1101 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
1102 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
1104 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
1105 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
1106 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
1108 #define IMPLEMENT_CAST_CASE_END() \
1109 default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
1114 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
1115 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
1116 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
1117 IMPLEMENT_CAST_CASE_END()
1119 static GenericValue executeCastOperation(Value *SrcVal, const Type *Ty,
1120 ExecutionContext &SF) {
1121 const Type *SrcTy = SrcVal->getType();
1122 GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1124 switch (Ty->getPrimitiveID()) {
1125 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
1126 IMPLEMENT_CAST_CASE(SByte , ( signed char));
1127 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1128 IMPLEMENT_CAST_CASE(Short , ( signed short));
1129 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
1130 IMPLEMENT_CAST_CASE(Int , ( signed int ));
1131 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
1132 IMPLEMENT_CAST_CASE(Long , ( int64_t));
1133 IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
1134 IMPLEMENT_CAST_CASE(Float , (float));
1135 IMPLEMENT_CAST_CASE(Double , (double));
1137 cout << "Unhandled dest type for cast instruction: " << Ty << "\n";
1144 static void executeCastInst(CastInst &I, ExecutionContext &SF) {
1145 SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
1149 //===----------------------------------------------------------------------===//
1150 // Dispatch and Execution Code
1151 //===----------------------------------------------------------------------===//
1153 MethodInfo::MethodInfo(Function *F) : Annotation(MethodInfoAID) {
1154 // Assign slot numbers to the function arguments...
1155 for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1156 AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
1158 // Iterate over all of the instructions...
1159 unsigned InstNum = 0;
1160 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
1161 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
1162 // For each instruction... Add Annote
1163 II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
1166 unsigned MethodInfo::getValueSlot(const Value *V) {
1167 unsigned Plane = V->getType()->getUniqueID();
1168 if (Plane >= NumPlaneElements.size())
1169 NumPlaneElements.resize(Plane+1, 0);
1170 return NumPlaneElements[Plane]++;
1174 //===----------------------------------------------------------------------===//
1175 // callMethod - Execute the specified function...
1177 void Interpreter::callMethod(Function *M, const vector<GenericValue> &ArgVals) {
1178 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
1179 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
1180 "Incorrect number of arguments passed into function call!");
1181 if (M->isExternal()) {
1182 GenericValue Result = callExternalMethod(M, ArgVals);
1183 const Type *RetTy = M->getReturnType();
1185 // Copy the result back into the result variable if we are not returning
1187 if (RetTy != Type::VoidTy) {
1188 if (!ECStack.empty() && ECStack.back().Caller) {
1189 ExecutionContext &SF = ECStack.back();
1190 SetValue(SF.Caller, Result, SF);
1192 SF.Caller = 0; // We returned from the call...
1193 } else if (!QuietMode) {
1195 CW << "Function " << M->getType() << " \"" << M->getName()
1197 print(RetTy, Result);
1200 if (RetTy->isIntegral())
1201 ExitCode = Result.IntVal; // Capture the exit code of the program
1208 // Process the function, assigning instruction numbers to the instructions in
1209 // the function. Also calculate the number of values for each type slot
1212 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
1213 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
1215 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
1216 StackFrame.CurMethod = M;
1217 StackFrame.CurBB = M->begin();
1218 StackFrame.CurInst = StackFrame.CurBB->begin();
1219 StackFrame.MethInfo = MethInfo;
1221 // Initialize the values to nothing...
1222 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
1223 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i) {
1224 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
1226 // Taint the initial values of stuff
1227 memset(&StackFrame.Values[i][0], 42,
1228 MethInfo->NumPlaneElements[i]*sizeof(GenericValue));
1231 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
1234 // Run through the function arguments and initialize their values...
1235 assert(ArgVals.size() == M->asize() &&
1236 "Invalid number of values passed to function invocation!");
1238 for (Function::aiterator AI = M->abegin(), E = M->aend(); AI != E; ++AI, ++i)
1239 SetValue(AI, ArgVals[i], StackFrame);
1242 // executeInstruction - Interpret a single instruction, increment the "PC", and
1243 // return true if the next instruction is a breakpoint...
1245 bool Interpreter::executeInstruction() {
1246 assert(!ECStack.empty() && "No program running, cannot execute inst!");
1248 ExecutionContext &SF = ECStack.back(); // Current stack frame
1249 Instruction &I = *SF.CurInst++; // Increment before execute
1254 // Set a sigsetjmp buffer so that we can recover if an error happens during
1255 // instruction execution...
1257 if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1258 --SF.CurInst; // Back up to erroring instruction
1259 if (SigNo != SIGINT) {
1260 cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]:\n";
1262 // If -abort-on-exception was specified, terminate LLI instead of trying
1265 if (AbortOnExceptions) exit(1);
1266 } else if (SigNo == SIGINT) {
1267 cout << "CTRL-C Detected, execution halted.\n";
1269 InInstruction = false;
1273 InInstruction = true;
1274 if (I.isBinaryOp()) {
1275 executeBinaryInst(cast<BinaryOperator>(I), SF);
1277 switch (I.getOpcode()) {
1279 case Instruction::Ret: executeRetInst (cast<ReturnInst>(I), SF); break;
1280 case Instruction::Br: executeBrInst (cast<BranchInst>(I), SF); break;
1281 // Memory Instructions
1282 case Instruction::Alloca:
1283 case Instruction::Malloc: executeAllocInst((AllocationInst&)I, SF); break;
1284 case Instruction::Free: executeFreeInst (cast<FreeInst> (I), SF); break;
1285 case Instruction::Load: executeLoadInst (cast<LoadInst> (I), SF); break;
1286 case Instruction::Store: executeStoreInst(cast<StoreInst>(I), SF); break;
1287 case Instruction::GetElementPtr:
1288 executeGEPInst(cast<GetElementPtrInst>(I), SF); break;
1290 // Miscellaneous Instructions
1291 case Instruction::Call: executeCallInst (cast<CallInst> (I), SF); break;
1292 case Instruction::PHINode: executePHINode (cast<PHINode> (I), SF); break;
1293 case Instruction::Shl: executeShlInst (cast<ShiftInst>(I), SF); break;
1294 case Instruction::Shr: executeShrInst (cast<ShiftInst>(I), SF); break;
1295 case Instruction::Cast: executeCastInst (cast<CastInst> (I), SF); break;
1297 cout << "Don't know how to execute this instruction!\n-->" << I;
1300 InInstruction = false;
1302 // Reset the current frame location to the top of stack
1303 CurFrame = ECStack.size()-1;
1305 if (CurFrame == -1) return false; // No breakpoint if no code
1307 // Return true if there is a breakpoint annotation on the instruction...
1308 return ECStack[CurFrame].CurInst->getAnnotation(BreakpointAID) != 0;
1311 void Interpreter::stepInstruction() { // Do the 'step' command
1312 if (ECStack.empty()) {
1313 cout << "Error: no program running, cannot step!\n";
1317 // Run an instruction...
1318 executeInstruction();
1320 // Print the next instruction to execute...
1321 printCurrentInstruction();
1325 void Interpreter::nextInstruction() { // Do the 'next' command
1326 if (ECStack.empty()) {
1327 cout << "Error: no program running, cannot 'next'!\n";
1331 // If this is a call instruction, step over the call instruction...
1332 // TODO: ICALL, CALL WITH, ...
1333 if (ECStack.back().CurInst->getOpcode() == Instruction::Call) {
1334 unsigned StackSize = ECStack.size();
1335 // Step into the function...
1336 if (executeInstruction()) {
1337 // Hit a breakpoint, print current instruction, then return to user...
1338 cout << "Breakpoint hit!\n";
1339 printCurrentInstruction();
1343 // If we we able to step into the function, finish it now. We might not be
1344 // able the step into a function, if it's external for example.
1345 if (ECStack.size() != StackSize)
1346 finish(); // Finish executing the function...
1348 printCurrentInstruction();
1351 // Normal instruction, just step...
1356 void Interpreter::run() {
1357 if (ECStack.empty()) {
1358 cout << "Error: no program running, cannot run!\n";
1362 bool HitBreakpoint = false;
1363 while (!ECStack.empty() && !HitBreakpoint) {
1364 // Run an instruction...
1365 HitBreakpoint = executeInstruction();
1368 if (HitBreakpoint) {
1369 cout << "Breakpoint hit!\n";
1371 // Print the next instruction to execute...
1372 printCurrentInstruction();
1375 void Interpreter::finish() {
1376 if (ECStack.empty()) {
1377 cout << "Error: no program running, cannot run!\n";
1381 unsigned StackSize = ECStack.size();
1382 bool HitBreakpoint = false;
1383 while (ECStack.size() >= StackSize && !HitBreakpoint) {
1384 // Run an instruction...
1385 HitBreakpoint = executeInstruction();
1388 if (HitBreakpoint) {
1389 cout << "Breakpoint hit!\n";
1392 // Print the next instruction to execute...
1393 printCurrentInstruction();
1398 // printCurrentInstruction - Print out the instruction that the virtual PC is
1399 // at, or fail silently if no program is running.
1401 void Interpreter::printCurrentInstruction() {
1402 if (!ECStack.empty()) {
1403 if (ECStack.back().CurBB->begin() == ECStack.back().CurInst) // print label
1404 WriteAsOperand(cout, ECStack.back().CurBB) << ":\n";
1406 Instruction &I = *ECStack.back().CurInst;
1407 InstNumber *IN = (InstNumber*)I.getAnnotation(SlotNumberAID);
1408 assert(IN && "Instruction has no numbering annotation!");
1409 cout << "#" << IN->InstNum << I;
1413 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1414 switch (Ty->getPrimitiveID()) {
1415 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
1416 case Type::SByteTyID:
1417 cout << (int)V.SByteVal << " '" << V.SByteVal << "'"; break;
1418 case Type::UByteTyID:
1419 cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'"; break;
1420 case Type::ShortTyID: cout << V.ShortVal; break;
1421 case Type::UShortTyID: cout << V.UShortVal; break;
1422 case Type::IntTyID: cout << V.IntVal; break;
1423 case Type::UIntTyID: cout << V.UIntVal; break;
1424 case Type::LongTyID: cout << (long)V.LongVal; break;
1425 case Type::ULongTyID: cout << (unsigned long)V.ULongVal; break;
1426 case Type::FloatTyID: cout << V.FloatVal; break;
1427 case Type::DoubleTyID: cout << V.DoubleVal; break;
1428 case Type::PointerTyID:cout << (void*)V.PointerVal; break;
1430 cout << "- Don't know how to print value of this type!";
1435 void Interpreter::print(const Type *Ty, GenericValue V) {
1440 void Interpreter::print(const std::string &Name) {
1441 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1442 if (!PickedVal) return;
1444 if (const Function *F = dyn_cast<const Function>(PickedVal)) {
1445 CW << F; // Print the function
1446 } else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
1447 CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
1448 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
1449 CW << BB; // Print the basic block
1450 } else { // Otherwise there should be an annotation for the slot#
1451 print(PickedVal->getType(),
1452 getOperandValue(PickedVal, ECStack[CurFrame]));
1457 void Interpreter::infoValue(const std::string &Name) {
1458 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1459 if (!PickedVal) return;
1462 print(PickedVal->getType(),
1463 getOperandValue(PickedVal, ECStack[CurFrame]));
1465 printOperandInfo(PickedVal, ECStack[CurFrame]);
1468 // printStackFrame - Print information about the specified stack frame, or -1
1469 // for the default one.
1471 void Interpreter::printStackFrame(int FrameNo) {
1472 if (FrameNo == -1) FrameNo = CurFrame;
1473 Function *F = ECStack[FrameNo].CurMethod;
1474 const Type *RetTy = F->getReturnType();
1476 CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1477 << (Value*)RetTy << " \"" << F->getName() << "\"(";
1480 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++i) {
1481 if (i != 0) cout << ", ";
1484 printValue(I->getType(), getOperandValue(I, ECStack[FrameNo]));
1489 if (FrameNo != int(ECStack.size()-1)) {
1490 BasicBlock::iterator I = ECStack[FrameNo].CurInst;
1493 CW << *ECStack[FrameNo].CurInst;