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/ValueObject.h"
14 #include "lldb/Expression/DiagnosticManager.h"
15 #include "lldb/Expression/IRExecutionUnit.h"
16 #include "lldb/Expression/IRMemoryMap.h"
17 #include "lldb/Utility/ConstString.h"
18 #include "lldb/Utility/DataExtractor.h"
19 #include "lldb/Utility/Endian.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/Scalar.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);
159 type_size = PowerOf2Ceil(type_size);
161 scalar = llvm::APInt(type_size*8, u64value);
165 bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
167 const Constant *constant = dyn_cast<Constant>(value);
172 if (!ResolveConstantValue(value_apint, constant))
175 return AssignToMatchType(scalar, value_apint.getLimitedValue(),
178 lldb::addr_t process_address = ResolveValue(value, module);
179 size_t value_size = m_target_data.getTypeStoreSize(value->getType());
181 lldb_private::DataExtractor value_extractor;
182 lldb_private::Status extract_error;
184 m_execution_unit.GetMemoryData(value_extractor, process_address,
185 value_size, extract_error);
187 if (!extract_error.Success())
190 lldb::offset_t offset = 0;
191 if (value_size <= 8) {
192 uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
193 return AssignToMatchType(scalar, u64value, value->getType());
200 bool AssignValue(const Value *value, lldb_private::Scalar &scalar,
202 lldb::addr_t process_address = ResolveValue(value, module);
204 if (process_address == LLDB_INVALID_ADDRESS)
207 lldb_private::Scalar cast_scalar;
209 if (!AssignToMatchType(cast_scalar, scalar.ULongLong(), value->getType()))
212 size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
214 lldb_private::DataBufferHeap buf(value_byte_size, 0);
216 lldb_private::Status get_data_error;
218 if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
219 m_byte_order, get_data_error))
222 lldb_private::Status write_error;
224 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
225 buf.GetByteSize(), write_error);
227 return write_error.Success();
230 bool ResolveConstantValue(APInt &value, const Constant *constant) {
231 switch (constant->getValueID()) {
234 case Value::FunctionVal:
235 if (const Function *constant_func = dyn_cast<Function>(constant)) {
236 lldb_private::ConstString name(constant_func->getName());
237 lldb::addr_t addr = m_execution_unit.FindSymbol(name);
238 if (addr == LLDB_INVALID_ADDRESS)
240 value = APInt(m_target_data.getPointerSizeInBits(), addr);
244 case Value::ConstantIntVal:
245 if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
246 value = constant_int->getValue();
250 case Value::ConstantFPVal:
251 if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
252 value = constant_fp->getValueAPF().bitcastToAPInt();
256 case Value::ConstantExprVal:
257 if (const ConstantExpr *constant_expr =
258 dyn_cast<ConstantExpr>(constant)) {
259 switch (constant_expr->getOpcode()) {
262 case Instruction::IntToPtr:
263 case Instruction::PtrToInt:
264 case Instruction::BitCast:
265 return ResolveConstantValue(value, constant_expr->getOperand(0));
266 case Instruction::GetElementPtr: {
267 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
268 ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
270 Constant *base = dyn_cast<Constant>(*op_cursor);
275 if (!ResolveConstantValue(value, base))
280 if (op_cursor == op_end)
281 return true; // no offset to apply!
283 SmallVector<Value *, 8> indices(op_cursor, op_end);
286 cast<GEPOperator>(constant_expr)->getSourceElementType();
288 m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
290 const bool is_signed = true;
291 value += APInt(value.getBitWidth(), offset, is_signed);
298 case Value::ConstantPointerNullVal:
299 if (isa<ConstantPointerNull>(constant)) {
300 value = APInt(m_target_data.getPointerSizeInBits(), 0);
308 bool MakeArgument(const Argument *value, uint64_t address) {
309 lldb::addr_t data_address = Malloc(value->getType());
311 if (data_address == LLDB_INVALID_ADDRESS)
314 lldb_private::Status write_error;
316 m_execution_unit.WritePointerToMemory(data_address, address, write_error);
318 if (!write_error.Success()) {
319 lldb_private::Status free_error;
320 m_execution_unit.Free(data_address, free_error);
324 m_values[value] = data_address;
326 lldb_private::Log *log(
327 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
330 log->Printf("Made an allocation for argument %s",
331 PrintValue(value).c_str());
332 log->Printf(" Data region : %llx", (unsigned long long)address);
333 log->Printf(" Ref region : %llx", (unsigned long long)data_address);
339 bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
340 APInt resolved_value;
342 if (!ResolveConstantValue(resolved_value, constant))
345 size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
346 lldb_private::DataBufferHeap buf(constant_size, 0);
348 lldb_private::Status get_data_error;
350 lldb_private::Scalar resolved_scalar(
351 resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
352 if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
353 m_byte_order, get_data_error))
356 lldb_private::Status write_error;
358 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
359 buf.GetByteSize(), write_error);
361 return write_error.Success();
364 lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
365 lldb::addr_t ret = m_stack_pointer;
368 ret -= (ret % byte_alignment);
370 if (ret < m_frame_process_address)
371 return LLDB_INVALID_ADDRESS;
373 m_stack_pointer = ret;
377 lldb::addr_t Malloc(llvm::Type *type) {
378 lldb_private::Status alloc_error;
380 return Malloc(m_target_data.getTypeAllocSize(type),
381 m_target_data.getPrefTypeAlignment(type));
384 std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
385 size_t length = m_target_data.getTypeStoreSize(type);
387 lldb_private::DataBufferHeap buf(length, 0);
389 lldb_private::Status read_error;
391 m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
393 if (!read_error.Success())
394 return std::string("<couldn't read data>");
396 lldb_private::StreamString ss;
398 for (size_t i = 0; i < length; i++) {
399 if ((!(i & 0xf)) && i)
400 ss.Printf("%02hhx - ", buf.GetBytes()[i]);
402 ss.Printf("%02hhx ", buf.GetBytes()[i]);
405 return ss.GetString();
408 lldb::addr_t ResolveValue(const Value *value, Module &module) {
409 ValueMap::iterator i = m_values.find(value);
411 if (i != m_values.end())
414 // Fall back and allocate space [allocation type Alloca]
416 lldb::addr_t data_address = Malloc(value->getType());
418 if (const Constant *constant = dyn_cast<Constant>(value)) {
419 if (!ResolveConstant(data_address, constant)) {
420 lldb_private::Status free_error;
421 m_execution_unit.Free(data_address, free_error);
422 return LLDB_INVALID_ADDRESS;
426 m_values[value] = data_address;
431 static const char *unsupported_opcode_error =
432 "Interpreter doesn't handle one of the expression's opcodes";
433 static const char *unsupported_operand_error =
434 "Interpreter doesn't handle one of the expression's operands";
435 // static const char *interpreter_initialization_error = "Interpreter couldn't
437 static const char *interpreter_internal_error =
438 "Interpreter encountered an internal error";
439 static const char *bad_value_error =
440 "Interpreter couldn't resolve a value during execution";
441 static const char *memory_allocation_error =
442 "Interpreter couldn't allocate memory";
443 static const char *memory_write_error = "Interpreter couldn't write to memory";
444 static const char *memory_read_error = "Interpreter couldn't read from memory";
445 static const char *infinite_loop_error = "Interpreter ran for too many cycles";
446 // static const char *bad_result_error = "Result of expression
447 // is in bad memory";
448 static const char *too_many_functions_error =
449 "Interpreter doesn't handle modules with multiple function bodies.";
451 static bool CanResolveConstant(llvm::Constant *constant) {
452 switch (constant->getValueID()) {
455 case Value::ConstantIntVal:
456 case Value::ConstantFPVal:
457 case Value::FunctionVal:
459 case Value::ConstantExprVal:
460 if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
461 switch (constant_expr->getOpcode()) {
464 case Instruction::IntToPtr:
465 case Instruction::PtrToInt:
466 case Instruction::BitCast:
467 return CanResolveConstant(constant_expr->getOperand(0));
468 case Instruction::GetElementPtr: {
469 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
470 Constant *base = dyn_cast<Constant>(*op_cursor);
474 return CanResolveConstant(base);
480 case Value::ConstantPointerNullVal:
485 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
486 lldb_private::Status &error,
487 const bool support_function_calls) {
488 lldb_private::Log *log(
489 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
491 bool saw_function_with_body = false;
493 for (Module::iterator fi = module.begin(), fe = module.end(); fi != fe;
495 if (fi->begin() != fi->end()) {
496 if (saw_function_with_body) {
498 log->Printf("More than one function in the module has a body");
499 error.SetErrorToGenericError();
500 error.SetErrorString(too_many_functions_error);
503 saw_function_with_body = true;
507 for (Function::iterator bbi = function.begin(), bbe = function.end();
509 for (BasicBlock::iterator ii = bbi->begin(), ie = bbi->end(); ii != ie;
511 switch (ii->getOpcode()) {
514 log->Printf("Unsupported instruction: %s", PrintValue(&*ii).c_str());
515 error.SetErrorToGenericError();
516 error.SetErrorString(unsupported_opcode_error);
519 case Instruction::Add:
520 case Instruction::Alloca:
521 case Instruction::BitCast:
522 case Instruction::Br:
523 case Instruction::PHI:
525 case Instruction::Call: {
526 CallInst *call_inst = dyn_cast<CallInst>(ii);
529 error.SetErrorToGenericError();
530 error.SetErrorString(interpreter_internal_error);
534 if (!CanIgnoreCall(call_inst) && !support_function_calls) {
536 log->Printf("Unsupported instruction: %s",
537 PrintValue(&*ii).c_str());
538 error.SetErrorToGenericError();
539 error.SetErrorString(unsupported_opcode_error);
543 case Instruction::GetElementPtr:
545 case Instruction::ICmp: {
546 ICmpInst *icmp_inst = dyn_cast<ICmpInst>(ii);
549 error.SetErrorToGenericError();
550 error.SetErrorString(interpreter_internal_error);
554 switch (icmp_inst->getPredicate()) {
557 log->Printf("Unsupported ICmp predicate: %s",
558 PrintValue(&*ii).c_str());
560 error.SetErrorToGenericError();
561 error.SetErrorString(unsupported_opcode_error);
564 case CmpInst::ICMP_EQ:
565 case CmpInst::ICMP_NE:
566 case CmpInst::ICMP_UGT:
567 case CmpInst::ICMP_UGE:
568 case CmpInst::ICMP_ULT:
569 case CmpInst::ICMP_ULE:
570 case CmpInst::ICMP_SGT:
571 case CmpInst::ICMP_SGE:
572 case CmpInst::ICMP_SLT:
573 case CmpInst::ICMP_SLE:
577 case Instruction::And:
578 case Instruction::AShr:
579 case Instruction::IntToPtr:
580 case Instruction::PtrToInt:
581 case Instruction::Load:
582 case Instruction::LShr:
583 case Instruction::Mul:
584 case Instruction::Or:
585 case Instruction::Ret:
586 case Instruction::SDiv:
587 case Instruction::SExt:
588 case Instruction::Shl:
589 case Instruction::SRem:
590 case Instruction::Store:
591 case Instruction::Sub:
592 case Instruction::Trunc:
593 case Instruction::UDiv:
594 case Instruction::URem:
595 case Instruction::Xor:
596 case Instruction::ZExt:
600 for (int oi = 0, oe = ii->getNumOperands(); oi != oe; ++oi) {
601 Value *operand = ii->getOperand(oi);
602 Type *operand_type = operand->getType();
604 switch (operand_type->getTypeID()) {
607 case Type::VectorTyID: {
609 log->Printf("Unsupported operand type: %s",
610 PrintType(operand_type).c_str());
611 error.SetErrorString(unsupported_operand_error);
616 // The IR interpreter currently doesn't know about
617 // 128-bit integers. As they're not that frequent,
618 // we can just fall back to the JIT rather than
620 if (operand_type->getPrimitiveSizeInBits() > 64) {
622 log->Printf("Unsupported operand type: %s",
623 PrintType(operand_type).c_str());
624 error.SetErrorString(unsupported_operand_error);
628 if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
629 if (!CanResolveConstant(constant)) {
631 log->Printf("Unsupported constant: %s",
632 PrintValue(constant).c_str());
633 error.SetErrorString(unsupported_operand_error);
644 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
645 llvm::ArrayRef<lldb::addr_t> args,
646 lldb_private::IRExecutionUnit &execution_unit,
647 lldb_private::Status &error,
648 lldb::addr_t stack_frame_bottom,
649 lldb::addr_t stack_frame_top,
650 lldb_private::ExecutionContext &exe_ctx) {
651 lldb_private::Log *log(
652 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
656 raw_string_ostream oss(s);
658 module.print(oss, NULL);
662 log->Printf("Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
666 DataLayout data_layout(&module);
668 InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
671 if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
672 error.SetErrorString("Couldn't allocate stack frame");
677 for (llvm::Function::arg_iterator ai = function.arg_begin(),
678 ae = function.arg_end();
679 ai != ae; ++ai, ++arg_index) {
680 if (args.size() <= static_cast<size_t>(arg_index)) {
681 error.SetErrorString("Not enough arguments passed in to function");
685 lldb::addr_t ptr = args[arg_index];
687 frame.MakeArgument(&*ai, ptr);
690 uint32_t num_insts = 0;
692 frame.Jump(&function.front());
694 while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
695 const Instruction *inst = &*frame.m_ii;
698 log->Printf("Interpreting %s", PrintValue(inst).c_str());
700 switch (inst->getOpcode()) {
704 case Instruction::Add:
705 case Instruction::Sub:
706 case Instruction::Mul:
707 case Instruction::SDiv:
708 case Instruction::UDiv:
709 case Instruction::SRem:
710 case Instruction::URem:
711 case Instruction::Shl:
712 case Instruction::LShr:
713 case Instruction::AShr:
714 case Instruction::And:
715 case Instruction::Or:
716 case Instruction::Xor: {
717 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
722 "getOpcode() returns %s, but instruction is not a BinaryOperator",
723 inst->getOpcodeName());
724 error.SetErrorToGenericError();
725 error.SetErrorString(interpreter_internal_error);
729 Value *lhs = inst->getOperand(0);
730 Value *rhs = inst->getOperand(1);
732 lldb_private::Scalar L;
733 lldb_private::Scalar R;
735 if (!frame.EvaluateValue(L, lhs, module)) {
737 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
738 error.SetErrorToGenericError();
739 error.SetErrorString(bad_value_error);
743 if (!frame.EvaluateValue(R, rhs, module)) {
745 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
746 error.SetErrorToGenericError();
747 error.SetErrorString(bad_value_error);
751 lldb_private::Scalar result;
753 switch (inst->getOpcode()) {
756 case Instruction::Add:
759 case Instruction::Mul:
762 case Instruction::Sub:
765 case Instruction::SDiv:
770 case Instruction::UDiv:
775 case Instruction::SRem:
780 case Instruction::URem:
785 case Instruction::Shl:
788 case Instruction::AShr:
791 case Instruction::LShr:
793 result.ShiftRightLogical(R);
795 case Instruction::And:
798 case Instruction::Or:
801 case Instruction::Xor:
806 frame.AssignValue(inst, result, module);
809 log->Printf("Interpreted a %s", inst->getOpcodeName());
810 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
811 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
812 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
815 case Instruction::Alloca: {
816 const AllocaInst *alloca_inst = dyn_cast<AllocaInst>(inst);
820 log->Printf("getOpcode() returns Alloca, but instruction is not an "
822 error.SetErrorToGenericError();
823 error.SetErrorString(interpreter_internal_error);
827 if (alloca_inst->isArrayAllocation()) {
830 "AllocaInsts are not handled if isArrayAllocation() is true");
831 error.SetErrorToGenericError();
832 error.SetErrorString(unsupported_opcode_error);
836 // The semantics of Alloca are:
837 // Create a region R of virtual memory of type T, backed by a data
839 // Create a region P of virtual memory of type T*, backed by a data
841 // Write the virtual address of R into P
843 Type *T = alloca_inst->getAllocatedType();
844 Type *Tptr = alloca_inst->getType();
846 lldb::addr_t R = frame.Malloc(T);
848 if (R == LLDB_INVALID_ADDRESS) {
850 log->Printf("Couldn't allocate memory for an AllocaInst");
851 error.SetErrorToGenericError();
852 error.SetErrorString(memory_allocation_error);
856 lldb::addr_t P = frame.Malloc(Tptr);
858 if (P == LLDB_INVALID_ADDRESS) {
860 log->Printf("Couldn't allocate the result pointer for an AllocaInst");
861 error.SetErrorToGenericError();
862 error.SetErrorString(memory_allocation_error);
866 lldb_private::Status write_error;
868 execution_unit.WritePointerToMemory(P, R, write_error);
870 if (!write_error.Success()) {
872 log->Printf("Couldn't write the result pointer for an AllocaInst");
873 error.SetErrorToGenericError();
874 error.SetErrorString(memory_write_error);
875 lldb_private::Status free_error;
876 execution_unit.Free(P, free_error);
877 execution_unit.Free(R, free_error);
881 frame.m_values[alloca_inst] = P;
884 log->Printf("Interpreted an AllocaInst");
885 log->Printf(" R : 0x%" PRIx64, R);
886 log->Printf(" P : 0x%" PRIx64, P);
889 case Instruction::BitCast:
890 case Instruction::ZExt: {
891 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
896 "getOpcode() returns %s, but instruction is not a BitCastInst",
897 cast_inst->getOpcodeName());
898 error.SetErrorToGenericError();
899 error.SetErrorString(interpreter_internal_error);
903 Value *source = cast_inst->getOperand(0);
905 lldb_private::Scalar S;
907 if (!frame.EvaluateValue(S, source, module)) {
909 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
910 error.SetErrorToGenericError();
911 error.SetErrorString(bad_value_error);
915 frame.AssignValue(inst, S, module);
917 case Instruction::SExt: {
918 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
923 "getOpcode() returns %s, but instruction is not a BitCastInst",
924 cast_inst->getOpcodeName());
925 error.SetErrorToGenericError();
926 error.SetErrorString(interpreter_internal_error);
930 Value *source = cast_inst->getOperand(0);
932 lldb_private::Scalar S;
934 if (!frame.EvaluateValue(S, source, module)) {
936 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
937 error.SetErrorToGenericError();
938 error.SetErrorString(bad_value_error);
944 lldb_private::Scalar S_signextend(S.SLongLong());
946 frame.AssignValue(inst, S_signextend, module);
948 case Instruction::Br: {
949 const BranchInst *br_inst = dyn_cast<BranchInst>(inst);
954 "getOpcode() returns Br, but instruction is not a BranchInst");
955 error.SetErrorToGenericError();
956 error.SetErrorString(interpreter_internal_error);
960 if (br_inst->isConditional()) {
961 Value *condition = br_inst->getCondition();
963 lldb_private::Scalar C;
965 if (!frame.EvaluateValue(C, condition, module)) {
967 log->Printf("Couldn't evaluate %s", PrintValue(condition).c_str());
968 error.SetErrorToGenericError();
969 error.SetErrorString(bad_value_error);
974 frame.Jump(br_inst->getSuccessor(0));
976 frame.Jump(br_inst->getSuccessor(1));
979 log->Printf("Interpreted a BrInst with a condition");
980 log->Printf(" cond : %s", frame.SummarizeValue(condition).c_str());
983 frame.Jump(br_inst->getSuccessor(0));
986 log->Printf("Interpreted a BrInst with no condition");
991 case Instruction::PHI: {
992 const PHINode *phi_inst = dyn_cast<PHINode>(inst);
997 "getOpcode() returns PHI, but instruction is not a PHINode");
998 error.SetErrorToGenericError();
999 error.SetErrorString(interpreter_internal_error);
1002 if (!frame.m_prev_bb) {
1004 log->Printf("Encountered PHI node without having jumped from another "
1006 error.SetErrorToGenericError();
1007 error.SetErrorString(interpreter_internal_error);
1011 Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
1012 lldb_private::Scalar result;
1013 if (!frame.EvaluateValue(result, value, module)) {
1015 log->Printf("Couldn't evaluate %s", PrintValue(value).c_str());
1016 error.SetErrorToGenericError();
1017 error.SetErrorString(bad_value_error);
1020 frame.AssignValue(inst, result, module);
1023 log->Printf("Interpreted a %s", inst->getOpcodeName());
1024 log->Printf(" Incoming value : %s",
1025 frame.SummarizeValue(value).c_str());
1028 case Instruction::GetElementPtr: {
1029 const GetElementPtrInst *gep_inst = dyn_cast<GetElementPtrInst>(inst);
1033 log->Printf("getOpcode() returns GetElementPtr, but instruction is "
1034 "not a GetElementPtrInst");
1035 error.SetErrorToGenericError();
1036 error.SetErrorString(interpreter_internal_error);
1040 const Value *pointer_operand = gep_inst->getPointerOperand();
1041 Type *src_elem_ty = gep_inst->getSourceElementType();
1043 lldb_private::Scalar P;
1045 if (!frame.EvaluateValue(P, pointer_operand, module)) {
1047 log->Printf("Couldn't evaluate %s",
1048 PrintValue(pointer_operand).c_str());
1049 error.SetErrorToGenericError();
1050 error.SetErrorString(bad_value_error);
1054 typedef SmallVector<Value *, 8> IndexVector;
1055 typedef IndexVector::iterator IndexIterator;
1057 SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
1058 gep_inst->idx_end());
1060 SmallVector<Value *, 8> const_indices;
1062 for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
1064 ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1066 if (!constant_index) {
1067 lldb_private::Scalar I;
1069 if (!frame.EvaluateValue(I, *ii, module)) {
1071 log->Printf("Couldn't evaluate %s", PrintValue(*ii).c_str());
1072 error.SetErrorToGenericError();
1073 error.SetErrorString(bad_value_error);
1078 log->Printf("Evaluated constant index %s as %llu",
1079 PrintValue(*ii).c_str(),
1080 I.ULongLong(LLDB_INVALID_ADDRESS));
1082 constant_index = cast<ConstantInt>(ConstantInt::get(
1083 (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1086 const_indices.push_back(constant_index);
1090 data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1092 lldb_private::Scalar Poffset = P + offset;
1094 frame.AssignValue(inst, Poffset, module);
1097 log->Printf("Interpreted a GetElementPtrInst");
1098 log->Printf(" P : %s",
1099 frame.SummarizeValue(pointer_operand).c_str());
1100 log->Printf(" Poffset : %s", frame.SummarizeValue(inst).c_str());
1103 case Instruction::ICmp: {
1104 const ICmpInst *icmp_inst = dyn_cast<ICmpInst>(inst);
1109 "getOpcode() returns ICmp, but instruction is not an ICmpInst");
1110 error.SetErrorToGenericError();
1111 error.SetErrorString(interpreter_internal_error);
1115 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1117 Value *lhs = inst->getOperand(0);
1118 Value *rhs = inst->getOperand(1);
1120 lldb_private::Scalar L;
1121 lldb_private::Scalar R;
1123 if (!frame.EvaluateValue(L, lhs, module)) {
1125 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1126 error.SetErrorToGenericError();
1127 error.SetErrorString(bad_value_error);
1131 if (!frame.EvaluateValue(R, rhs, module)) {
1133 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1134 error.SetErrorToGenericError();
1135 error.SetErrorString(bad_value_error);
1139 lldb_private::Scalar result;
1141 switch (predicate) {
1144 case CmpInst::ICMP_EQ:
1147 case CmpInst::ICMP_NE:
1150 case CmpInst::ICMP_UGT:
1155 case CmpInst::ICMP_UGE:
1160 case CmpInst::ICMP_ULT:
1165 case CmpInst::ICMP_ULE:
1170 case CmpInst::ICMP_SGT:
1175 case CmpInst::ICMP_SGE:
1180 case CmpInst::ICMP_SLT:
1185 case CmpInst::ICMP_SLE:
1192 frame.AssignValue(inst, result, module);
1195 log->Printf("Interpreted an ICmpInst");
1196 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
1197 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
1198 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1201 case Instruction::IntToPtr: {
1202 const IntToPtrInst *int_to_ptr_inst = dyn_cast<IntToPtrInst>(inst);
1204 if (!int_to_ptr_inst) {
1206 log->Printf("getOpcode() returns IntToPtr, but instruction is not an "
1208 error.SetErrorToGenericError();
1209 error.SetErrorString(interpreter_internal_error);
1213 Value *src_operand = int_to_ptr_inst->getOperand(0);
1215 lldb_private::Scalar I;
1217 if (!frame.EvaluateValue(I, src_operand, module)) {
1219 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1220 error.SetErrorToGenericError();
1221 error.SetErrorString(bad_value_error);
1225 frame.AssignValue(inst, I, module);
1228 log->Printf("Interpreted an IntToPtr");
1229 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1230 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1233 case Instruction::PtrToInt: {
1234 const PtrToIntInst *ptr_to_int_inst = dyn_cast<PtrToIntInst>(inst);
1236 if (!ptr_to_int_inst) {
1238 log->Printf("getOpcode() returns PtrToInt, but instruction is not an "
1240 error.SetErrorToGenericError();
1241 error.SetErrorString(interpreter_internal_error);
1245 Value *src_operand = ptr_to_int_inst->getOperand(0);
1247 lldb_private::Scalar I;
1249 if (!frame.EvaluateValue(I, src_operand, module)) {
1251 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1252 error.SetErrorToGenericError();
1253 error.SetErrorString(bad_value_error);
1257 frame.AssignValue(inst, I, module);
1260 log->Printf("Interpreted a PtrToInt");
1261 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1262 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1265 case Instruction::Trunc: {
1266 const TruncInst *trunc_inst = dyn_cast<TruncInst>(inst);
1271 "getOpcode() returns Trunc, but instruction is not a TruncInst");
1272 error.SetErrorToGenericError();
1273 error.SetErrorString(interpreter_internal_error);
1277 Value *src_operand = trunc_inst->getOperand(0);
1279 lldb_private::Scalar I;
1281 if (!frame.EvaluateValue(I, src_operand, module)) {
1283 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1284 error.SetErrorToGenericError();
1285 error.SetErrorString(bad_value_error);
1289 frame.AssignValue(inst, I, module);
1292 log->Printf("Interpreted a Trunc");
1293 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1294 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1297 case Instruction::Load: {
1298 const LoadInst *load_inst = dyn_cast<LoadInst>(inst);
1303 "getOpcode() returns Load, but instruction is not a LoadInst");
1304 error.SetErrorToGenericError();
1305 error.SetErrorString(interpreter_internal_error);
1309 // The semantics of Load are:
1310 // Create a region D that will contain the loaded data
1311 // Resolve the region P containing a pointer
1312 // Dereference P to get the region R that the data should be loaded from
1313 // Transfer a unit of type type(D) from R to D
1315 const Value *pointer_operand = load_inst->getPointerOperand();
1317 Type *pointer_ty = pointer_operand->getType();
1318 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1319 if (!pointer_ptr_ty) {
1321 log->Printf("getPointerOperand()->getType() is not a PointerType");
1322 error.SetErrorToGenericError();
1323 error.SetErrorString(interpreter_internal_error);
1326 Type *target_ty = pointer_ptr_ty->getElementType();
1328 lldb::addr_t D = frame.ResolveValue(load_inst, module);
1329 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1331 if (D == LLDB_INVALID_ADDRESS) {
1333 log->Printf("LoadInst's value doesn't resolve to anything");
1334 error.SetErrorToGenericError();
1335 error.SetErrorString(bad_value_error);
1339 if (P == LLDB_INVALID_ADDRESS) {
1341 log->Printf("LoadInst's pointer doesn't resolve to anything");
1342 error.SetErrorToGenericError();
1343 error.SetErrorString(bad_value_error);
1348 lldb_private::Status read_error;
1349 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1351 if (!read_error.Success()) {
1353 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1354 error.SetErrorToGenericError();
1355 error.SetErrorString(memory_read_error);
1359 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1360 lldb_private::DataBufferHeap buffer(target_size, 0);
1363 execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1365 if (!read_error.Success()) {
1367 log->Printf("Couldn't read from a region on behalf of a LoadInst");
1368 error.SetErrorToGenericError();
1369 error.SetErrorString(memory_read_error);
1373 lldb_private::Status write_error;
1374 execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1376 if (!write_error.Success()) {
1378 log->Printf("Couldn't write to a region on behalf of a LoadInst");
1379 error.SetErrorToGenericError();
1380 error.SetErrorString(memory_read_error);
1385 log->Printf("Interpreted a LoadInst");
1386 log->Printf(" P : 0x%" PRIx64, P);
1387 log->Printf(" R : 0x%" PRIx64, R);
1388 log->Printf(" D : 0x%" PRIx64, D);
1391 case Instruction::Ret: {
1394 case Instruction::Store: {
1395 const StoreInst *store_inst = dyn_cast<StoreInst>(inst);
1400 "getOpcode() returns Store, but instruction is not a StoreInst");
1401 error.SetErrorToGenericError();
1402 error.SetErrorString(interpreter_internal_error);
1406 // The semantics of Store are:
1407 // Resolve the region D containing the data to be stored
1408 // Resolve the region P containing a pointer
1409 // Dereference P to get the region R that the data should be stored in
1410 // Transfer a unit of type type(D) from D to R
1412 const Value *value_operand = store_inst->getValueOperand();
1413 const Value *pointer_operand = store_inst->getPointerOperand();
1415 Type *pointer_ty = pointer_operand->getType();
1416 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1417 if (!pointer_ptr_ty)
1419 Type *target_ty = pointer_ptr_ty->getElementType();
1421 lldb::addr_t D = frame.ResolveValue(value_operand, module);
1422 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1424 if (D == LLDB_INVALID_ADDRESS) {
1426 log->Printf("StoreInst's value doesn't resolve to anything");
1427 error.SetErrorToGenericError();
1428 error.SetErrorString(bad_value_error);
1432 if (P == LLDB_INVALID_ADDRESS) {
1434 log->Printf("StoreInst's pointer doesn't resolve to anything");
1435 error.SetErrorToGenericError();
1436 error.SetErrorString(bad_value_error);
1441 lldb_private::Status read_error;
1442 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1444 if (!read_error.Success()) {
1446 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1447 error.SetErrorToGenericError();
1448 error.SetErrorString(memory_read_error);
1452 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1453 lldb_private::DataBufferHeap buffer(target_size, 0);
1456 execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1458 if (!read_error.Success()) {
1460 log->Printf("Couldn't read from a region on behalf of a StoreInst");
1461 error.SetErrorToGenericError();
1462 error.SetErrorString(memory_read_error);
1466 lldb_private::Status write_error;
1467 execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1469 if (!write_error.Success()) {
1471 log->Printf("Couldn't write to a region on behalf of a StoreInst");
1472 error.SetErrorToGenericError();
1473 error.SetErrorString(memory_write_error);
1478 log->Printf("Interpreted a StoreInst");
1479 log->Printf(" D : 0x%" PRIx64, D);
1480 log->Printf(" P : 0x%" PRIx64, P);
1481 log->Printf(" R : 0x%" PRIx64, R);
1484 case Instruction::Call: {
1485 const CallInst *call_inst = dyn_cast<CallInst>(inst);
1490 "getOpcode() returns %s, but instruction is not a CallInst",
1491 inst->getOpcodeName());
1492 error.SetErrorToGenericError();
1493 error.SetErrorString(interpreter_internal_error);
1497 if (CanIgnoreCall(call_inst))
1500 // Get the return type
1501 llvm::Type *returnType = call_inst->getType();
1502 if (returnType == nullptr) {
1503 error.SetErrorToGenericError();
1504 error.SetErrorString("unable to access return type");
1508 // Work with void, integer and pointer return types
1509 if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1510 !returnType->isPointerTy()) {
1511 error.SetErrorToGenericError();
1512 error.SetErrorString("return type is not supported");
1516 // Check we can actually get a thread
1517 if (exe_ctx.GetThreadPtr() == nullptr) {
1518 error.SetErrorToGenericError();
1519 error.SetErrorStringWithFormat("unable to acquire thread");
1523 // Make sure we have a valid process
1524 if (!exe_ctx.GetProcessPtr()) {
1525 error.SetErrorToGenericError();
1526 error.SetErrorStringWithFormat("unable to get the process");
1530 // Find the address of the callee function
1531 lldb_private::Scalar I;
1532 const llvm::Value *val = call_inst->getCalledValue();
1534 if (!frame.EvaluateValue(I, val, module)) {
1535 error.SetErrorToGenericError();
1536 error.SetErrorString("unable to get address of function");
1539 lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1541 lldb_private::DiagnosticManager diagnostics;
1542 lldb_private::EvaluateExpressionOptions options;
1544 // We generally receive a function pointer which we must dereference
1545 llvm::Type *prototype = val->getType();
1546 if (!prototype->isPointerTy()) {
1547 error.SetErrorToGenericError();
1548 error.SetErrorString("call need function pointer");
1552 // Dereference the function pointer
1553 prototype = prototype->getPointerElementType();
1554 if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1555 error.SetErrorToGenericError();
1556 error.SetErrorString("call need function pointer");
1560 // Find number of arguments
1561 const int numArgs = call_inst->getNumArgOperands();
1563 // We work with a fixed array of 16 arguments which is our upper limit
1564 static lldb_private::ABI::CallArgument rawArgs[16];
1565 if (numArgs >= 16) {
1566 error.SetErrorToGenericError();
1567 error.SetErrorStringWithFormat("function takes too many arguments");
1571 // Push all function arguments to the argument list that will be passed
1572 // to the call function thread plan
1573 for (int i = 0; i < numArgs; i++) {
1574 // Get details of this argument
1575 llvm::Value *arg_op = call_inst->getArgOperand(i);
1576 llvm::Type *arg_ty = arg_op->getType();
1578 // Ensure that this argument is an supported type
1579 if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1580 error.SetErrorToGenericError();
1581 error.SetErrorStringWithFormat("argument %d must be integer type", i);
1585 // Extract the arguments value
1586 lldb_private::Scalar tmp_op = 0;
1587 if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1588 error.SetErrorToGenericError();
1589 error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1593 // Check if this is a string literal or constant string pointer
1594 if (arg_ty->isPointerTy()) {
1595 lldb::addr_t addr = tmp_op.ULongLong();
1596 size_t dataSize = 0;
1598 bool Success = execution_unit.GetAllocSize(addr, dataSize);
1601 "unable to locate host data for transfer to device");
1602 // Create the required buffer
1603 rawArgs[i].size = dataSize;
1604 rawArgs[i].data_ap.reset(new uint8_t[dataSize + 1]);
1606 // Read string from host memory
1607 execution_unit.ReadMemory(rawArgs[i].data_ap.get(), addr, dataSize,
1609 assert(!error.Fail() &&
1610 "we have failed to read the string from memory");
1612 // Add null terminator
1613 rawArgs[i].data_ap[dataSize] = '\0';
1614 rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
1615 } else /* if ( arg_ty->isPointerTy() ) */
1617 rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1618 // Get argument size in bytes
1619 rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1620 // Push value into argument list for thread plan
1621 rawArgs[i].value = tmp_op.ULongLong();
1625 // Pack the arguments into an llvm::array
1626 llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1628 // Setup a thread plan to call the target function
1629 lldb::ThreadPlanSP call_plan_sp(
1630 new lldb_private::ThreadPlanCallFunctionUsingABI(
1631 exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1634 // Check if the plan is valid
1635 lldb_private::StreamString ss;
1636 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1637 error.SetErrorToGenericError();
1638 error.SetErrorStringWithFormat(
1639 "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1644 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1646 // Execute the actual function call thread plan
1647 lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1648 exe_ctx, call_plan_sp, options, diagnostics);
1650 // Check that the thread plan completed successfully
1651 if (res != lldb::ExpressionResults::eExpressionCompleted) {
1652 error.SetErrorToGenericError();
1653 error.SetErrorStringWithFormat("ThreadPlanCallFunctionUsingABI failed");
1657 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1660 if (returnType->isVoidTy()) {
1661 // Cant assign to void types, so we leave the frame untouched
1663 // Integer or pointer return type
1664 if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1665 // Get the encapsulated return value
1666 lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1668 lldb_private::Scalar returnVal = -1;
1669 lldb_private::ValueObject *vobj = retVal.get();
1671 // Check if the return value is valid
1672 if (vobj == nullptr || retVal.empty()) {
1673 error.SetErrorToGenericError();
1674 error.SetErrorStringWithFormat("unable to get the return value");
1678 // Extract the return value as a integer
1679 lldb_private::Value &value = vobj->GetValue();
1680 returnVal = value.GetScalar();
1682 // Push the return value as the result
1683 frame.AssignValue(inst, returnVal, module);
1691 if (num_insts >= 4096) {
1692 error.SetErrorToGenericError();
1693 error.SetErrorString(infinite_loop_error);