1 //===-- IRInterpreter.cpp ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Expression/IRInterpreter.h"
10 #include "lldb/Core/Module.h"
11 #include "lldb/Core/ModuleSpec.h"
12 #include "lldb/Core/ValueObject.h"
13 #include "lldb/Expression/DiagnosticManager.h"
14 #include "lldb/Expression/IRExecutionUnit.h"
15 #include "lldb/Expression/IRMemoryMap.h"
16 #include "lldb/Utility/ConstString.h"
17 #include "lldb/Utility/DataExtractor.h"
18 #include "lldb/Utility/Endian.h"
19 #include "lldb/Utility/Log.h"
20 #include "lldb/Utility/Scalar.h"
21 #include "lldb/Utility/Status.h"
22 #include "lldb/Utility/StreamString.h"
23 
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Target/ThreadPlan.h"
29 #include "lldb/Target/ThreadPlanCallFunctionUsingABI.h"
30 
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 #include <map>
42 
43 using namespace llvm;
44 
45 static std::string PrintValue(const Value *value, bool truncate = false) {
46   std::string s;
47   raw_string_ostream rso(s);
48   value->print(rso);
49   rso.flush();
50   if (truncate)
51     s.resize(s.length() - 1);
52 
53   size_t offset;
54   while ((offset = s.find('\n')) != s.npos)
55     s.erase(offset, 1);
56   while (s[0] == ' ' || s[0] == '\t')
57     s.erase(0, 1);
58 
59   return s;
60 }
61 
62 static std::string PrintType(const Type *type, bool truncate = false) {
63   std::string s;
64   raw_string_ostream rso(s);
65   type->print(rso);
66   rso.flush();
67   if (truncate)
68     s.resize(s.length() - 1);
69   return s;
70 }
71 
72 static bool CanIgnoreCall(const CallInst *call) {
73   const llvm::Function *called_function = call->getCalledFunction();
74 
75   if (!called_function)
76     return false;
77 
78   if (called_function->isIntrinsic()) {
79     switch (called_function->getIntrinsicID()) {
80     default:
81       break;
82     case llvm::Intrinsic::dbg_declare:
83     case llvm::Intrinsic::dbg_value:
84       return true;
85     }
86   }
87 
88   return false;
89 }
90 
91 class InterpreterStackFrame {
92 public:
93   typedef std::map<const Value *, lldb::addr_t> ValueMap;
94 
95   ValueMap m_values;
96   DataLayout &m_target_data;
97   lldb_private::IRExecutionUnit &m_execution_unit;
98   const BasicBlock *m_bb;
99   const BasicBlock *m_prev_bb;
100   BasicBlock::const_iterator m_ii;
101   BasicBlock::const_iterator m_ie;
102 
103   lldb::addr_t m_frame_process_address;
104   size_t m_frame_size;
105   lldb::addr_t m_stack_pointer;
106 
107   lldb::ByteOrder m_byte_order;
108   size_t m_addr_byte_size;
109 
110   InterpreterStackFrame(DataLayout &target_data,
111                         lldb_private::IRExecutionUnit &execution_unit,
112                         lldb::addr_t stack_frame_bottom,
113                         lldb::addr_t stack_frame_top)
114       : m_target_data(target_data), m_execution_unit(execution_unit),
115         m_bb(nullptr), m_prev_bb(nullptr) {
116     m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle
117                                                  : lldb::eByteOrderBig);
118     m_addr_byte_size = (target_data.getPointerSize(0));
119 
120     m_frame_process_address = stack_frame_bottom;
121     m_frame_size = stack_frame_top - stack_frame_bottom;
122     m_stack_pointer = stack_frame_top;
123   }
124 
125   ~InterpreterStackFrame() {}
126 
127   void Jump(const BasicBlock *bb) {
128     m_prev_bb = m_bb;
129     m_bb = bb;
130     m_ii = m_bb->begin();
131     m_ie = m_bb->end();
132   }
133 
134   std::string SummarizeValue(const Value *value) {
135     lldb_private::StreamString ss;
136 
137     ss.Printf("%s", PrintValue(value).c_str());
138 
139     ValueMap::iterator i = m_values.find(value);
140 
141     if (i != m_values.end()) {
142       lldb::addr_t addr = i->second;
143 
144       ss.Printf(" 0x%llx", (unsigned long long)addr);
145     }
146 
147     return ss.GetString();
148   }
149 
150   bool AssignToMatchType(lldb_private::Scalar &scalar, uint64_t u64value,
151                          Type *type) {
152     size_t type_size = m_target_data.getTypeStoreSize(type);
153 
154     if (type_size > 8)
155       return false;
156 
157     if (type_size != 1)
158       type_size = PowerOf2Ceil(type_size);
159 
160     scalar = llvm::APInt(type_size*8, u64value);
161     return true;
162   }
163 
164   bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
165                      Module &module) {
166     const Constant *constant = dyn_cast<Constant>(value);
167 
168     if (constant) {
169       APInt value_apint;
170 
171       if (!ResolveConstantValue(value_apint, constant))
172         return false;
173 
174       return AssignToMatchType(scalar, value_apint.getLimitedValue(),
175                                value->getType());
176     } else {
177       lldb::addr_t process_address = ResolveValue(value, module);
178       size_t value_size = m_target_data.getTypeStoreSize(value->getType());
179 
180       lldb_private::DataExtractor value_extractor;
181       lldb_private::Status extract_error;
182 
183       m_execution_unit.GetMemoryData(value_extractor, process_address,
184                                      value_size, extract_error);
185 
186       if (!extract_error.Success())
187         return false;
188 
189       lldb::offset_t offset = 0;
190       if (value_size <= 8) {
191         uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
192         return AssignToMatchType(scalar, u64value, value->getType());
193       }
194     }
195 
196     return false;
197   }
198 
199   bool AssignValue(const Value *value, lldb_private::Scalar &scalar,
200                    Module &module) {
201     lldb::addr_t process_address = ResolveValue(value, module);
202 
203     if (process_address == LLDB_INVALID_ADDRESS)
204       return false;
205 
206     lldb_private::Scalar cast_scalar;
207 
208     if (!AssignToMatchType(cast_scalar, scalar.ULongLong(), value->getType()))
209       return false;
210 
211     size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
212 
213     lldb_private::DataBufferHeap buf(value_byte_size, 0);
214 
215     lldb_private::Status get_data_error;
216 
217     if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
218                                      m_byte_order, get_data_error))
219       return false;
220 
221     lldb_private::Status write_error;
222 
223     m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
224                                  buf.GetByteSize(), write_error);
225 
226     return write_error.Success();
227   }
228 
229   bool ResolveConstantValue(APInt &value, const Constant *constant) {
230     switch (constant->getValueID()) {
231     default:
232       break;
233     case Value::FunctionVal:
234       if (const Function *constant_func = dyn_cast<Function>(constant)) {
235         lldb_private::ConstString name(constant_func->getName());
236         bool missing_weak = false;
237         lldb::addr_t addr = m_execution_unit.FindSymbol(name, missing_weak);
238         if (addr == LLDB_INVALID_ADDRESS || missing_weak)
239           return false;
240         value = APInt(m_target_data.getPointerSizeInBits(), addr);
241         return true;
242       }
243       break;
244     case Value::ConstantIntVal:
245       if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
246         value = constant_int->getValue();
247         return true;
248       }
249       break;
250     case Value::ConstantFPVal:
251       if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
252         value = constant_fp->getValueAPF().bitcastToAPInt();
253         return true;
254       }
255       break;
256     case Value::ConstantExprVal:
257       if (const ConstantExpr *constant_expr =
258               dyn_cast<ConstantExpr>(constant)) {
259         switch (constant_expr->getOpcode()) {
260         default:
261           return false;
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();
269 
270           Constant *base = dyn_cast<Constant>(*op_cursor);
271 
272           if (!base)
273             return false;
274 
275           if (!ResolveConstantValue(value, base))
276             return false;
277 
278           op_cursor++;
279 
280           if (op_cursor == op_end)
281             return true; // no offset to apply!
282 
283           SmallVector<Value *, 8> indices(op_cursor, op_end);
284 
285           Type *src_elem_ty =
286               cast<GEPOperator>(constant_expr)->getSourceElementType();
287           uint64_t offset =
288               m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
289 
290           const bool is_signed = true;
291           value += APInt(value.getBitWidth(), offset, is_signed);
292 
293           return true;
294         }
295         }
296       }
297       break;
298     case Value::ConstantPointerNullVal:
299       if (isa<ConstantPointerNull>(constant)) {
300         value = APInt(m_target_data.getPointerSizeInBits(), 0);
301         return true;
302       }
303       break;
304     }
305     return false;
306   }
307 
308   bool MakeArgument(const Argument *value, uint64_t address) {
309     lldb::addr_t data_address = Malloc(value->getType());
310 
311     if (data_address == LLDB_INVALID_ADDRESS)
312       return false;
313 
314     lldb_private::Status write_error;
315 
316     m_execution_unit.WritePointerToMemory(data_address, address, write_error);
317 
318     if (!write_error.Success()) {
319       lldb_private::Status free_error;
320       m_execution_unit.Free(data_address, free_error);
321       return false;
322     }
323 
324     m_values[value] = data_address;
325 
326     lldb_private::Log *log(
327         lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
328 
329     if (log) {
330       LLDB_LOGF(log, "Made an allocation for argument %s",
331                 PrintValue(value).c_str());
332       LLDB_LOGF(log, "  Data region    : %llx", (unsigned long long)address);
333       LLDB_LOGF(log, "  Ref region     : %llx",
334                 (unsigned long long)data_address);
335     }
336 
337     return true;
338   }
339 
340   bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
341     APInt resolved_value;
342 
343     if (!ResolveConstantValue(resolved_value, constant))
344       return false;
345 
346     size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
347     lldb_private::DataBufferHeap buf(constant_size, 0);
348 
349     lldb_private::Status get_data_error;
350 
351     lldb_private::Scalar resolved_scalar(
352         resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
353     if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
354                                          m_byte_order, get_data_error))
355       return false;
356 
357     lldb_private::Status write_error;
358 
359     m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
360                                  buf.GetByteSize(), write_error);
361 
362     return write_error.Success();
363   }
364 
365   lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
366     lldb::addr_t ret = m_stack_pointer;
367 
368     ret -= size;
369     ret -= (ret % byte_alignment);
370 
371     if (ret < m_frame_process_address)
372       return LLDB_INVALID_ADDRESS;
373 
374     m_stack_pointer = ret;
375     return ret;
376   }
377 
378   lldb::addr_t Malloc(llvm::Type *type) {
379     lldb_private::Status alloc_error;
380 
381     return Malloc(m_target_data.getTypeAllocSize(type),
382                   m_target_data.getPrefTypeAlignment(type));
383   }
384 
385   std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
386     size_t length = m_target_data.getTypeStoreSize(type);
387 
388     lldb_private::DataBufferHeap buf(length, 0);
389 
390     lldb_private::Status read_error;
391 
392     m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
393 
394     if (!read_error.Success())
395       return std::string("<couldn't read data>");
396 
397     lldb_private::StreamString ss;
398 
399     for (size_t i = 0; i < length; i++) {
400       if ((!(i & 0xf)) && i)
401         ss.Printf("%02hhx - ", buf.GetBytes()[i]);
402       else
403         ss.Printf("%02hhx ", buf.GetBytes()[i]);
404     }
405 
406     return ss.GetString();
407   }
408 
409   lldb::addr_t ResolveValue(const Value *value, Module &module) {
410     ValueMap::iterator i = m_values.find(value);
411 
412     if (i != m_values.end())
413       return i->second;
414 
415     // Fall back and allocate space [allocation type Alloca]
416 
417     lldb::addr_t data_address = Malloc(value->getType());
418 
419     if (const Constant *constant = dyn_cast<Constant>(value)) {
420       if (!ResolveConstant(data_address, constant)) {
421         lldb_private::Status free_error;
422         m_execution_unit.Free(data_address, free_error);
423         return LLDB_INVALID_ADDRESS;
424       }
425     }
426 
427     m_values[value] = data_address;
428     return data_address;
429   }
430 };
431 
432 static const char *unsupported_opcode_error =
433     "Interpreter doesn't handle one of the expression's opcodes";
434 static const char *unsupported_operand_error =
435     "Interpreter doesn't handle one of the expression's operands";
436 // static const char *interpreter_initialization_error = "Interpreter couldn't
437 // be initialized";
438 static const char *interpreter_internal_error =
439     "Interpreter encountered an internal error";
440 static const char *bad_value_error =
441     "Interpreter couldn't resolve a value during execution";
442 static const char *memory_allocation_error =
443     "Interpreter couldn't allocate memory";
444 static const char *memory_write_error = "Interpreter couldn't write to memory";
445 static const char *memory_read_error = "Interpreter couldn't read from memory";
446 static const char *infinite_loop_error = "Interpreter ran for too many cycles";
447 // static const char *bad_result_error                 = "Result of expression
448 // is in bad memory";
449 static const char *too_many_functions_error =
450     "Interpreter doesn't handle modules with multiple function bodies.";
451 
452 static bool CanResolveConstant(llvm::Constant *constant) {
453   switch (constant->getValueID()) {
454   default:
455     return false;
456   case Value::ConstantIntVal:
457   case Value::ConstantFPVal:
458   case Value::FunctionVal:
459     return true;
460   case Value::ConstantExprVal:
461     if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
462       switch (constant_expr->getOpcode()) {
463       default:
464         return false;
465       case Instruction::IntToPtr:
466       case Instruction::PtrToInt:
467       case Instruction::BitCast:
468         return CanResolveConstant(constant_expr->getOperand(0));
469       case Instruction::GetElementPtr: {
470         ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
471         Constant *base = dyn_cast<Constant>(*op_cursor);
472         if (!base)
473           return false;
474 
475         return CanResolveConstant(base);
476       }
477       }
478     } else {
479       return false;
480     }
481   case Value::ConstantPointerNullVal:
482     return true;
483   }
484 }
485 
486 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
487                                  lldb_private::Status &error,
488                                  const bool support_function_calls) {
489   lldb_private::Log *log(
490       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
491 
492   bool saw_function_with_body = false;
493   for (Function &f : module) {
494     if (f.begin() != f.end()) {
495       if (saw_function_with_body) {
496         LLDB_LOGF(log, "More than one function in the module has a body");
497         error.SetErrorToGenericError();
498         error.SetErrorString(too_many_functions_error);
499         return false;
500       }
501       saw_function_with_body = true;
502     }
503   }
504 
505   for (BasicBlock &bb : function) {
506     for (Instruction &ii : bb) {
507       switch (ii.getOpcode()) {
508       default: {
509         LLDB_LOGF(log, "Unsupported instruction: %s", PrintValue(&ii).c_str());
510         error.SetErrorToGenericError();
511         error.SetErrorString(unsupported_opcode_error);
512         return false;
513       }
514       case Instruction::Add:
515       case Instruction::Alloca:
516       case Instruction::BitCast:
517       case Instruction::Br:
518       case Instruction::PHI:
519         break;
520       case Instruction::Call: {
521         CallInst *call_inst = dyn_cast<CallInst>(&ii);
522 
523         if (!call_inst) {
524           error.SetErrorToGenericError();
525           error.SetErrorString(interpreter_internal_error);
526           return false;
527         }
528 
529         if (!CanIgnoreCall(call_inst) && !support_function_calls) {
530           LLDB_LOGF(log, "Unsupported instruction: %s",
531                     PrintValue(&ii).c_str());
532           error.SetErrorToGenericError();
533           error.SetErrorString(unsupported_opcode_error);
534           return false;
535         }
536       } break;
537       case Instruction::GetElementPtr:
538         break;
539       case Instruction::ICmp: {
540         ICmpInst *icmp_inst = dyn_cast<ICmpInst>(&ii);
541 
542         if (!icmp_inst) {
543           error.SetErrorToGenericError();
544           error.SetErrorString(interpreter_internal_error);
545           return false;
546         }
547 
548         switch (icmp_inst->getPredicate()) {
549         default: {
550           LLDB_LOGF(log, "Unsupported ICmp predicate: %s",
551                     PrintValue(&ii).c_str());
552 
553           error.SetErrorToGenericError();
554           error.SetErrorString(unsupported_opcode_error);
555           return false;
556         }
557         case CmpInst::ICMP_EQ:
558         case CmpInst::ICMP_NE:
559         case CmpInst::ICMP_UGT:
560         case CmpInst::ICMP_UGE:
561         case CmpInst::ICMP_ULT:
562         case CmpInst::ICMP_ULE:
563         case CmpInst::ICMP_SGT:
564         case CmpInst::ICMP_SGE:
565         case CmpInst::ICMP_SLT:
566         case CmpInst::ICMP_SLE:
567           break;
568         }
569       } break;
570       case Instruction::And:
571       case Instruction::AShr:
572       case Instruction::IntToPtr:
573       case Instruction::PtrToInt:
574       case Instruction::Load:
575       case Instruction::LShr:
576       case Instruction::Mul:
577       case Instruction::Or:
578       case Instruction::Ret:
579       case Instruction::SDiv:
580       case Instruction::SExt:
581       case Instruction::Shl:
582       case Instruction::SRem:
583       case Instruction::Store:
584       case Instruction::Sub:
585       case Instruction::Trunc:
586       case Instruction::UDiv:
587       case Instruction::URem:
588       case Instruction::Xor:
589       case Instruction::ZExt:
590         break;
591       }
592 
593       for (unsigned oi = 0, oe = ii.getNumOperands(); oi != oe; ++oi) {
594         Value *operand = ii.getOperand(oi);
595         Type *operand_type = operand->getType();
596 
597         switch (operand_type->getTypeID()) {
598         default:
599           break;
600         case Type::VectorTyID: {
601           LLDB_LOGF(log, "Unsupported operand type: %s",
602                     PrintType(operand_type).c_str());
603           error.SetErrorString(unsupported_operand_error);
604           return false;
605         }
606         }
607 
608         // The IR interpreter currently doesn't know about
609         // 128-bit integers. As they're not that frequent,
610         // we can just fall back to the JIT rather than
611         // choking.
612         if (operand_type->getPrimitiveSizeInBits() > 64) {
613           LLDB_LOGF(log, "Unsupported operand type: %s",
614                     PrintType(operand_type).c_str());
615           error.SetErrorString(unsupported_operand_error);
616           return false;
617         }
618 
619         if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
620           if (!CanResolveConstant(constant)) {
621             LLDB_LOGF(log, "Unsupported constant: %s",
622                       PrintValue(constant).c_str());
623             error.SetErrorString(unsupported_operand_error);
624             return false;
625           }
626         }
627       }
628     }
629   }
630 
631   return true;
632 }
633 
634 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
635                               llvm::ArrayRef<lldb::addr_t> args,
636                               lldb_private::IRExecutionUnit &execution_unit,
637                               lldb_private::Status &error,
638                               lldb::addr_t stack_frame_bottom,
639                               lldb::addr_t stack_frame_top,
640                               lldb_private::ExecutionContext &exe_ctx) {
641   lldb_private::Log *log(
642       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
643 
644   if (log) {
645     std::string s;
646     raw_string_ostream oss(s);
647 
648     module.print(oss, nullptr);
649 
650     oss.flush();
651 
652     LLDB_LOGF(log, "Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
653               s.c_str());
654   }
655 
656   DataLayout data_layout(&module);
657 
658   InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
659                               stack_frame_top);
660 
661   if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
662     error.SetErrorString("Couldn't allocate stack frame");
663   }
664 
665   int arg_index = 0;
666 
667   for (llvm::Function::arg_iterator ai = function.arg_begin(),
668                                     ae = function.arg_end();
669        ai != ae; ++ai, ++arg_index) {
670     if (args.size() <= static_cast<size_t>(arg_index)) {
671       error.SetErrorString("Not enough arguments passed in to function");
672       return false;
673     }
674 
675     lldb::addr_t ptr = args[arg_index];
676 
677     frame.MakeArgument(&*ai, ptr);
678   }
679 
680   uint32_t num_insts = 0;
681 
682   frame.Jump(&function.front());
683 
684   while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
685     const Instruction *inst = &*frame.m_ii;
686 
687     LLDB_LOGF(log, "Interpreting %s", PrintValue(inst).c_str());
688 
689     switch (inst->getOpcode()) {
690     default:
691       break;
692 
693     case Instruction::Add:
694     case Instruction::Sub:
695     case Instruction::Mul:
696     case Instruction::SDiv:
697     case Instruction::UDiv:
698     case Instruction::SRem:
699     case Instruction::URem:
700     case Instruction::Shl:
701     case Instruction::LShr:
702     case Instruction::AShr:
703     case Instruction::And:
704     case Instruction::Or:
705     case Instruction::Xor: {
706       const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
707 
708       if (!bin_op) {
709         LLDB_LOGF(
710             log,
711             "getOpcode() returns %s, but instruction is not a BinaryOperator",
712             inst->getOpcodeName());
713         error.SetErrorToGenericError();
714         error.SetErrorString(interpreter_internal_error);
715         return false;
716       }
717 
718       Value *lhs = inst->getOperand(0);
719       Value *rhs = inst->getOperand(1);
720 
721       lldb_private::Scalar L;
722       lldb_private::Scalar R;
723 
724       if (!frame.EvaluateValue(L, lhs, module)) {
725         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
726         error.SetErrorToGenericError();
727         error.SetErrorString(bad_value_error);
728         return false;
729       }
730 
731       if (!frame.EvaluateValue(R, rhs, module)) {
732         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
733         error.SetErrorToGenericError();
734         error.SetErrorString(bad_value_error);
735         return false;
736       }
737 
738       lldb_private::Scalar result;
739 
740       switch (inst->getOpcode()) {
741       default:
742         break;
743       case Instruction::Add:
744         result = L + R;
745         break;
746       case Instruction::Mul:
747         result = L * R;
748         break;
749       case Instruction::Sub:
750         result = L - R;
751         break;
752       case Instruction::SDiv:
753         L.MakeSigned();
754         R.MakeSigned();
755         result = L / R;
756         break;
757       case Instruction::UDiv:
758         L.MakeUnsigned();
759         R.MakeUnsigned();
760         result = L / R;
761         break;
762       case Instruction::SRem:
763         L.MakeSigned();
764         R.MakeSigned();
765         result = L % R;
766         break;
767       case Instruction::URem:
768         L.MakeUnsigned();
769         R.MakeUnsigned();
770         result = L % R;
771         break;
772       case Instruction::Shl:
773         result = L << R;
774         break;
775       case Instruction::AShr:
776         result = L >> R;
777         break;
778       case Instruction::LShr:
779         result = L;
780         result.ShiftRightLogical(R);
781         break;
782       case Instruction::And:
783         result = L & R;
784         break;
785       case Instruction::Or:
786         result = L | R;
787         break;
788       case Instruction::Xor:
789         result = L ^ R;
790         break;
791       }
792 
793       frame.AssignValue(inst, result, module);
794 
795       if (log) {
796         LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
797         LLDB_LOGF(log, "  L : %s", frame.SummarizeValue(lhs).c_str());
798         LLDB_LOGF(log, "  R : %s", frame.SummarizeValue(rhs).c_str());
799         LLDB_LOGF(log, "  = : %s", frame.SummarizeValue(inst).c_str());
800       }
801     } break;
802     case Instruction::Alloca: {
803       const AllocaInst *alloca_inst = cast<AllocaInst>(inst);
804 
805       if (alloca_inst->isArrayAllocation()) {
806         LLDB_LOGF(log,
807                   "AllocaInsts are not handled if isArrayAllocation() is true");
808         error.SetErrorToGenericError();
809         error.SetErrorString(unsupported_opcode_error);
810         return false;
811       }
812 
813       // The semantics of Alloca are:
814       //   Create a region R of virtual memory of type T, backed by a data
815       //   buffer
816       //   Create a region P of virtual memory of type T*, backed by a data
817       //   buffer
818       //   Write the virtual address of R into P
819 
820       Type *T = alloca_inst->getAllocatedType();
821       Type *Tptr = alloca_inst->getType();
822 
823       lldb::addr_t R = frame.Malloc(T);
824 
825       if (R == LLDB_INVALID_ADDRESS) {
826         LLDB_LOGF(log, "Couldn't allocate memory for an AllocaInst");
827         error.SetErrorToGenericError();
828         error.SetErrorString(memory_allocation_error);
829         return false;
830       }
831 
832       lldb::addr_t P = frame.Malloc(Tptr);
833 
834       if (P == LLDB_INVALID_ADDRESS) {
835         LLDB_LOGF(log,
836                   "Couldn't allocate the result pointer for an AllocaInst");
837         error.SetErrorToGenericError();
838         error.SetErrorString(memory_allocation_error);
839         return false;
840       }
841 
842       lldb_private::Status write_error;
843 
844       execution_unit.WritePointerToMemory(P, R, write_error);
845 
846       if (!write_error.Success()) {
847         LLDB_LOGF(log, "Couldn't write the result pointer for an AllocaInst");
848         error.SetErrorToGenericError();
849         error.SetErrorString(memory_write_error);
850         lldb_private::Status free_error;
851         execution_unit.Free(P, free_error);
852         execution_unit.Free(R, free_error);
853         return false;
854       }
855 
856       frame.m_values[alloca_inst] = P;
857 
858       if (log) {
859         LLDB_LOGF(log, "Interpreted an AllocaInst");
860         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
861         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
862       }
863     } break;
864     case Instruction::BitCast:
865     case Instruction::ZExt: {
866       const CastInst *cast_inst = cast<CastInst>(inst);
867 
868       Value *source = cast_inst->getOperand(0);
869 
870       lldb_private::Scalar S;
871 
872       if (!frame.EvaluateValue(S, source, module)) {
873         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
874         error.SetErrorToGenericError();
875         error.SetErrorString(bad_value_error);
876         return false;
877       }
878 
879       frame.AssignValue(inst, S, module);
880     } break;
881     case Instruction::SExt: {
882       const CastInst *cast_inst = cast<CastInst>(inst);
883 
884       Value *source = cast_inst->getOperand(0);
885 
886       lldb_private::Scalar S;
887 
888       if (!frame.EvaluateValue(S, source, module)) {
889         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
890         error.SetErrorToGenericError();
891         error.SetErrorString(bad_value_error);
892         return false;
893       }
894 
895       S.MakeSigned();
896 
897       lldb_private::Scalar S_signextend(S.SLongLong());
898 
899       frame.AssignValue(inst, S_signextend, module);
900     } break;
901     case Instruction::Br: {
902       const BranchInst *br_inst = cast<BranchInst>(inst);
903 
904       if (br_inst->isConditional()) {
905         Value *condition = br_inst->getCondition();
906 
907         lldb_private::Scalar C;
908 
909         if (!frame.EvaluateValue(C, condition, module)) {
910           LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(condition).c_str());
911           error.SetErrorToGenericError();
912           error.SetErrorString(bad_value_error);
913           return false;
914         }
915 
916         if (!C.IsZero())
917           frame.Jump(br_inst->getSuccessor(0));
918         else
919           frame.Jump(br_inst->getSuccessor(1));
920 
921         if (log) {
922           LLDB_LOGF(log, "Interpreted a BrInst with a condition");
923           LLDB_LOGF(log, "  cond : %s",
924                     frame.SummarizeValue(condition).c_str());
925         }
926       } else {
927         frame.Jump(br_inst->getSuccessor(0));
928 
929         if (log) {
930           LLDB_LOGF(log, "Interpreted a BrInst with no condition");
931         }
932       }
933     }
934       continue;
935     case Instruction::PHI: {
936       const PHINode *phi_inst = cast<PHINode>(inst);
937       if (!frame.m_prev_bb) {
938         LLDB_LOGF(log,
939                   "Encountered PHI node without having jumped from another "
940                   "basic block");
941         error.SetErrorToGenericError();
942         error.SetErrorString(interpreter_internal_error);
943         return false;
944       }
945 
946       Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
947       lldb_private::Scalar result;
948       if (!frame.EvaluateValue(result, value, module)) {
949         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(value).c_str());
950         error.SetErrorToGenericError();
951         error.SetErrorString(bad_value_error);
952         return false;
953       }
954       frame.AssignValue(inst, result, module);
955 
956       if (log) {
957         LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
958         LLDB_LOGF(log, "  Incoming value : %s",
959                   frame.SummarizeValue(value).c_str());
960       }
961     } break;
962     case Instruction::GetElementPtr: {
963       const GetElementPtrInst *gep_inst = cast<GetElementPtrInst>(inst);
964 
965       const Value *pointer_operand = gep_inst->getPointerOperand();
966       Type *src_elem_ty = gep_inst->getSourceElementType();
967 
968       lldb_private::Scalar P;
969 
970       if (!frame.EvaluateValue(P, pointer_operand, module)) {
971         LLDB_LOGF(log, "Couldn't evaluate %s",
972                   PrintValue(pointer_operand).c_str());
973         error.SetErrorToGenericError();
974         error.SetErrorString(bad_value_error);
975         return false;
976       }
977 
978       typedef SmallVector<Value *, 8> IndexVector;
979       typedef IndexVector::iterator IndexIterator;
980 
981       SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
982                                       gep_inst->idx_end());
983 
984       SmallVector<Value *, 8> const_indices;
985 
986       for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
987            ++ii) {
988         ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
989 
990         if (!constant_index) {
991           lldb_private::Scalar I;
992 
993           if (!frame.EvaluateValue(I, *ii, module)) {
994             LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(*ii).c_str());
995             error.SetErrorToGenericError();
996             error.SetErrorString(bad_value_error);
997             return false;
998           }
999 
1000           LLDB_LOGF(log, "Evaluated constant index %s as %llu",
1001                     PrintValue(*ii).c_str(), I.ULongLong(LLDB_INVALID_ADDRESS));
1002 
1003           constant_index = cast<ConstantInt>(ConstantInt::get(
1004               (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1005         }
1006 
1007         const_indices.push_back(constant_index);
1008       }
1009 
1010       uint64_t offset =
1011           data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1012 
1013       lldb_private::Scalar Poffset = P + offset;
1014 
1015       frame.AssignValue(inst, Poffset, module);
1016 
1017       if (log) {
1018         LLDB_LOGF(log, "Interpreted a GetElementPtrInst");
1019         LLDB_LOGF(log, "  P       : %s",
1020                   frame.SummarizeValue(pointer_operand).c_str());
1021         LLDB_LOGF(log, "  Poffset : %s", frame.SummarizeValue(inst).c_str());
1022       }
1023     } break;
1024     case Instruction::ICmp: {
1025       const ICmpInst *icmp_inst = cast<ICmpInst>(inst);
1026 
1027       CmpInst::Predicate predicate = icmp_inst->getPredicate();
1028 
1029       Value *lhs = inst->getOperand(0);
1030       Value *rhs = inst->getOperand(1);
1031 
1032       lldb_private::Scalar L;
1033       lldb_private::Scalar R;
1034 
1035       if (!frame.EvaluateValue(L, lhs, module)) {
1036         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
1037         error.SetErrorToGenericError();
1038         error.SetErrorString(bad_value_error);
1039         return false;
1040       }
1041 
1042       if (!frame.EvaluateValue(R, rhs, module)) {
1043         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
1044         error.SetErrorToGenericError();
1045         error.SetErrorString(bad_value_error);
1046         return false;
1047       }
1048 
1049       lldb_private::Scalar result;
1050 
1051       switch (predicate) {
1052       default:
1053         return false;
1054       case CmpInst::ICMP_EQ:
1055         result = (L == R);
1056         break;
1057       case CmpInst::ICMP_NE:
1058         result = (L != R);
1059         break;
1060       case CmpInst::ICMP_UGT:
1061         L.MakeUnsigned();
1062         R.MakeUnsigned();
1063         result = (L > R);
1064         break;
1065       case CmpInst::ICMP_UGE:
1066         L.MakeUnsigned();
1067         R.MakeUnsigned();
1068         result = (L >= R);
1069         break;
1070       case CmpInst::ICMP_ULT:
1071         L.MakeUnsigned();
1072         R.MakeUnsigned();
1073         result = (L < R);
1074         break;
1075       case CmpInst::ICMP_ULE:
1076         L.MakeUnsigned();
1077         R.MakeUnsigned();
1078         result = (L <= R);
1079         break;
1080       case CmpInst::ICMP_SGT:
1081         L.MakeSigned();
1082         R.MakeSigned();
1083         result = (L > R);
1084         break;
1085       case CmpInst::ICMP_SGE:
1086         L.MakeSigned();
1087         R.MakeSigned();
1088         result = (L >= R);
1089         break;
1090       case CmpInst::ICMP_SLT:
1091         L.MakeSigned();
1092         R.MakeSigned();
1093         result = (L < R);
1094         break;
1095       case CmpInst::ICMP_SLE:
1096         L.MakeSigned();
1097         R.MakeSigned();
1098         result = (L <= R);
1099         break;
1100       }
1101 
1102       frame.AssignValue(inst, result, module);
1103 
1104       if (log) {
1105         LLDB_LOGF(log, "Interpreted an ICmpInst");
1106         LLDB_LOGF(log, "  L : %s", frame.SummarizeValue(lhs).c_str());
1107         LLDB_LOGF(log, "  R : %s", frame.SummarizeValue(rhs).c_str());
1108         LLDB_LOGF(log, "  = : %s", frame.SummarizeValue(inst).c_str());
1109       }
1110     } break;
1111     case Instruction::IntToPtr: {
1112       const IntToPtrInst *int_to_ptr_inst = cast<IntToPtrInst>(inst);
1113 
1114       Value *src_operand = int_to_ptr_inst->getOperand(0);
1115 
1116       lldb_private::Scalar I;
1117 
1118       if (!frame.EvaluateValue(I, src_operand, module)) {
1119         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1120         error.SetErrorToGenericError();
1121         error.SetErrorString(bad_value_error);
1122         return false;
1123       }
1124 
1125       frame.AssignValue(inst, I, module);
1126 
1127       if (log) {
1128         LLDB_LOGF(log, "Interpreted an IntToPtr");
1129         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1130         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1131       }
1132     } break;
1133     case Instruction::PtrToInt: {
1134       const PtrToIntInst *ptr_to_int_inst = cast<PtrToIntInst>(inst);
1135 
1136       Value *src_operand = ptr_to_int_inst->getOperand(0);
1137 
1138       lldb_private::Scalar I;
1139 
1140       if (!frame.EvaluateValue(I, src_operand, module)) {
1141         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1142         error.SetErrorToGenericError();
1143         error.SetErrorString(bad_value_error);
1144         return false;
1145       }
1146 
1147       frame.AssignValue(inst, I, module);
1148 
1149       if (log) {
1150         LLDB_LOGF(log, "Interpreted a PtrToInt");
1151         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1152         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1153       }
1154     } break;
1155     case Instruction::Trunc: {
1156       const TruncInst *trunc_inst = cast<TruncInst>(inst);
1157 
1158       Value *src_operand = trunc_inst->getOperand(0);
1159 
1160       lldb_private::Scalar I;
1161 
1162       if (!frame.EvaluateValue(I, src_operand, module)) {
1163         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1164         error.SetErrorToGenericError();
1165         error.SetErrorString(bad_value_error);
1166         return false;
1167       }
1168 
1169       frame.AssignValue(inst, I, module);
1170 
1171       if (log) {
1172         LLDB_LOGF(log, "Interpreted a Trunc");
1173         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1174         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1175       }
1176     } break;
1177     case Instruction::Load: {
1178       const LoadInst *load_inst = cast<LoadInst>(inst);
1179 
1180       // The semantics of Load are:
1181       //   Create a region D that will contain the loaded data
1182       //   Resolve the region P containing a pointer
1183       //   Dereference P to get the region R that the data should be loaded from
1184       //   Transfer a unit of type type(D) from R to D
1185 
1186       const Value *pointer_operand = load_inst->getPointerOperand();
1187 
1188       Type *pointer_ty = pointer_operand->getType();
1189       PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1190       if (!pointer_ptr_ty) {
1191         LLDB_LOGF(log, "getPointerOperand()->getType() is not a PointerType");
1192         error.SetErrorToGenericError();
1193         error.SetErrorString(interpreter_internal_error);
1194         return false;
1195       }
1196       Type *target_ty = pointer_ptr_ty->getElementType();
1197 
1198       lldb::addr_t D = frame.ResolveValue(load_inst, module);
1199       lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1200 
1201       if (D == LLDB_INVALID_ADDRESS) {
1202         LLDB_LOGF(log, "LoadInst's value doesn't resolve to anything");
1203         error.SetErrorToGenericError();
1204         error.SetErrorString(bad_value_error);
1205         return false;
1206       }
1207 
1208       if (P == LLDB_INVALID_ADDRESS) {
1209         LLDB_LOGF(log, "LoadInst's pointer doesn't resolve to anything");
1210         error.SetErrorToGenericError();
1211         error.SetErrorString(bad_value_error);
1212         return false;
1213       }
1214 
1215       lldb::addr_t R;
1216       lldb_private::Status read_error;
1217       execution_unit.ReadPointerFromMemory(&R, P, read_error);
1218 
1219       if (!read_error.Success()) {
1220         LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1221         error.SetErrorToGenericError();
1222         error.SetErrorString(memory_read_error);
1223         return false;
1224       }
1225 
1226       size_t target_size = data_layout.getTypeStoreSize(target_ty);
1227       lldb_private::DataBufferHeap buffer(target_size, 0);
1228 
1229       read_error.Clear();
1230       execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1231                                 read_error);
1232       if (!read_error.Success()) {
1233         LLDB_LOGF(log, "Couldn't read from a region on behalf of a LoadInst");
1234         error.SetErrorToGenericError();
1235         error.SetErrorString(memory_read_error);
1236         return false;
1237       }
1238 
1239       lldb_private::Status write_error;
1240       execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1241                                  write_error);
1242       if (!write_error.Success()) {
1243         LLDB_LOGF(log, "Couldn't write to a region on behalf of a LoadInst");
1244         error.SetErrorToGenericError();
1245         error.SetErrorString(memory_read_error);
1246         return false;
1247       }
1248 
1249       if (log) {
1250         LLDB_LOGF(log, "Interpreted a LoadInst");
1251         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
1252         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
1253         LLDB_LOGF(log, "  D : 0x%" PRIx64, D);
1254       }
1255     } break;
1256     case Instruction::Ret: {
1257       return true;
1258     }
1259     case Instruction::Store: {
1260       const StoreInst *store_inst = cast<StoreInst>(inst);
1261 
1262       // The semantics of Store are:
1263       //   Resolve the region D containing the data to be stored
1264       //   Resolve the region P containing a pointer
1265       //   Dereference P to get the region R that the data should be stored in
1266       //   Transfer a unit of type type(D) from D to R
1267 
1268       const Value *value_operand = store_inst->getValueOperand();
1269       const Value *pointer_operand = store_inst->getPointerOperand();
1270 
1271       Type *pointer_ty = pointer_operand->getType();
1272       PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1273       if (!pointer_ptr_ty)
1274         return false;
1275       Type *target_ty = pointer_ptr_ty->getElementType();
1276 
1277       lldb::addr_t D = frame.ResolveValue(value_operand, module);
1278       lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1279 
1280       if (D == LLDB_INVALID_ADDRESS) {
1281         LLDB_LOGF(log, "StoreInst's value doesn't resolve to anything");
1282         error.SetErrorToGenericError();
1283         error.SetErrorString(bad_value_error);
1284         return false;
1285       }
1286 
1287       if (P == LLDB_INVALID_ADDRESS) {
1288         LLDB_LOGF(log, "StoreInst's pointer doesn't resolve to anything");
1289         error.SetErrorToGenericError();
1290         error.SetErrorString(bad_value_error);
1291         return false;
1292       }
1293 
1294       lldb::addr_t R;
1295       lldb_private::Status read_error;
1296       execution_unit.ReadPointerFromMemory(&R, P, read_error);
1297 
1298       if (!read_error.Success()) {
1299         LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1300         error.SetErrorToGenericError();
1301         error.SetErrorString(memory_read_error);
1302         return false;
1303       }
1304 
1305       size_t target_size = data_layout.getTypeStoreSize(target_ty);
1306       lldb_private::DataBufferHeap buffer(target_size, 0);
1307 
1308       read_error.Clear();
1309       execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1310                                 read_error);
1311       if (!read_error.Success()) {
1312         LLDB_LOGF(log, "Couldn't read from a region on behalf of a StoreInst");
1313         error.SetErrorToGenericError();
1314         error.SetErrorString(memory_read_error);
1315         return false;
1316       }
1317 
1318       lldb_private::Status write_error;
1319       execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1320                                  write_error);
1321       if (!write_error.Success()) {
1322         LLDB_LOGF(log, "Couldn't write to a region on behalf of a StoreInst");
1323         error.SetErrorToGenericError();
1324         error.SetErrorString(memory_write_error);
1325         return false;
1326       }
1327 
1328       if (log) {
1329         LLDB_LOGF(log, "Interpreted a StoreInst");
1330         LLDB_LOGF(log, "  D : 0x%" PRIx64, D);
1331         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
1332         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
1333       }
1334     } break;
1335     case Instruction::Call: {
1336       const CallInst *call_inst = cast<CallInst>(inst);
1337 
1338       if (CanIgnoreCall(call_inst))
1339         break;
1340 
1341       // Get the return type
1342       llvm::Type *returnType = call_inst->getType();
1343       if (returnType == nullptr) {
1344         error.SetErrorToGenericError();
1345         error.SetErrorString("unable to access return type");
1346         return false;
1347       }
1348 
1349       // Work with void, integer and pointer return types
1350       if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1351           !returnType->isPointerTy()) {
1352         error.SetErrorToGenericError();
1353         error.SetErrorString("return type is not supported");
1354         return false;
1355       }
1356 
1357       // Check we can actually get a thread
1358       if (exe_ctx.GetThreadPtr() == nullptr) {
1359         error.SetErrorToGenericError();
1360         error.SetErrorStringWithFormat("unable to acquire thread");
1361         return false;
1362       }
1363 
1364       // Make sure we have a valid process
1365       if (!exe_ctx.GetProcessPtr()) {
1366         error.SetErrorToGenericError();
1367         error.SetErrorStringWithFormat("unable to get the process");
1368         return false;
1369       }
1370 
1371       // Find the address of the callee function
1372       lldb_private::Scalar I;
1373       const llvm::Value *val = call_inst->getCalledValue();
1374 
1375       if (!frame.EvaluateValue(I, val, module)) {
1376         error.SetErrorToGenericError();
1377         error.SetErrorString("unable to get address of function");
1378         return false;
1379       }
1380       lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1381 
1382       lldb_private::DiagnosticManager diagnostics;
1383       lldb_private::EvaluateExpressionOptions options;
1384 
1385       // We generally receive a function pointer which we must dereference
1386       llvm::Type *prototype = val->getType();
1387       if (!prototype->isPointerTy()) {
1388         error.SetErrorToGenericError();
1389         error.SetErrorString("call need function pointer");
1390         return false;
1391       }
1392 
1393       // Dereference the function pointer
1394       prototype = prototype->getPointerElementType();
1395       if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1396         error.SetErrorToGenericError();
1397         error.SetErrorString("call need function pointer");
1398         return false;
1399       }
1400 
1401       // Find number of arguments
1402       const int numArgs = call_inst->getNumArgOperands();
1403 
1404       // We work with a fixed array of 16 arguments which is our upper limit
1405       static lldb_private::ABI::CallArgument rawArgs[16];
1406       if (numArgs >= 16) {
1407         error.SetErrorToGenericError();
1408         error.SetErrorStringWithFormat("function takes too many arguments");
1409         return false;
1410       }
1411 
1412       // Push all function arguments to the argument list that will be passed
1413       // to the call function thread plan
1414       for (int i = 0; i < numArgs; i++) {
1415         // Get details of this argument
1416         llvm::Value *arg_op = call_inst->getArgOperand(i);
1417         llvm::Type *arg_ty = arg_op->getType();
1418 
1419         // Ensure that this argument is an supported type
1420         if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1421           error.SetErrorToGenericError();
1422           error.SetErrorStringWithFormat("argument %d must be integer type", i);
1423           return false;
1424         }
1425 
1426         // Extract the arguments value
1427         lldb_private::Scalar tmp_op = 0;
1428         if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1429           error.SetErrorToGenericError();
1430           error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1431           return false;
1432         }
1433 
1434         // Check if this is a string literal or constant string pointer
1435         if (arg_ty->isPointerTy()) {
1436           lldb::addr_t addr = tmp_op.ULongLong();
1437           size_t dataSize = 0;
1438 
1439           bool Success = execution_unit.GetAllocSize(addr, dataSize);
1440           (void)Success;
1441           assert(Success &&
1442                  "unable to locate host data for transfer to device");
1443           // Create the required buffer
1444           rawArgs[i].size = dataSize;
1445           rawArgs[i].data_up.reset(new uint8_t[dataSize + 1]);
1446 
1447           // Read string from host memory
1448           execution_unit.ReadMemory(rawArgs[i].data_up.get(), addr, dataSize,
1449                                     error);
1450           assert(!error.Fail() &&
1451                  "we have failed to read the string from memory");
1452 
1453           // Add null terminator
1454           rawArgs[i].data_up[dataSize] = '\0';
1455           rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
1456         } else /* if ( arg_ty->isPointerTy() ) */
1457         {
1458           rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1459           // Get argument size in bytes
1460           rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1461           // Push value into argument list for thread plan
1462           rawArgs[i].value = tmp_op.ULongLong();
1463         }
1464       }
1465 
1466       // Pack the arguments into an llvm::array
1467       llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1468 
1469       // Setup a thread plan to call the target function
1470       lldb::ThreadPlanSP call_plan_sp(
1471           new lldb_private::ThreadPlanCallFunctionUsingABI(
1472               exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1473               options));
1474 
1475       // Check if the plan is valid
1476       lldb_private::StreamString ss;
1477       if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1478         error.SetErrorToGenericError();
1479         error.SetErrorStringWithFormat(
1480             "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1481             I.ULongLong());
1482         return false;
1483       }
1484 
1485       exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1486 
1487       // Execute the actual function call thread plan
1488       lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1489           exe_ctx, call_plan_sp, options, diagnostics);
1490 
1491       // Check that the thread plan completed successfully
1492       if (res != lldb::ExpressionResults::eExpressionCompleted) {
1493         error.SetErrorToGenericError();
1494         error.SetErrorStringWithFormat("ThreadPlanCallFunctionUsingABI failed");
1495         return false;
1496       }
1497 
1498       exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1499 
1500       // Void return type
1501       if (returnType->isVoidTy()) {
1502         // Cant assign to void types, so we leave the frame untouched
1503       } else
1504           // Integer or pointer return type
1505           if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1506         // Get the encapsulated return value
1507         lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1508 
1509         lldb_private::Scalar returnVal = -1;
1510         lldb_private::ValueObject *vobj = retVal.get();
1511 
1512         // Check if the return value is valid
1513         if (vobj == nullptr || retVal.empty()) {
1514           error.SetErrorToGenericError();
1515           error.SetErrorStringWithFormat("unable to get the return value");
1516           return false;
1517         }
1518 
1519         // Extract the return value as a integer
1520         lldb_private::Value &value = vobj->GetValue();
1521         returnVal = value.GetScalar();
1522 
1523         // Push the return value as the result
1524         frame.AssignValue(inst, returnVal, module);
1525       }
1526     } break;
1527     }
1528 
1529     ++frame.m_ii;
1530   }
1531 
1532   if (num_insts >= 4096) {
1533     error.SetErrorToGenericError();
1534     error.SetErrorString(infinite_loop_error);
1535     return false;
1536   }
1537 
1538   return false;
1539 }
1540