1 //===-- IRInterpreter.cpp ---------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Expression/IRInterpreter.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ModuleSpec.h"
13 #include "lldb/Core/Scalar.h"
14 #include "lldb/Core/ValueObject.h"
15 #include "lldb/Expression/DiagnosticManager.h"
16 #include "lldb/Expression/IRExecutionUnit.h"
17 #include "lldb/Expression/IRMemoryMap.h"
18 #include "lldb/Utility/ConstString.h"
19 #include "lldb/Utility/DataExtractor.h"
20 #include "lldb/Utility/Endian.h"
21 #include "lldb/Utility/Log.h"
22 #include "lldb/Utility/Status.h"
23 #include "lldb/Utility/StreamString.h"
25 #include "lldb/Target/ABI.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Target/ThreadPlan.h"
30 #include "lldb/Target/ThreadPlanCallFunctionUsingABI.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/Support/raw_ostream.h"
46 static std::string PrintValue(const Value *value, bool truncate = false) {
48 raw_string_ostream rso(s);
52 s.resize(s.length() - 1);
55 while ((offset = s.find('\n')) != s.npos)
57 while (s[0] == ' ' || s[0] == '\t')
63 static std::string PrintType(const Type *type, bool truncate = false) {
65 raw_string_ostream rso(s);
69 s.resize(s.length() - 1);
73 static bool CanIgnoreCall(const CallInst *call) {
74 const llvm::Function *called_function = call->getCalledFunction();
79 if (called_function->isIntrinsic()) {
80 switch (called_function->getIntrinsicID()) {
83 case llvm::Intrinsic::dbg_declare:
84 case llvm::Intrinsic::dbg_value:
92 class InterpreterStackFrame {
94 typedef std::map<const Value *, lldb::addr_t> ValueMap;
97 DataLayout &m_target_data;
98 lldb_private::IRExecutionUnit &m_execution_unit;
99 const BasicBlock *m_bb;
100 const BasicBlock *m_prev_bb;
101 BasicBlock::const_iterator m_ii;
102 BasicBlock::const_iterator m_ie;
104 lldb::addr_t m_frame_process_address;
106 lldb::addr_t m_stack_pointer;
108 lldb::ByteOrder m_byte_order;
109 size_t m_addr_byte_size;
111 InterpreterStackFrame(DataLayout &target_data,
112 lldb_private::IRExecutionUnit &execution_unit,
113 lldb::addr_t stack_frame_bottom,
114 lldb::addr_t stack_frame_top)
115 : m_target_data(target_data), m_execution_unit(execution_unit),
116 m_bb(nullptr), m_prev_bb(nullptr) {
117 m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle
118 : lldb::eByteOrderBig);
119 m_addr_byte_size = (target_data.getPointerSize(0));
121 m_frame_process_address = stack_frame_bottom;
122 m_frame_size = stack_frame_top - stack_frame_bottom;
123 m_stack_pointer = stack_frame_top;
126 ~InterpreterStackFrame() {}
128 void Jump(const BasicBlock *bb) {
131 m_ii = m_bb->begin();
135 std::string SummarizeValue(const Value *value) {
136 lldb_private::StreamString ss;
138 ss.Printf("%s", PrintValue(value).c_str());
140 ValueMap::iterator i = m_values.find(value);
142 if (i != m_values.end()) {
143 lldb::addr_t addr = i->second;
145 ss.Printf(" 0x%llx", (unsigned long long)addr);
148 return ss.GetString();
151 bool AssignToMatchType(lldb_private::Scalar &scalar, uint64_t u64value,
153 size_t type_size = m_target_data.getTypeStoreSize(type);
157 scalar = (uint8_t)u64value;
160 scalar = (uint16_t)u64value;
163 scalar = (uint32_t)u64value;
166 scalar = (uint64_t)u64value;
175 bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
177 const Constant *constant = dyn_cast<Constant>(value);
182 if (!ResolveConstantValue(value_apint, constant))
185 return AssignToMatchType(scalar, value_apint.getLimitedValue(),
188 lldb::addr_t process_address = ResolveValue(value, module);
189 size_t value_size = m_target_data.getTypeStoreSize(value->getType());
191 lldb_private::DataExtractor value_extractor;
192 lldb_private::Status extract_error;
194 m_execution_unit.GetMemoryData(value_extractor, process_address,
195 value_size, extract_error);
197 if (!extract_error.Success())
200 lldb::offset_t offset = 0;
201 if (value_size == 1 || value_size == 2 || value_size == 4 ||
203 uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
204 return AssignToMatchType(scalar, u64value, value->getType());
211 bool AssignValue(const Value *value, lldb_private::Scalar &scalar,
213 lldb::addr_t process_address = ResolveValue(value, module);
215 if (process_address == LLDB_INVALID_ADDRESS)
218 lldb_private::Scalar cast_scalar;
220 if (!AssignToMatchType(cast_scalar, scalar.ULongLong(), value->getType()))
223 size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
225 lldb_private::DataBufferHeap buf(value_byte_size, 0);
227 lldb_private::Status get_data_error;
229 if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
230 m_byte_order, get_data_error))
233 lldb_private::Status write_error;
235 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
236 buf.GetByteSize(), write_error);
238 return write_error.Success();
241 bool ResolveConstantValue(APInt &value, const Constant *constant) {
242 switch (constant->getValueID()) {
245 case Value::FunctionVal:
246 if (const Function *constant_func = dyn_cast<Function>(constant)) {
247 lldb_private::ConstString name(constant_func->getName());
248 lldb::addr_t addr = m_execution_unit.FindSymbol(name);
249 if (addr == LLDB_INVALID_ADDRESS)
251 value = APInt(m_target_data.getPointerSizeInBits(), addr);
255 case Value::ConstantIntVal:
256 if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
257 value = constant_int->getValue();
261 case Value::ConstantFPVal:
262 if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
263 value = constant_fp->getValueAPF().bitcastToAPInt();
267 case Value::ConstantExprVal:
268 if (const ConstantExpr *constant_expr =
269 dyn_cast<ConstantExpr>(constant)) {
270 switch (constant_expr->getOpcode()) {
273 case Instruction::IntToPtr:
274 case Instruction::PtrToInt:
275 case Instruction::BitCast:
276 return ResolveConstantValue(value, constant_expr->getOperand(0));
277 case Instruction::GetElementPtr: {
278 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
279 ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
281 Constant *base = dyn_cast<Constant>(*op_cursor);
286 if (!ResolveConstantValue(value, base))
291 if (op_cursor == op_end)
292 return true; // no offset to apply!
294 SmallVector<Value *, 8> indices(op_cursor, op_end);
297 cast<GEPOperator>(constant_expr)->getSourceElementType();
299 m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
301 const bool is_signed = true;
302 value += APInt(value.getBitWidth(), offset, is_signed);
309 case Value::ConstantPointerNullVal:
310 if (isa<ConstantPointerNull>(constant)) {
311 value = APInt(m_target_data.getPointerSizeInBits(), 0);
319 bool MakeArgument(const Argument *value, uint64_t address) {
320 lldb::addr_t data_address = Malloc(value->getType());
322 if (data_address == LLDB_INVALID_ADDRESS)
325 lldb_private::Status write_error;
327 m_execution_unit.WritePointerToMemory(data_address, address, write_error);
329 if (!write_error.Success()) {
330 lldb_private::Status free_error;
331 m_execution_unit.Free(data_address, free_error);
335 m_values[value] = data_address;
337 lldb_private::Log *log(
338 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
341 log->Printf("Made an allocation for argument %s",
342 PrintValue(value).c_str());
343 log->Printf(" Data region : %llx", (unsigned long long)address);
344 log->Printf(" Ref region : %llx", (unsigned long long)data_address);
350 bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
351 APInt resolved_value;
353 if (!ResolveConstantValue(resolved_value, constant))
356 size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
357 lldb_private::DataBufferHeap buf(constant_size, 0);
359 lldb_private::Status get_data_error;
361 lldb_private::Scalar resolved_scalar(
362 resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
363 if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
364 m_byte_order, get_data_error))
367 lldb_private::Status write_error;
369 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
370 buf.GetByteSize(), write_error);
372 return write_error.Success();
375 lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
376 lldb::addr_t ret = m_stack_pointer;
379 ret -= (ret % byte_alignment);
381 if (ret < m_frame_process_address)
382 return LLDB_INVALID_ADDRESS;
384 m_stack_pointer = ret;
388 lldb::addr_t Malloc(llvm::Type *type) {
389 lldb_private::Status alloc_error;
391 return Malloc(m_target_data.getTypeAllocSize(type),
392 m_target_data.getPrefTypeAlignment(type));
395 std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
396 size_t length = m_target_data.getTypeStoreSize(type);
398 lldb_private::DataBufferHeap buf(length, 0);
400 lldb_private::Status read_error;
402 m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
404 if (!read_error.Success())
405 return std::string("<couldn't read data>");
407 lldb_private::StreamString ss;
409 for (size_t i = 0; i < length; i++) {
410 if ((!(i & 0xf)) && i)
411 ss.Printf("%02hhx - ", buf.GetBytes()[i]);
413 ss.Printf("%02hhx ", buf.GetBytes()[i]);
416 return ss.GetString();
419 lldb::addr_t ResolveValue(const Value *value, Module &module) {
420 ValueMap::iterator i = m_values.find(value);
422 if (i != m_values.end())
425 // Fall back and allocate space [allocation type Alloca]
427 lldb::addr_t data_address = Malloc(value->getType());
429 if (const Constant *constant = dyn_cast<Constant>(value)) {
430 if (!ResolveConstant(data_address, constant)) {
431 lldb_private::Status free_error;
432 m_execution_unit.Free(data_address, free_error);
433 return LLDB_INVALID_ADDRESS;
437 m_values[value] = data_address;
442 static const char *unsupported_opcode_error =
443 "Interpreter doesn't handle one of the expression's opcodes";
444 static const char *unsupported_operand_error =
445 "Interpreter doesn't handle one of the expression's operands";
446 // static const char *interpreter_initialization_error = "Interpreter couldn't
448 static const char *interpreter_internal_error =
449 "Interpreter encountered an internal error";
450 static const char *bad_value_error =
451 "Interpreter couldn't resolve a value during execution";
452 static const char *memory_allocation_error =
453 "Interpreter couldn't allocate memory";
454 static const char *memory_write_error = "Interpreter couldn't write to memory";
455 static const char *memory_read_error = "Interpreter couldn't read from memory";
456 static const char *infinite_loop_error = "Interpreter ran for too many cycles";
457 // static const char *bad_result_error = "Result of expression
458 // is in bad memory";
459 static const char *too_many_functions_error =
460 "Interpreter doesn't handle modules with multiple function bodies.";
462 static bool CanResolveConstant(llvm::Constant *constant) {
463 switch (constant->getValueID()) {
466 case Value::ConstantIntVal:
467 case Value::ConstantFPVal:
468 case Value::FunctionVal:
470 case Value::ConstantExprVal:
471 if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
472 switch (constant_expr->getOpcode()) {
475 case Instruction::IntToPtr:
476 case Instruction::PtrToInt:
477 case Instruction::BitCast:
478 return CanResolveConstant(constant_expr->getOperand(0));
479 case Instruction::GetElementPtr: {
480 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
481 Constant *base = dyn_cast<Constant>(*op_cursor);
485 return CanResolveConstant(base);
491 case Value::ConstantPointerNullVal:
496 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
497 lldb_private::Status &error,
498 const bool support_function_calls) {
499 lldb_private::Log *log(
500 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
502 bool saw_function_with_body = false;
504 for (Module::iterator fi = module.begin(), fe = module.end(); fi != fe;
506 if (fi->begin() != fi->end()) {
507 if (saw_function_with_body) {
509 log->Printf("More than one function in the module has a body");
510 error.SetErrorToGenericError();
511 error.SetErrorString(too_many_functions_error);
514 saw_function_with_body = true;
518 for (Function::iterator bbi = function.begin(), bbe = function.end();
520 for (BasicBlock::iterator ii = bbi->begin(), ie = bbi->end(); ii != ie;
522 switch (ii->getOpcode()) {
525 log->Printf("Unsupported instruction: %s", PrintValue(&*ii).c_str());
526 error.SetErrorToGenericError();
527 error.SetErrorString(unsupported_opcode_error);
530 case Instruction::Add:
531 case Instruction::Alloca:
532 case Instruction::BitCast:
533 case Instruction::Br:
534 case Instruction::PHI:
536 case Instruction::Call: {
537 CallInst *call_inst = dyn_cast<CallInst>(ii);
540 error.SetErrorToGenericError();
541 error.SetErrorString(interpreter_internal_error);
545 if (!CanIgnoreCall(call_inst) && !support_function_calls) {
547 log->Printf("Unsupported instruction: %s",
548 PrintValue(&*ii).c_str());
549 error.SetErrorToGenericError();
550 error.SetErrorString(unsupported_opcode_error);
554 case Instruction::GetElementPtr:
556 case Instruction::ICmp: {
557 ICmpInst *icmp_inst = dyn_cast<ICmpInst>(ii);
560 error.SetErrorToGenericError();
561 error.SetErrorString(interpreter_internal_error);
565 switch (icmp_inst->getPredicate()) {
568 log->Printf("Unsupported ICmp predicate: %s",
569 PrintValue(&*ii).c_str());
571 error.SetErrorToGenericError();
572 error.SetErrorString(unsupported_opcode_error);
575 case CmpInst::ICMP_EQ:
576 case CmpInst::ICMP_NE:
577 case CmpInst::ICMP_UGT:
578 case CmpInst::ICMP_UGE:
579 case CmpInst::ICMP_ULT:
580 case CmpInst::ICMP_ULE:
581 case CmpInst::ICMP_SGT:
582 case CmpInst::ICMP_SGE:
583 case CmpInst::ICMP_SLT:
584 case CmpInst::ICMP_SLE:
588 case Instruction::And:
589 case Instruction::AShr:
590 case Instruction::IntToPtr:
591 case Instruction::PtrToInt:
592 case Instruction::Load:
593 case Instruction::LShr:
594 case Instruction::Mul:
595 case Instruction::Or:
596 case Instruction::Ret:
597 case Instruction::SDiv:
598 case Instruction::SExt:
599 case Instruction::Shl:
600 case Instruction::SRem:
601 case Instruction::Store:
602 case Instruction::Sub:
603 case Instruction::Trunc:
604 case Instruction::UDiv:
605 case Instruction::URem:
606 case Instruction::Xor:
607 case Instruction::ZExt:
611 for (int oi = 0, oe = ii->getNumOperands(); oi != oe; ++oi) {
612 Value *operand = ii->getOperand(oi);
613 Type *operand_type = operand->getType();
615 switch (operand_type->getTypeID()) {
618 case Type::VectorTyID: {
620 log->Printf("Unsupported operand type: %s",
621 PrintType(operand_type).c_str());
622 error.SetErrorString(unsupported_operand_error);
627 if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
628 if (!CanResolveConstant(constant)) {
630 log->Printf("Unsupported constant: %s",
631 PrintValue(constant).c_str());
632 error.SetErrorString(unsupported_operand_error);
643 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
644 llvm::ArrayRef<lldb::addr_t> args,
645 lldb_private::IRExecutionUnit &execution_unit,
646 lldb_private::Status &error,
647 lldb::addr_t stack_frame_bottom,
648 lldb::addr_t stack_frame_top,
649 lldb_private::ExecutionContext &exe_ctx) {
650 lldb_private::Log *log(
651 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
655 raw_string_ostream oss(s);
657 module.print(oss, NULL);
661 log->Printf("Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
665 DataLayout data_layout(&module);
667 InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
670 if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
671 error.SetErrorString("Couldn't allocate stack frame");
676 for (llvm::Function::arg_iterator ai = function.arg_begin(),
677 ae = function.arg_end();
678 ai != ae; ++ai, ++arg_index) {
679 if (args.size() <= static_cast<size_t>(arg_index)) {
680 error.SetErrorString("Not enough arguments passed in to function");
684 lldb::addr_t ptr = args[arg_index];
686 frame.MakeArgument(&*ai, ptr);
689 uint32_t num_insts = 0;
691 frame.Jump(&function.front());
693 while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
694 const Instruction *inst = &*frame.m_ii;
697 log->Printf("Interpreting %s", PrintValue(inst).c_str());
699 switch (inst->getOpcode()) {
703 case Instruction::Add:
704 case Instruction::Sub:
705 case Instruction::Mul:
706 case Instruction::SDiv:
707 case Instruction::UDiv:
708 case Instruction::SRem:
709 case Instruction::URem:
710 case Instruction::Shl:
711 case Instruction::LShr:
712 case Instruction::AShr:
713 case Instruction::And:
714 case Instruction::Or:
715 case Instruction::Xor: {
716 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
721 "getOpcode() returns %s, but instruction is not a BinaryOperator",
722 inst->getOpcodeName());
723 error.SetErrorToGenericError();
724 error.SetErrorString(interpreter_internal_error);
728 Value *lhs = inst->getOperand(0);
729 Value *rhs = inst->getOperand(1);
731 lldb_private::Scalar L;
732 lldb_private::Scalar R;
734 if (!frame.EvaluateValue(L, lhs, module)) {
736 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
737 error.SetErrorToGenericError();
738 error.SetErrorString(bad_value_error);
742 if (!frame.EvaluateValue(R, rhs, module)) {
744 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
745 error.SetErrorToGenericError();
746 error.SetErrorString(bad_value_error);
750 lldb_private::Scalar result;
752 switch (inst->getOpcode()) {
755 case Instruction::Add:
758 case Instruction::Mul:
761 case Instruction::Sub:
764 case Instruction::SDiv:
769 case Instruction::UDiv:
774 case Instruction::SRem:
779 case Instruction::URem:
784 case Instruction::Shl:
787 case Instruction::AShr:
790 case Instruction::LShr:
792 result.ShiftRightLogical(R);
794 case Instruction::And:
797 case Instruction::Or:
800 case Instruction::Xor:
805 frame.AssignValue(inst, result, module);
808 log->Printf("Interpreted a %s", inst->getOpcodeName());
809 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
810 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
811 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
814 case Instruction::Alloca: {
815 const AllocaInst *alloca_inst = dyn_cast<AllocaInst>(inst);
819 log->Printf("getOpcode() returns Alloca, but instruction is not an "
821 error.SetErrorToGenericError();
822 error.SetErrorString(interpreter_internal_error);
826 if (alloca_inst->isArrayAllocation()) {
829 "AllocaInsts are not handled if isArrayAllocation() is true");
830 error.SetErrorToGenericError();
831 error.SetErrorString(unsupported_opcode_error);
835 // The semantics of Alloca are:
836 // Create a region R of virtual memory of type T, backed by a data
838 // Create a region P of virtual memory of type T*, backed by a data
840 // Write the virtual address of R into P
842 Type *T = alloca_inst->getAllocatedType();
843 Type *Tptr = alloca_inst->getType();
845 lldb::addr_t R = frame.Malloc(T);
847 if (R == LLDB_INVALID_ADDRESS) {
849 log->Printf("Couldn't allocate memory for an AllocaInst");
850 error.SetErrorToGenericError();
851 error.SetErrorString(memory_allocation_error);
855 lldb::addr_t P = frame.Malloc(Tptr);
857 if (P == LLDB_INVALID_ADDRESS) {
859 log->Printf("Couldn't allocate the result pointer for an AllocaInst");
860 error.SetErrorToGenericError();
861 error.SetErrorString(memory_allocation_error);
865 lldb_private::Status write_error;
867 execution_unit.WritePointerToMemory(P, R, write_error);
869 if (!write_error.Success()) {
871 log->Printf("Couldn't write the result pointer for an AllocaInst");
872 error.SetErrorToGenericError();
873 error.SetErrorString(memory_write_error);
874 lldb_private::Status free_error;
875 execution_unit.Free(P, free_error);
876 execution_unit.Free(R, free_error);
880 frame.m_values[alloca_inst] = P;
883 log->Printf("Interpreted an AllocaInst");
884 log->Printf(" R : 0x%" PRIx64, R);
885 log->Printf(" P : 0x%" PRIx64, P);
888 case Instruction::BitCast:
889 case Instruction::ZExt: {
890 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
895 "getOpcode() returns %s, but instruction is not a BitCastInst",
896 cast_inst->getOpcodeName());
897 error.SetErrorToGenericError();
898 error.SetErrorString(interpreter_internal_error);
902 Value *source = cast_inst->getOperand(0);
904 lldb_private::Scalar S;
906 if (!frame.EvaluateValue(S, source, module)) {
908 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
909 error.SetErrorToGenericError();
910 error.SetErrorString(bad_value_error);
914 frame.AssignValue(inst, S, module);
916 case Instruction::SExt: {
917 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
922 "getOpcode() returns %s, but instruction is not a BitCastInst",
923 cast_inst->getOpcodeName());
924 error.SetErrorToGenericError();
925 error.SetErrorString(interpreter_internal_error);
929 Value *source = cast_inst->getOperand(0);
931 lldb_private::Scalar S;
933 if (!frame.EvaluateValue(S, source, module)) {
935 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
936 error.SetErrorToGenericError();
937 error.SetErrorString(bad_value_error);
943 lldb_private::Scalar S_signextend(S.SLongLong());
945 frame.AssignValue(inst, S_signextend, module);
947 case Instruction::Br: {
948 const BranchInst *br_inst = dyn_cast<BranchInst>(inst);
953 "getOpcode() returns Br, but instruction is not a BranchInst");
954 error.SetErrorToGenericError();
955 error.SetErrorString(interpreter_internal_error);
959 if (br_inst->isConditional()) {
960 Value *condition = br_inst->getCondition();
962 lldb_private::Scalar C;
964 if (!frame.EvaluateValue(C, condition, module)) {
966 log->Printf("Couldn't evaluate %s", PrintValue(condition).c_str());
967 error.SetErrorToGenericError();
968 error.SetErrorString(bad_value_error);
973 frame.Jump(br_inst->getSuccessor(0));
975 frame.Jump(br_inst->getSuccessor(1));
978 log->Printf("Interpreted a BrInst with a condition");
979 log->Printf(" cond : %s", frame.SummarizeValue(condition).c_str());
982 frame.Jump(br_inst->getSuccessor(0));
985 log->Printf("Interpreted a BrInst with no condition");
990 case Instruction::PHI: {
991 const PHINode *phi_inst = dyn_cast<PHINode>(inst);
996 "getOpcode() returns PHI, but instruction is not a PHINode");
997 error.SetErrorToGenericError();
998 error.SetErrorString(interpreter_internal_error);
1001 if (!frame.m_prev_bb) {
1003 log->Printf("Encountered PHI node without having jumped from another "
1005 error.SetErrorToGenericError();
1006 error.SetErrorString(interpreter_internal_error);
1010 Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
1011 lldb_private::Scalar result;
1012 if (!frame.EvaluateValue(result, value, module)) {
1014 log->Printf("Couldn't evaluate %s", PrintValue(value).c_str());
1015 error.SetErrorToGenericError();
1016 error.SetErrorString(bad_value_error);
1019 frame.AssignValue(inst, result, module);
1022 log->Printf("Interpreted a %s", inst->getOpcodeName());
1023 log->Printf(" Incoming value : %s",
1024 frame.SummarizeValue(value).c_str());
1027 case Instruction::GetElementPtr: {
1028 const GetElementPtrInst *gep_inst = dyn_cast<GetElementPtrInst>(inst);
1032 log->Printf("getOpcode() returns GetElementPtr, but instruction is "
1033 "not a GetElementPtrInst");
1034 error.SetErrorToGenericError();
1035 error.SetErrorString(interpreter_internal_error);
1039 const Value *pointer_operand = gep_inst->getPointerOperand();
1040 Type *src_elem_ty = gep_inst->getSourceElementType();
1042 lldb_private::Scalar P;
1044 if (!frame.EvaluateValue(P, pointer_operand, module)) {
1046 log->Printf("Couldn't evaluate %s",
1047 PrintValue(pointer_operand).c_str());
1048 error.SetErrorToGenericError();
1049 error.SetErrorString(bad_value_error);
1053 typedef SmallVector<Value *, 8> IndexVector;
1054 typedef IndexVector::iterator IndexIterator;
1056 SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
1057 gep_inst->idx_end());
1059 SmallVector<Value *, 8> const_indices;
1061 for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
1063 ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1065 if (!constant_index) {
1066 lldb_private::Scalar I;
1068 if (!frame.EvaluateValue(I, *ii, module)) {
1070 log->Printf("Couldn't evaluate %s", PrintValue(*ii).c_str());
1071 error.SetErrorToGenericError();
1072 error.SetErrorString(bad_value_error);
1077 log->Printf("Evaluated constant index %s as %llu",
1078 PrintValue(*ii).c_str(),
1079 I.ULongLong(LLDB_INVALID_ADDRESS));
1081 constant_index = cast<ConstantInt>(ConstantInt::get(
1082 (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1085 const_indices.push_back(constant_index);
1089 data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1091 lldb_private::Scalar Poffset = P + offset;
1093 frame.AssignValue(inst, Poffset, module);
1096 log->Printf("Interpreted a GetElementPtrInst");
1097 log->Printf(" P : %s",
1098 frame.SummarizeValue(pointer_operand).c_str());
1099 log->Printf(" Poffset : %s", frame.SummarizeValue(inst).c_str());
1102 case Instruction::ICmp: {
1103 const ICmpInst *icmp_inst = dyn_cast<ICmpInst>(inst);
1108 "getOpcode() returns ICmp, but instruction is not an ICmpInst");
1109 error.SetErrorToGenericError();
1110 error.SetErrorString(interpreter_internal_error);
1114 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1116 Value *lhs = inst->getOperand(0);
1117 Value *rhs = inst->getOperand(1);
1119 lldb_private::Scalar L;
1120 lldb_private::Scalar R;
1122 if (!frame.EvaluateValue(L, lhs, module)) {
1124 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1125 error.SetErrorToGenericError();
1126 error.SetErrorString(bad_value_error);
1130 if (!frame.EvaluateValue(R, rhs, module)) {
1132 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1133 error.SetErrorToGenericError();
1134 error.SetErrorString(bad_value_error);
1138 lldb_private::Scalar result;
1140 switch (predicate) {
1143 case CmpInst::ICMP_EQ:
1146 case CmpInst::ICMP_NE:
1149 case CmpInst::ICMP_UGT:
1154 case CmpInst::ICMP_UGE:
1159 case CmpInst::ICMP_ULT:
1164 case CmpInst::ICMP_ULE:
1169 case CmpInst::ICMP_SGT:
1174 case CmpInst::ICMP_SGE:
1179 case CmpInst::ICMP_SLT:
1184 case CmpInst::ICMP_SLE:
1191 frame.AssignValue(inst, result, module);
1194 log->Printf("Interpreted an ICmpInst");
1195 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
1196 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
1197 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1200 case Instruction::IntToPtr: {
1201 const IntToPtrInst *int_to_ptr_inst = dyn_cast<IntToPtrInst>(inst);
1203 if (!int_to_ptr_inst) {
1205 log->Printf("getOpcode() returns IntToPtr, but instruction is not an "
1207 error.SetErrorToGenericError();
1208 error.SetErrorString(interpreter_internal_error);
1212 Value *src_operand = int_to_ptr_inst->getOperand(0);
1214 lldb_private::Scalar I;
1216 if (!frame.EvaluateValue(I, src_operand, module)) {
1218 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1219 error.SetErrorToGenericError();
1220 error.SetErrorString(bad_value_error);
1224 frame.AssignValue(inst, I, module);
1227 log->Printf("Interpreted an IntToPtr");
1228 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1229 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1232 case Instruction::PtrToInt: {
1233 const PtrToIntInst *ptr_to_int_inst = dyn_cast<PtrToIntInst>(inst);
1235 if (!ptr_to_int_inst) {
1237 log->Printf("getOpcode() returns PtrToInt, but instruction is not an "
1239 error.SetErrorToGenericError();
1240 error.SetErrorString(interpreter_internal_error);
1244 Value *src_operand = ptr_to_int_inst->getOperand(0);
1246 lldb_private::Scalar I;
1248 if (!frame.EvaluateValue(I, src_operand, module)) {
1250 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1251 error.SetErrorToGenericError();
1252 error.SetErrorString(bad_value_error);
1256 frame.AssignValue(inst, I, module);
1259 log->Printf("Interpreted a PtrToInt");
1260 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1261 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1264 case Instruction::Trunc: {
1265 const TruncInst *trunc_inst = dyn_cast<TruncInst>(inst);
1270 "getOpcode() returns Trunc, but instruction is not a TruncInst");
1271 error.SetErrorToGenericError();
1272 error.SetErrorString(interpreter_internal_error);
1276 Value *src_operand = trunc_inst->getOperand(0);
1278 lldb_private::Scalar I;
1280 if (!frame.EvaluateValue(I, src_operand, module)) {
1282 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1283 error.SetErrorToGenericError();
1284 error.SetErrorString(bad_value_error);
1288 frame.AssignValue(inst, I, module);
1291 log->Printf("Interpreted a Trunc");
1292 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1293 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1296 case Instruction::Load: {
1297 const LoadInst *load_inst = dyn_cast<LoadInst>(inst);
1302 "getOpcode() returns Load, but instruction is not a LoadInst");
1303 error.SetErrorToGenericError();
1304 error.SetErrorString(interpreter_internal_error);
1308 // The semantics of Load are:
1309 // Create a region D that will contain the loaded data
1310 // Resolve the region P containing a pointer
1311 // Dereference P to get the region R that the data should be loaded from
1312 // Transfer a unit of type type(D) from R to D
1314 const Value *pointer_operand = load_inst->getPointerOperand();
1316 Type *pointer_ty = pointer_operand->getType();
1317 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1318 if (!pointer_ptr_ty) {
1320 log->Printf("getPointerOperand()->getType() is not a PointerType");
1321 error.SetErrorToGenericError();
1322 error.SetErrorString(interpreter_internal_error);
1325 Type *target_ty = pointer_ptr_ty->getElementType();
1327 lldb::addr_t D = frame.ResolveValue(load_inst, module);
1328 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1330 if (D == LLDB_INVALID_ADDRESS) {
1332 log->Printf("LoadInst's value doesn't resolve to anything");
1333 error.SetErrorToGenericError();
1334 error.SetErrorString(bad_value_error);
1338 if (P == LLDB_INVALID_ADDRESS) {
1340 log->Printf("LoadInst's pointer doesn't resolve to anything");
1341 error.SetErrorToGenericError();
1342 error.SetErrorString(bad_value_error);
1347 lldb_private::Status read_error;
1348 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1350 if (!read_error.Success()) {
1352 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1353 error.SetErrorToGenericError();
1354 error.SetErrorString(memory_read_error);
1358 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1359 lldb_private::DataBufferHeap buffer(target_size, 0);
1362 execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1364 if (!read_error.Success()) {
1366 log->Printf("Couldn't read from a region on behalf of a LoadInst");
1367 error.SetErrorToGenericError();
1368 error.SetErrorString(memory_read_error);
1372 lldb_private::Status write_error;
1373 execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1375 if (!write_error.Success()) {
1377 log->Printf("Couldn't write to a region on behalf of a LoadInst");
1378 error.SetErrorToGenericError();
1379 error.SetErrorString(memory_read_error);
1384 log->Printf("Interpreted a LoadInst");
1385 log->Printf(" P : 0x%" PRIx64, P);
1386 log->Printf(" R : 0x%" PRIx64, R);
1387 log->Printf(" D : 0x%" PRIx64, D);
1390 case Instruction::Ret: {
1393 case Instruction::Store: {
1394 const StoreInst *store_inst = dyn_cast<StoreInst>(inst);
1399 "getOpcode() returns Store, but instruction is not a StoreInst");
1400 error.SetErrorToGenericError();
1401 error.SetErrorString(interpreter_internal_error);
1405 // The semantics of Store are:
1406 // Resolve the region D containing the data to be stored
1407 // Resolve the region P containing a pointer
1408 // Dereference P to get the region R that the data should be stored in
1409 // Transfer a unit of type type(D) from D to R
1411 const Value *value_operand = store_inst->getValueOperand();
1412 const Value *pointer_operand = store_inst->getPointerOperand();
1414 Type *pointer_ty = pointer_operand->getType();
1415 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1416 if (!pointer_ptr_ty)
1418 Type *target_ty = pointer_ptr_ty->getElementType();
1420 lldb::addr_t D = frame.ResolveValue(value_operand, module);
1421 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1423 if (D == LLDB_INVALID_ADDRESS) {
1425 log->Printf("StoreInst's value doesn't resolve to anything");
1426 error.SetErrorToGenericError();
1427 error.SetErrorString(bad_value_error);
1431 if (P == LLDB_INVALID_ADDRESS) {
1433 log->Printf("StoreInst's pointer doesn't resolve to anything");
1434 error.SetErrorToGenericError();
1435 error.SetErrorString(bad_value_error);
1440 lldb_private::Status read_error;
1441 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1443 if (!read_error.Success()) {
1445 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1446 error.SetErrorToGenericError();
1447 error.SetErrorString(memory_read_error);
1451 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1452 lldb_private::DataBufferHeap buffer(target_size, 0);
1455 execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1457 if (!read_error.Success()) {
1459 log->Printf("Couldn't read from a region on behalf of a StoreInst");
1460 error.SetErrorToGenericError();
1461 error.SetErrorString(memory_read_error);
1465 lldb_private::Status write_error;
1466 execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1468 if (!write_error.Success()) {
1470 log->Printf("Couldn't write to a region on behalf of a StoreInst");
1471 error.SetErrorToGenericError();
1472 error.SetErrorString(memory_write_error);
1477 log->Printf("Interpreted a StoreInst");
1478 log->Printf(" D : 0x%" PRIx64, D);
1479 log->Printf(" P : 0x%" PRIx64, P);
1480 log->Printf(" R : 0x%" PRIx64, R);
1483 case Instruction::Call: {
1484 const CallInst *call_inst = dyn_cast<CallInst>(inst);
1489 "getOpcode() returns %s, but instruction is not a CallInst",
1490 inst->getOpcodeName());
1491 error.SetErrorToGenericError();
1492 error.SetErrorString(interpreter_internal_error);
1496 if (CanIgnoreCall(call_inst))
1499 // Get the return type
1500 llvm::Type *returnType = call_inst->getType();
1501 if (returnType == nullptr) {
1502 error.SetErrorToGenericError();
1503 error.SetErrorString("unable to access return type");
1507 // Work with void, integer and pointer return types
1508 if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1509 !returnType->isPointerTy()) {
1510 error.SetErrorToGenericError();
1511 error.SetErrorString("return type is not supported");
1515 // Check we can actually get a thread
1516 if (exe_ctx.GetThreadPtr() == nullptr) {
1517 error.SetErrorToGenericError();
1518 error.SetErrorStringWithFormat("unable to acquire thread");
1522 // Make sure we have a valid process
1523 if (!exe_ctx.GetProcessPtr()) {
1524 error.SetErrorToGenericError();
1525 error.SetErrorStringWithFormat("unable to get the process");
1529 // Find the address of the callee function
1530 lldb_private::Scalar I;
1531 const llvm::Value *val = call_inst->getCalledValue();
1533 if (!frame.EvaluateValue(I, val, module)) {
1534 error.SetErrorToGenericError();
1535 error.SetErrorString("unable to get address of function");
1538 lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1540 lldb_private::DiagnosticManager diagnostics;
1541 lldb_private::EvaluateExpressionOptions options;
1543 // We generally receive a function pointer which we must dereference
1544 llvm::Type *prototype = val->getType();
1545 if (!prototype->isPointerTy()) {
1546 error.SetErrorToGenericError();
1547 error.SetErrorString("call need function pointer");
1551 // Dereference the function pointer
1552 prototype = prototype->getPointerElementType();
1553 if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1554 error.SetErrorToGenericError();
1555 error.SetErrorString("call need function pointer");
1559 // Find number of arguments
1560 const int numArgs = call_inst->getNumArgOperands();
1562 // We work with a fixed array of 16 arguments which is our upper limit
1563 static lldb_private::ABI::CallArgument rawArgs[16];
1564 if (numArgs >= 16) {
1565 error.SetErrorToGenericError();
1566 error.SetErrorStringWithFormat("function takes too many arguments");
1570 // Push all function arguments to the argument list that will
1571 // be passed to the call function thread plan
1572 for (int i = 0; i < numArgs; i++) {
1573 // Get details of this argument
1574 llvm::Value *arg_op = call_inst->getArgOperand(i);
1575 llvm::Type *arg_ty = arg_op->getType();
1577 // Ensure that this argument is an supported type
1578 if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1579 error.SetErrorToGenericError();
1580 error.SetErrorStringWithFormat("argument %d must be integer type", i);
1584 // Extract the arguments value
1585 lldb_private::Scalar tmp_op = 0;
1586 if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1587 error.SetErrorToGenericError();
1588 error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1592 // Check if this is a string literal or constant string pointer
1593 if (arg_ty->isPointerTy()) {
1594 // Pointer to just one type
1595 assert(arg_ty->getNumContainedTypes() == 1);
1597 lldb::addr_t addr = tmp_op.ULongLong();
1598 size_t dataSize = 0;
1600 bool Success = execution_unit.GetAllocSize(addr, dataSize);
1603 "unable to locate host data for transfer to device");
1604 // Create the required buffer
1605 rawArgs[i].size = dataSize;
1606 rawArgs[i].data_ap.reset(new uint8_t[dataSize + 1]);
1608 // Read string from host memory
1609 execution_unit.ReadMemory(rawArgs[i].data_ap.get(), addr, dataSize,
1611 assert(!error.Fail() &&
1612 "we have failed to read the string from memory");
1614 // Add null terminator
1615 rawArgs[i].data_ap[dataSize] = '\0';
1616 rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
1617 } else /* if ( arg_ty->isPointerTy() ) */
1619 rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1620 // Get argument size in bytes
1621 rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1622 // Push value into argument list for thread plan
1623 rawArgs[i].value = tmp_op.ULongLong();
1627 // Pack the arguments into an llvm::array
1628 llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1630 // Setup a thread plan to call the target function
1631 lldb::ThreadPlanSP call_plan_sp(
1632 new lldb_private::ThreadPlanCallFunctionUsingABI(
1633 exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1636 // Check if the plan is valid
1637 lldb_private::StreamString ss;
1638 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1639 error.SetErrorToGenericError();
1640 error.SetErrorStringWithFormat(
1641 "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1646 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1648 // Execute the actual function call thread plan
1649 lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1650 exe_ctx, call_plan_sp, options, diagnostics);
1652 // Check that the thread plan completed successfully
1653 if (res != lldb::ExpressionResults::eExpressionCompleted) {
1654 error.SetErrorToGenericError();
1655 error.SetErrorStringWithFormat("ThreadPlanCallFunctionUsingABI failed");
1659 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1662 if (returnType->isVoidTy()) {
1663 // Cant assign to void types, so we leave the frame untouched
1665 // Integer or pointer return type
1666 if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1667 // Get the encapsulated return value
1668 lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1670 lldb_private::Scalar returnVal = -1;
1671 lldb_private::ValueObject *vobj = retVal.get();
1673 // Check if the return value is valid
1674 if (vobj == nullptr || retVal.empty()) {
1675 error.SetErrorToGenericError();
1676 error.SetErrorStringWithFormat("unable to get the return value");
1680 // Extract the return value as a integer
1681 lldb_private::Value &value = vobj->GetValue();
1682 returnVal = value.GetScalar();
1684 // Push the return value as the result
1685 frame.AssignValue(inst, returnVal, module);
1693 if (num_insts >= 4096) {
1694 error.SetErrorToGenericError();
1695 error.SetErrorString(infinite_loop_error);