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