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