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/DataEncoder.h"
11 #include "lldb/Core/Log.h"
12 #include "lldb/Core/ValueObjectConstResult.h"
13 #include "lldb/Expression/ClangExpressionDeclMap.h"
14 #include "lldb/Expression/ClangExpressionVariable.h"
15 #include "lldb/Expression/IRForTarget.h"
16 #include "lldb/Expression/IRInterpreter.h"
17 
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/IR/DataLayout.h"
24 
25 #include <map>
26 
27 using namespace llvm;
28 
29 IRInterpreter::IRInterpreter(lldb_private::ClangExpressionDeclMap &decl_map,
30                                            lldb_private::Stream *error_stream) :
31     m_decl_map(decl_map)
32 {
33 
34 }
35 
36 IRInterpreter::~IRInterpreter()
37 {
38 
39 }
40 
41 static std::string
42 PrintValue(const Value *value, bool truncate = false)
43 {
44     std::string s;
45     raw_string_ostream rso(s);
46     value->print(rso);
47     rso.flush();
48     if (truncate)
49         s.resize(s.length() - 1);
50 
51     size_t offset;
52     while ((offset = s.find('\n')) != s.npos)
53         s.erase(offset, 1);
54     while (s[0] == ' ' || s[0] == '\t')
55         s.erase(0, 1);
56 
57     return s;
58 }
59 
60 static std::string
61 PrintType(const Type *type, bool truncate = false)
62 {
63     std::string s;
64     raw_string_ostream rso(s);
65     type->print(rso);
66     rso.flush();
67     if (truncate)
68         s.resize(s.length() - 1);
69     return s;
70 }
71 
72 typedef STD_SHARED_PTR(lldb_private::DataEncoder) DataEncoderSP;
73 typedef STD_SHARED_PTR(lldb_private::DataExtractor) DataExtractorSP;
74 
75 class Memory
76 {
77 public:
78     typedef uint32_t                    index_t;
79 
80     struct Allocation
81     {
82         // m_virtual_address is always the address of the variable in the virtual memory
83         // space provided by Memory.
84         //
85         // m_origin is always non-NULL and describes the source of the data (possibly
86         // m_data if this allocation is the authoritative source).
87         //
88         // Possible value configurations:
89         //
90         // Allocation type  getValueType()          getContextType()            m_origin->GetScalar()       m_data
91         // =========================================================================================================================
92         // FileAddress      eValueTypeFileAddress   eContextTypeInvalid         A location in a binary      NULL
93         //                                                                      image
94         //
95         // LoadAddress      eValueTypeLoadAddress   eContextTypeInvalid         A location in the target's  NULL
96         //                                                                      virtual memory
97         //
98         // Alloca           eValueTypeHostAddress   eContextTypeInvalid         == m_data->GetBytes()       Deleted at end of
99         //                                                                                                  execution
100         //
101         // PersistentVar    eValueTypeHostAddress   eContextTypeClangType       A persistent variable's     NULL
102         //                                                                      location in LLDB's memory
103         //
104         // Register         [ignored]               eContextTypeRegister        [ignored]                   Flushed to the register
105         //                                                                                                  at the end of execution
106 
107         lldb::addr_t        m_virtual_address;
108         size_t              m_extent;
109         lldb_private::Value m_origin;
110         lldb::DataBufferSP  m_data;
111 
112         Allocation (lldb::addr_t virtual_address,
113                     size_t extent,
114                     lldb::DataBufferSP data) :
115             m_virtual_address(virtual_address),
116             m_extent(extent),
117             m_data(data)
118         {
119         }
120 
121         Allocation (const Allocation &allocation) :
122             m_virtual_address(allocation.m_virtual_address),
123             m_extent(allocation.m_extent),
124             m_origin(allocation.m_origin),
125             m_data(allocation.m_data)
126         {
127         }
128     };
129 
130     typedef STD_SHARED_PTR(Allocation)  AllocationSP;
131 
132     struct Region
133     {
134         AllocationSP m_allocation;
135         uint64_t m_base;
136         uint64_t m_extent;
137 
138         Region () :
139             m_allocation(),
140             m_base(0),
141             m_extent(0)
142         {
143         }
144 
145         Region (AllocationSP allocation, uint64_t base, uint64_t extent) :
146             m_allocation(allocation),
147             m_base(base),
148             m_extent(extent)
149         {
150         }
151 
152         Region (const Region &region) :
153             m_allocation(region.m_allocation),
154             m_base(region.m_base),
155             m_extent(region.m_extent)
156         {
157         }
158 
159         bool IsValid ()
160         {
161             return (bool) m_allocation;
162         }
163 
164         bool IsInvalid ()
165         {
166             return !m_allocation;
167         }
168     };
169 
170     typedef std::vector <AllocationSP>          MemoryMap;
171 
172 private:
173     lldb::addr_t        m_addr_base;
174     lldb::addr_t        m_addr_max;
175     MemoryMap           m_memory;
176     lldb::ByteOrder     m_byte_order;
177     lldb::addr_t        m_addr_byte_size;
178     DataLayout         &m_target_data;
179 
180     lldb_private::ClangExpressionDeclMap   &m_decl_map;
181 
182     MemoryMap::iterator LookupInternal (lldb::addr_t addr)
183     {
184         for (MemoryMap::iterator i = m_memory.begin(), e = m_memory.end();
185              i != e;
186              ++i)
187         {
188             if ((*i)->m_virtual_address <= addr &&
189                 (*i)->m_virtual_address + (*i)->m_extent > addr)
190                 return i;
191         }
192 
193         return m_memory.end();
194     }
195 
196 public:
197     Memory (DataLayout &target_data,
198             lldb_private::ClangExpressionDeclMap &decl_map,
199             lldb::addr_t alloc_start,
200             lldb::addr_t alloc_max) :
201         m_addr_base(alloc_start),
202         m_addr_max(alloc_max),
203         m_target_data(target_data),
204         m_decl_map(decl_map)
205     {
206         m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle : lldb::eByteOrderBig);
207         m_addr_byte_size = (target_data.getPointerSize(0));
208     }
209 
210     Region Malloc (size_t size, size_t align)
211     {
212         lldb::DataBufferSP data(new lldb_private::DataBufferHeap(size, 0));
213 
214         if (data)
215         {
216             index_t index = m_memory.size();
217 
218             const size_t mask = (align - 1);
219 
220             m_addr_base += mask;
221             m_addr_base &= ~mask;
222 
223             if (m_addr_base + size < m_addr_base ||
224                 m_addr_base + size > m_addr_max)
225                 return Region();
226 
227             uint64_t base = m_addr_base;
228 
229             m_memory.push_back(AllocationSP(new Allocation(base, size, data)));
230 
231             m_addr_base += size;
232 
233             AllocationSP alloc = m_memory[index];
234 
235             alloc->m_origin.GetScalar() = (unsigned long long)data->GetBytes();
236             alloc->m_origin.SetContext(lldb_private::Value::eContextTypeInvalid, NULL);
237             alloc->m_origin.SetValueType(lldb_private::Value::eValueTypeHostAddress);
238 
239             return Region(alloc, base, size);
240         }
241 
242         return Region();
243     }
244 
245     Region Malloc (Type *type)
246     {
247         return Malloc (m_target_data.getTypeAllocSize(type),
248                        m_target_data.getPrefTypeAlignment(type));
249     }
250 
251     Region Place (Type *type, lldb::addr_t base, lldb_private::Value &value)
252     {
253         index_t index = m_memory.size();
254         size_t size = m_target_data.getTypeAllocSize(type);
255 
256         m_memory.push_back(AllocationSP(new Allocation(base, size, lldb::DataBufferSP())));
257 
258         AllocationSP alloc = m_memory[index];
259 
260         alloc->m_origin = value;
261 
262         return Region(alloc, base, size);
263     }
264 
265     void Free (lldb::addr_t addr)
266     {
267         MemoryMap::iterator i = LookupInternal (addr);
268 
269         if (i != m_memory.end())
270             m_memory.erase(i);
271     }
272 
273     Region Lookup (lldb::addr_t addr, Type *type)
274     {
275         MemoryMap::iterator i = LookupInternal(addr);
276 
277         if (i == m_memory.end() || !type->isSized())
278             return Region();
279 
280         size_t size = m_target_data.getTypeStoreSize(type);
281 
282         return Region(*i, addr, size);
283     }
284 
285     DataEncoderSP GetEncoder (Region region)
286     {
287         if (region.m_allocation->m_origin.GetValueType() != lldb_private::Value::eValueTypeHostAddress)
288             return DataEncoderSP();
289 
290         lldb::DataBufferSP buffer = region.m_allocation->m_data;
291 
292         if (!buffer)
293             return DataEncoderSP();
294 
295         size_t base_offset = (size_t)(region.m_base - region.m_allocation->m_virtual_address);
296 
297         return DataEncoderSP(new lldb_private::DataEncoder(buffer->GetBytes() + base_offset, region.m_extent, m_byte_order, m_addr_byte_size));
298     }
299 
300     DataExtractorSP GetExtractor (Region region)
301     {
302         if (region.m_allocation->m_origin.GetValueType() != lldb_private::Value::eValueTypeHostAddress)
303             return DataExtractorSP();
304 
305         lldb::DataBufferSP buffer = region.m_allocation->m_data;
306         size_t base_offset = (size_t)(region.m_base - region.m_allocation->m_virtual_address);
307 
308         if (buffer)
309             return DataExtractorSP(new lldb_private::DataExtractor(buffer->GetBytes() + base_offset, region.m_extent, m_byte_order, m_addr_byte_size));
310         else
311             return DataExtractorSP(new lldb_private::DataExtractor((uint8_t*)region.m_allocation->m_origin.GetScalar().ULongLong() + base_offset, region.m_extent, m_byte_order, m_addr_byte_size));
312     }
313 
314     lldb_private::Value GetAccessTarget(lldb::addr_t addr)
315     {
316         MemoryMap::iterator i = LookupInternal(addr);
317 
318         if (i == m_memory.end())
319             return lldb_private::Value();
320 
321         lldb_private::Value target = (*i)->m_origin;
322 
323         if (target.GetContextType() == lldb_private::Value::eContextTypeRegisterInfo)
324         {
325             target.SetContext(lldb_private::Value::eContextTypeInvalid, NULL);
326             target.SetValueType(lldb_private::Value::eValueTypeHostAddress);
327             target.GetScalar() = (unsigned long long)(*i)->m_data->GetBytes();
328         }
329 
330         target.GetScalar() += (addr - (*i)->m_virtual_address);
331 
332         return target;
333     }
334 
335     bool Write (lldb::addr_t addr, const uint8_t *data, size_t length)
336     {
337         lldb_private::Value target = GetAccessTarget(addr);
338 
339         return m_decl_map.WriteTarget(target, data, length);
340     }
341 
342     bool Read (uint8_t *data, lldb::addr_t addr, size_t length)
343     {
344         lldb_private::Value source = GetAccessTarget(addr);
345 
346         return m_decl_map.ReadTarget(data, source, length);
347     }
348 
349     bool WriteToRawPtr (lldb::addr_t addr, const uint8_t *data, size_t length)
350     {
351         lldb_private::Value target = m_decl_map.WrapBareAddress(addr);
352 
353         return m_decl_map.WriteTarget(target, data, length);
354     }
355 
356     bool ReadFromRawPtr (uint8_t *data, lldb::addr_t addr, size_t length)
357     {
358         lldb_private::Value source = m_decl_map.WrapBareAddress(addr);
359 
360         return m_decl_map.ReadTarget(data, source, length);
361     }
362 
363     std::string PrintData (lldb::addr_t addr, size_t length)
364     {
365         lldb_private::Value target = GetAccessTarget(addr);
366 
367         lldb_private::DataBufferHeap buf(length, 0);
368 
369         if (!m_decl_map.ReadTarget(buf.GetBytes(), target, length))
370             return std::string("<couldn't read data>");
371 
372         lldb_private::StreamString ss;
373 
374         for (size_t i = 0; i < length; i++)
375         {
376             if ((!(i & 0xf)) && i)
377                 ss.Printf("%02hhx - ", buf.GetBytes()[i]);
378             else
379                 ss.Printf("%02hhx ", buf.GetBytes()[i]);
380         }
381 
382         return ss.GetString();
383     }
384 
385     std::string SummarizeRegion (Region &region)
386     {
387         lldb_private::StreamString ss;
388 
389         lldb_private::Value base = GetAccessTarget(region.m_base);
390 
391         ss.Printf("%" PRIx64 " [%s - %s %llx]",
392                   region.m_base,
393                   lldb_private::Value::GetValueTypeAsCString(base.GetValueType()),
394                   lldb_private::Value::GetContextTypeAsCString(base.GetContextType()),
395                   base.GetScalar().ULongLong());
396 
397         ss.Printf(" %s", PrintData(region.m_base, region.m_extent).c_str());
398 
399         return ss.GetString();
400     }
401 };
402 
403 class InterpreterStackFrame
404 {
405 public:
406     typedef std::map <const Value*, Memory::Region> ValueMap;
407 
408     ValueMap                                m_values;
409     Memory                                 &m_memory;
410     DataLayout                             &m_target_data;
411     lldb_private::ClangExpressionDeclMap   &m_decl_map;
412     const BasicBlock                       *m_bb;
413     BasicBlock::const_iterator              m_ii;
414     BasicBlock::const_iterator              m_ie;
415 
416     lldb::ByteOrder                         m_byte_order;
417     size_t                                  m_addr_byte_size;
418 
419     InterpreterStackFrame (DataLayout &target_data,
420                            Memory &memory,
421                            lldb_private::ClangExpressionDeclMap &decl_map) :
422         m_memory (memory),
423         m_target_data (target_data),
424         m_decl_map (decl_map)
425     {
426         m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle : lldb::eByteOrderBig);
427         m_addr_byte_size = (target_data.getPointerSize(0));
428     }
429 
430     void Jump (const BasicBlock *bb)
431     {
432         m_bb = bb;
433         m_ii = m_bb->begin();
434         m_ie = m_bb->end();
435     }
436 
437     bool Cache (Memory::AllocationSP allocation, Type *type)
438     {
439         if (allocation->m_origin.GetContextType() != lldb_private::Value::eContextTypeRegisterInfo)
440             return false;
441 
442         return m_decl_map.ReadTarget(allocation->m_data->GetBytes(), allocation->m_origin, allocation->m_data->GetByteSize());
443     }
444 
445     std::string SummarizeValue (const Value *value)
446     {
447         lldb_private::StreamString ss;
448 
449         ss.Printf("%s", PrintValue(value).c_str());
450 
451         ValueMap::iterator i = m_values.find(value);
452 
453         if (i != m_values.end())
454         {
455             Memory::Region region = i->second;
456 
457             ss.Printf(" %s", m_memory.SummarizeRegion(region).c_str());
458         }
459 
460         return ss.GetString();
461     }
462 
463     bool AssignToMatchType (lldb_private::Scalar &scalar, uint64_t u64value, Type *type)
464     {
465         size_t type_size = m_target_data.getTypeStoreSize(type);
466 
467         switch (type_size)
468         {
469         case 1:
470             scalar = (uint8_t)u64value;
471             break;
472         case 2:
473             scalar = (uint16_t)u64value;
474             break;
475         case 4:
476             scalar = (uint32_t)u64value;
477             break;
478         case 8:
479             scalar = (uint64_t)u64value;
480             break;
481         default:
482             return false;
483         }
484 
485         return true;
486     }
487 
488     bool EvaluateValue (lldb_private::Scalar &scalar, const Value *value, Module &module)
489     {
490         const Constant *constant = dyn_cast<Constant>(value);
491 
492         if (constant)
493         {
494             if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant))
495             {
496                 return AssignToMatchType(scalar, constant_int->getLimitedValue(), value->getType());
497             }
498         }
499         else
500         {
501             Memory::Region region = ResolveValue(value, module);
502             DataExtractorSP value_extractor = m_memory.GetExtractor(region);
503 
504             if (!value_extractor)
505                 return false;
506 
507             size_t value_size = m_target_data.getTypeStoreSize(value->getType());
508 
509             lldb::offset_t offset = 0;
510             uint64_t u64value = value_extractor->GetMaxU64(&offset, value_size);
511 
512             return AssignToMatchType(scalar, u64value, value->getType());
513         }
514 
515         return false;
516     }
517 
518     bool AssignValue (const Value *value, lldb_private::Scalar &scalar, Module &module)
519     {
520         Memory::Region region = ResolveValue (value, module);
521 
522         lldb_private::Scalar cast_scalar;
523 
524         if (!AssignToMatchType(cast_scalar, scalar.GetRawBits64(0), value->getType()))
525             return false;
526 
527         lldb_private::DataBufferHeap buf(cast_scalar.GetByteSize(), 0);
528 
529         lldb_private::Error err;
530 
531         if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(), m_byte_order, err))
532             return false;
533 
534         DataEncoderSP region_encoder = m_memory.GetEncoder(region);
535 
536         memcpy(region_encoder->GetDataStart(), buf.GetBytes(), buf.GetByteSize());
537 
538         return true;
539     }
540 
541     bool ResolveConstantValue (APInt &value, const Constant *constant)
542     {
543         if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant))
544         {
545             value = constant_int->getValue();
546             return true;
547         }
548         else if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant))
549         {
550             value = constant_fp->getValueAPF().bitcastToAPInt();
551             return true;
552         }
553         else if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
554         {
555             switch (constant_expr->getOpcode())
556             {
557                 default:
558                     return false;
559                 case Instruction::IntToPtr:
560                 case Instruction::PtrToInt:
561                 case Instruction::BitCast:
562                     return ResolveConstantValue(value, constant_expr->getOperand(0));
563                 case Instruction::GetElementPtr:
564                 {
565                     ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
566                     ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
567 
568                     Constant *base = dyn_cast<Constant>(*op_cursor);
569 
570                     if (!base)
571                         return false;
572 
573                     if (!ResolveConstantValue(value, base))
574                         return false;
575 
576                     op_cursor++;
577 
578                     if (op_cursor == op_end)
579                         return true; // no offset to apply!
580 
581                     SmallVector <Value *, 8> indices (op_cursor, op_end);
582 
583                     uint64_t offset = m_target_data.getIndexedOffset(base->getType(), indices);
584 
585                     const bool is_signed = true;
586                     value += APInt(value.getBitWidth(), offset, is_signed);
587 
588                     return true;
589                 }
590             }
591         }
592 
593         return false;
594     }
595 
596     bool ResolveConstant (Memory::Region &region, const Constant *constant)
597     {
598         APInt resolved_value;
599 
600         if (!ResolveConstantValue(resolved_value, constant))
601             return false;
602 
603         const uint64_t *raw_data = resolved_value.getRawData();
604 
605         size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
606         return m_memory.Write(region.m_base, (const uint8_t*)raw_data, constant_size);
607     }
608 
609     Memory::Region ResolveValue (const Value *value, Module &module)
610     {
611         ValueMap::iterator i = m_values.find(value);
612 
613         if (i != m_values.end())
614             return i->second;
615 
616         const GlobalValue *global_value = dyn_cast<GlobalValue>(value);
617 
618         // If the variable is indirected through the argument
619         // array then we need to build an extra level of indirection
620         // for it.  This is the default; only magic arguments like
621         // "this", "self", and "_cmd" are direct.
622         bool variable_is_this = false;
623 
624         // Attempt to resolve the value using the program's data.
625         // If it is, the values to be created are:
626         //
627         // data_region - a region of memory in which the variable's data resides.
628         // ref_region - a region of memory in which its address (i.e., &var) resides.
629         //   In the JIT case, this region would be a member of the struct passed in.
630         // pointer_region - a region of memory in which the address of the pointer
631         //   resides.  This is an IR-level variable.
632         do
633         {
634             lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
635 
636             lldb_private::Value resolved_value;
637             lldb_private::ClangExpressionVariable::FlagType flags = 0;
638 
639             if (global_value)
640             {
641                 clang::NamedDecl *decl = IRForTarget::DeclForGlobal(global_value, &module);
642 
643                 if (!decl)
644                     break;
645 
646                 if (isa<clang::FunctionDecl>(decl))
647                 {
648                     if (log)
649                         log->Printf("The interpreter does not handle function pointers at the moment");
650 
651                     return Memory::Region();
652                 }
653 
654                 resolved_value = m_decl_map.LookupDecl(decl, flags);
655             }
656             else
657             {
658                 // Special-case "this", "self", and "_cmd"
659 
660                 std::string name_str = value->getName().str();
661 
662                 if (name_str == "this" ||
663                     name_str == "self" ||
664                     name_str == "_cmd")
665                     resolved_value = m_decl_map.GetSpecialValue(lldb_private::ConstString(name_str.c_str()));
666 
667                 variable_is_this = true;
668             }
669 
670             if (resolved_value.GetScalar().GetType() != lldb_private::Scalar::e_void)
671             {
672                 if (resolved_value.GetContextType() == lldb_private::Value::eContextTypeRegisterInfo)
673                 {
674                     if (variable_is_this)
675                     {
676                         Memory::Region data_region = m_memory.Place(value->getType(), resolved_value.GetScalar().ULongLong(), resolved_value);
677 
678                         lldb_private::Value origin;
679 
680                         origin.SetValueType(lldb_private::Value::eValueTypeLoadAddress);
681                         origin.SetContext(lldb_private::Value::eContextTypeInvalid, NULL);
682                         origin.GetScalar() = resolved_value.GetScalar();
683 
684                         data_region.m_allocation->m_origin = origin;
685 
686                         Memory::Region ref_region = m_memory.Malloc(value->getType());
687 
688                         if (ref_region.IsInvalid())
689                             return Memory::Region();
690 
691                         DataEncoderSP ref_encoder = m_memory.GetEncoder(ref_region);
692 
693                         if (ref_encoder->PutAddress(0, data_region.m_base) == UINT32_MAX)
694                             return Memory::Region();
695 
696                         if (log)
697                         {
698                             log->Printf("Made an allocation for \"this\" register variable %s", PrintValue(value).c_str());
699                             log->Printf("  Data region    : %llx", (unsigned long long)data_region.m_base);
700                             log->Printf("  Ref region     : %llx", (unsigned long long)ref_region.m_base);
701                         }
702 
703                         m_values[value] = ref_region;
704                         return ref_region;
705                     }
706                     else if (flags & lldb_private::ClangExpressionVariable::EVBareRegister)
707                     {
708                         lldb_private::RegisterInfo *reg_info = resolved_value.GetRegisterInfo();
709                         Memory::Region data_region = (reg_info->encoding == lldb::eEncodingVector) ?
710                         m_memory.Malloc(reg_info->byte_size, m_target_data.getPrefTypeAlignment(value->getType())) :
711                         m_memory.Malloc(value->getType());
712 
713                         data_region.m_allocation->m_origin = resolved_value;
714                         Memory::Region ref_region = m_memory.Malloc(value->getType());
715 
716                         if (!Cache(data_region.m_allocation, value->getType()))
717                             return Memory::Region();
718 
719                         if (ref_region.IsInvalid())
720                             return Memory::Region();
721 
722                         DataEncoderSP ref_encoder = m_memory.GetEncoder(ref_region);
723 
724                         if (ref_encoder->PutAddress(0, data_region.m_base) == UINT32_MAX)
725                             return Memory::Region();
726 
727                         if (log)
728                         {
729                             log->Printf("Made an allocation for bare register variable %s", PrintValue(value).c_str());
730                             log->Printf("  Data contents  : %s", m_memory.PrintData(data_region.m_base, data_region.m_extent).c_str());
731                             log->Printf("  Data region    : %llx", (unsigned long long)data_region.m_base);
732                             log->Printf("  Ref region     : %llx", (unsigned long long)ref_region.m_base);
733                         }
734 
735                         m_values[value] = ref_region;
736                         return ref_region;
737                     }
738                     else
739                     {
740                         lldb_private::RegisterInfo *reg_info = resolved_value.GetRegisterInfo();
741                         Memory::Region data_region = (reg_info->encoding == lldb::eEncodingVector) ?
742                         m_memory.Malloc(reg_info->byte_size, m_target_data.getPrefTypeAlignment(value->getType())) :
743                         m_memory.Malloc(value->getType());
744 
745                         data_region.m_allocation->m_origin = resolved_value;
746                         Memory::Region ref_region = m_memory.Malloc(value->getType());
747                         Memory::Region pointer_region;
748 
749                         pointer_region = m_memory.Malloc(value->getType());
750 
751                         if (!Cache(data_region.m_allocation, value->getType()))
752                             return Memory::Region();
753 
754                         if (ref_region.IsInvalid())
755                             return Memory::Region();
756 
757                         if (pointer_region.IsInvalid())
758                             return Memory::Region();
759 
760                         DataEncoderSP ref_encoder = m_memory.GetEncoder(ref_region);
761 
762                         if (ref_encoder->PutAddress(0, data_region.m_base) == UINT32_MAX)
763                             return Memory::Region();
764 
765                         if (log)
766                         {
767                             log->Printf("Made an allocation for ordinary register variable %s", PrintValue(value).c_str());
768                             log->Printf("  Data contents  : %s", m_memory.PrintData(data_region.m_base, data_region.m_extent).c_str());
769                             log->Printf("  Data region    : %llx", (unsigned long long)data_region.m_base);
770                             log->Printf("  Ref region     : %llx", (unsigned long long)ref_region.m_base);
771                             log->Printf("  Pointer region : %llx", (unsigned long long)pointer_region.m_base);
772                         }
773 
774                         DataEncoderSP pointer_encoder = m_memory.GetEncoder(pointer_region);
775 
776                         if (pointer_encoder->PutAddress(0, ref_region.m_base) == UINT32_MAX)
777                             return Memory::Region();
778 
779                         m_values[value] = pointer_region;
780                         return pointer_region;
781                     }
782                 }
783                 else
784                 {
785                     Memory::Region data_region = m_memory.Place(value->getType(), resolved_value.GetScalar().ULongLong(), resolved_value);
786                     Memory::Region ref_region = m_memory.Malloc(value->getType());
787                     Memory::Region pointer_region;
788 
789                     if (!variable_is_this)
790                         pointer_region = m_memory.Malloc(value->getType());
791 
792                     if (ref_region.IsInvalid())
793                         return Memory::Region();
794 
795                     if (pointer_region.IsInvalid() && !variable_is_this)
796                         return Memory::Region();
797 
798                     DataEncoderSP ref_encoder = m_memory.GetEncoder(ref_region);
799 
800                     if (ref_encoder->PutAddress(0, data_region.m_base) == UINT32_MAX)
801                         return Memory::Region();
802 
803                     if (!variable_is_this)
804                     {
805                         DataEncoderSP pointer_encoder = m_memory.GetEncoder(pointer_region);
806 
807                         if (pointer_encoder->PutAddress(0, ref_region.m_base) == UINT32_MAX)
808                             return Memory::Region();
809 
810                         m_values[value] = pointer_region;
811                     }
812 
813                     if (log)
814                     {
815                         log->Printf("Made an allocation for %s", PrintValue(value).c_str());
816                         log->Printf("  Data contents  : %s", m_memory.PrintData(data_region.m_base, data_region.m_extent).c_str());
817                         log->Printf("  Data region    : %llx", (unsigned long long)data_region.m_base);
818                         log->Printf("  Ref region     : %llx", (unsigned long long)ref_region.m_base);
819                         if (!variable_is_this)
820                             log->Printf("  Pointer region : %llx", (unsigned long long)pointer_region.m_base);
821                     }
822 
823                     if (variable_is_this)
824                         return ref_region;
825                     else
826                         return pointer_region;
827                 }
828             }
829         }
830         while(0);
831 
832         // Fall back and allocate space [allocation type Alloca]
833 
834         Type *type = value->getType();
835 
836         lldb::ValueSP backing_value(new lldb_private::Value);
837 
838         Memory::Region data_region = m_memory.Malloc(type);
839         data_region.m_allocation->m_origin.GetScalar() = (unsigned long long)data_region.m_allocation->m_data->GetBytes();
840         data_region.m_allocation->m_origin.SetContext(lldb_private::Value::eContextTypeInvalid, NULL);
841         data_region.m_allocation->m_origin.SetValueType(lldb_private::Value::eValueTypeHostAddress);
842 
843         const Constant *constant = dyn_cast<Constant>(value);
844 
845         do
846         {
847             if (!constant)
848                 break;
849 
850             if (!ResolveConstant (data_region, constant))
851                 return Memory::Region();
852         }
853         while(0);
854 
855         m_values[value] = data_region;
856         return data_region;
857     }
858 
859     bool ConstructResult (lldb::ClangExpressionVariableSP &result,
860                           const GlobalValue *result_value,
861                           const lldb_private::ConstString &result_name,
862                           lldb_private::TypeFromParser result_type,
863                           Module &module)
864     {
865         // The result_value resolves to P, a pointer to a region R containing the result data.
866         // If the result variable is a reference, the region R contains a pointer to the result R_final in the original process.
867 
868         if (!result_value)
869             return true; // There was no slot for a result – the expression doesn't return one.
870 
871         ValueMap::iterator i = m_values.find(result_value);
872 
873         if (i == m_values.end())
874             return false; // There was a slot for the result, but we didn't write into it.
875 
876         Memory::Region P = i->second;
877         DataExtractorSP P_extractor = m_memory.GetExtractor(P);
878 
879         if (!P_extractor)
880             return false;
881 
882         Type *pointer_ty = result_value->getType();
883         PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
884         if (!pointer_ptr_ty)
885             return false;
886         Type *R_ty = pointer_ptr_ty->getElementType();
887 
888         lldb::offset_t offset = 0;
889         lldb::addr_t pointer = P_extractor->GetAddress(&offset);
890 
891         Memory::Region R = m_memory.Lookup(pointer, R_ty);
892 
893         if (R.m_allocation->m_origin.GetValueType() != lldb_private::Value::eValueTypeHostAddress ||
894             !R.m_allocation->m_data)
895             return false;
896 
897         lldb_private::Value base;
898 
899         bool transient = false;
900         bool maybe_make_load = false;
901 
902         if (m_decl_map.ResultIsReference(result_name))
903         {
904             PointerType *R_ptr_ty = dyn_cast<PointerType>(R_ty);
905             if (!R_ptr_ty)
906                 return false;
907             Type *R_final_ty = R_ptr_ty->getElementType();
908 
909             DataExtractorSP R_extractor = m_memory.GetExtractor(R);
910 
911             if (!R_extractor)
912                 return false;
913 
914             offset = 0;
915             lldb::addr_t R_pointer = R_extractor->GetAddress(&offset);
916 
917             Memory::Region R_final = m_memory.Lookup(R_pointer, R_final_ty);
918 
919             if (R_final.m_allocation)
920             {
921                 if (R_final.m_allocation->m_data)
922                     transient = true; // this is a stack allocation
923 
924                 base = R_final.m_allocation->m_origin;
925                 base.GetScalar() += (R_final.m_base - R_final.m_allocation->m_virtual_address);
926             }
927             else
928             {
929                 // We got a bare pointer.  We are going to treat it as a load address
930                 // or a file address, letting decl_map make the choice based on whether
931                 // or not a process exists.
932 
933                 base.SetContext(lldb_private::Value::eContextTypeInvalid, NULL);
934                 base.SetValueType(lldb_private::Value::eValueTypeFileAddress);
935                 base.GetScalar() = (unsigned long long)R_pointer;
936                 maybe_make_load = true;
937             }
938         }
939         else
940         {
941             base.SetContext(lldb_private::Value::eContextTypeInvalid, NULL);
942             base.SetValueType(lldb_private::Value::eValueTypeHostAddress);
943             base.GetScalar() = (unsigned long long)R.m_allocation->m_data->GetBytes() + (R.m_base - R.m_allocation->m_virtual_address);
944         }
945 
946         return m_decl_map.CompleteResultVariable (result, base, result_name, result_type, transient, maybe_make_load);
947     }
948 };
949 
950 bool
951 IRInterpreter::maybeRunOnFunction (lldb::ClangExpressionVariableSP &result,
952                                    const lldb_private::ConstString &result_name,
953                                    lldb_private::TypeFromParser result_type,
954                                    Function &llvm_function,
955                                    Module &llvm_module,
956                                    lldb_private::Error &err)
957 {
958     if (supportsFunction (llvm_function, err))
959         return runOnFunction(result,
960                              result_name,
961                              result_type,
962                              llvm_function,
963                              llvm_module,
964                              err);
965     else
966         return false;
967 }
968 
969 static const char *unsupported_opcode_error         = "Interpreter doesn't handle one of the expression's opcodes";
970 static const char *interpreter_initialization_error = "Interpreter couldn't be initialized";
971 static const char *interpreter_internal_error       = "Interpreter encountered an internal error";
972 static const char *bad_value_error                  = "Interpreter couldn't resolve a value during execution";
973 static const char *memory_allocation_error          = "Interpreter couldn't allocate memory";
974 static const char *memory_write_error               = "Interpreter couldn't write to memory";
975 static const char *memory_read_error                = "Interpreter couldn't read from memory";
976 static const char *infinite_loop_error              = "Interpreter ran for too many cycles";
977 static const char *bad_result_error                 = "Result of expression is in bad memory";
978 
979 bool
980 IRInterpreter::supportsFunction (Function &llvm_function,
981                                  lldb_private::Error &err)
982 {
983     lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
984 
985     for (Function::iterator bbi = llvm_function.begin(), bbe = llvm_function.end();
986          bbi != bbe;
987          ++bbi)
988     {
989         for (BasicBlock::iterator ii = bbi->begin(), ie = bbi->end();
990              ii != ie;
991              ++ii)
992         {
993             switch (ii->getOpcode())
994             {
995             default:
996                 {
997                     if (log)
998                         log->Printf("Unsupported instruction: %s", PrintValue(ii).c_str());
999                     err.SetErrorToGenericError();
1000                     err.SetErrorString(unsupported_opcode_error);
1001                     return false;
1002                 }
1003             case Instruction::Add:
1004             case Instruction::Alloca:
1005             case Instruction::BitCast:
1006             case Instruction::Br:
1007             case Instruction::GetElementPtr:
1008                 break;
1009             case Instruction::ICmp:
1010                 {
1011                     ICmpInst *icmp_inst = dyn_cast<ICmpInst>(ii);
1012 
1013                     if (!icmp_inst)
1014                     {
1015                         err.SetErrorToGenericError();
1016                         err.SetErrorString(interpreter_internal_error);
1017                         return false;
1018                     }
1019 
1020                     switch (icmp_inst->getPredicate())
1021                     {
1022                     default:
1023                         {
1024                             if (log)
1025                                 log->Printf("Unsupported ICmp predicate: %s", PrintValue(ii).c_str());
1026 
1027                             err.SetErrorToGenericError();
1028                             err.SetErrorString(unsupported_opcode_error);
1029                             return false;
1030                         }
1031                     case CmpInst::ICMP_EQ:
1032                     case CmpInst::ICMP_NE:
1033                     case CmpInst::ICMP_UGT:
1034                     case CmpInst::ICMP_UGE:
1035                     case CmpInst::ICMP_ULT:
1036                     case CmpInst::ICMP_ULE:
1037                     case CmpInst::ICMP_SGT:
1038                     case CmpInst::ICMP_SGE:
1039                     case CmpInst::ICMP_SLT:
1040                     case CmpInst::ICMP_SLE:
1041                         break;
1042                     }
1043                 }
1044                 break;
1045             case Instruction::And:
1046             case Instruction::AShr:
1047             case Instruction::IntToPtr:
1048             case Instruction::PtrToInt:
1049             case Instruction::Load:
1050             case Instruction::LShr:
1051             case Instruction::Mul:
1052             case Instruction::Or:
1053             case Instruction::Ret:
1054             case Instruction::SDiv:
1055             case Instruction::Shl:
1056             case Instruction::SRem:
1057             case Instruction::Store:
1058             case Instruction::Sub:
1059             case Instruction::UDiv:
1060             case Instruction::URem:
1061             case Instruction::Xor:
1062             case Instruction::ZExt:
1063                 break;
1064             }
1065         }
1066     }
1067 
1068     return true;
1069 }
1070 
1071 bool
1072 IRInterpreter::runOnFunction (lldb::ClangExpressionVariableSP &result,
1073                               const lldb_private::ConstString &result_name,
1074                               lldb_private::TypeFromParser result_type,
1075                               Function &llvm_function,
1076                               Module &llvm_module,
1077                               lldb_private::Error &err)
1078 {
1079     lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1080 
1081     lldb_private::ClangExpressionDeclMap::TargetInfo target_info = m_decl_map.GetTargetInfo();
1082 
1083     if (!target_info.IsValid())
1084     {
1085         err.SetErrorToGenericError();
1086         err.SetErrorString(interpreter_initialization_error);
1087         return false;
1088     }
1089 
1090     lldb::addr_t alloc_min;
1091     lldb::addr_t alloc_max;
1092 
1093     switch (target_info.address_byte_size)
1094     {
1095     default:
1096         err.SetErrorToGenericError();
1097         err.SetErrorString(interpreter_initialization_error);
1098         return false;
1099     case 4:
1100         alloc_min = 0x00001000llu;
1101         alloc_max = 0x0000ffffllu;
1102         break;
1103     case 8:
1104         alloc_min = 0x0000000000001000llu;
1105         alloc_max = 0x000000000000ffffllu;
1106         break;
1107     }
1108 
1109     DataLayout target_data(&llvm_module);
1110     if (target_data.getPointerSize(0) != target_info.address_byte_size)
1111     {
1112         err.SetErrorToGenericError();
1113         err.SetErrorString(interpreter_initialization_error);
1114         return false;
1115     }
1116     if (target_data.isLittleEndian() != (target_info.byte_order == lldb::eByteOrderLittle))
1117     {
1118         err.SetErrorToGenericError();
1119         err.SetErrorString(interpreter_initialization_error);
1120         return false;
1121     }
1122 
1123     Memory memory(target_data, m_decl_map, alloc_min, alloc_max);
1124     InterpreterStackFrame frame(target_data, memory, m_decl_map);
1125 
1126     uint32_t num_insts = 0;
1127 
1128     frame.Jump(llvm_function.begin());
1129 
1130     while (frame.m_ii != frame.m_ie && (++num_insts < 4096))
1131     {
1132         const Instruction *inst = frame.m_ii;
1133 
1134         if (log)
1135             log->Printf("Interpreting %s", PrintValue(inst).c_str());
1136 
1137         switch (inst->getOpcode())
1138         {
1139         default:
1140             break;
1141         case Instruction::Add:
1142         case Instruction::Sub:
1143         case Instruction::Mul:
1144         case Instruction::SDiv:
1145         case Instruction::UDiv:
1146         case Instruction::SRem:
1147         case Instruction::URem:
1148         case Instruction::Shl:
1149         case Instruction::LShr:
1150         case Instruction::AShr:
1151         case Instruction::And:
1152         case Instruction::Or:
1153         case Instruction::Xor:
1154             {
1155                 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
1156 
1157                 if (!bin_op)
1158                 {
1159                     if (log)
1160                         log->Printf("getOpcode() returns %s, but instruction is not a BinaryOperator", inst->getOpcodeName());
1161                     err.SetErrorToGenericError();
1162                     err.SetErrorString(interpreter_internal_error);
1163                     return false;
1164                 }
1165 
1166                 Value *lhs = inst->getOperand(0);
1167                 Value *rhs = inst->getOperand(1);
1168 
1169                 lldb_private::Scalar L;
1170                 lldb_private::Scalar R;
1171 
1172                 if (!frame.EvaluateValue(L, lhs, llvm_module))
1173                 {
1174                     if (log)
1175                         log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1176                     err.SetErrorToGenericError();
1177                     err.SetErrorString(bad_value_error);
1178                     return false;
1179                 }
1180 
1181                 if (!frame.EvaluateValue(R, rhs, llvm_module))
1182                 {
1183                     if (log)
1184                         log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1185                     err.SetErrorToGenericError();
1186                     err.SetErrorString(bad_value_error);
1187                     return false;
1188                 }
1189 
1190                 lldb_private::Scalar result;
1191 
1192                 switch (inst->getOpcode())
1193                 {
1194                 default:
1195                     break;
1196                 case Instruction::Add:
1197                     result = L + R;
1198                     break;
1199                 case Instruction::Mul:
1200                     result = L * R;
1201                     break;
1202                 case Instruction::Sub:
1203                     result = L - R;
1204                     break;
1205                 case Instruction::SDiv:
1206                     result = L / R;
1207                     break;
1208                 case Instruction::UDiv:
1209                     result = L.GetRawBits64(0) / R.GetRawBits64(1);
1210                     break;
1211                 case Instruction::SRem:
1212                     result = L % R;
1213                     break;
1214                 case Instruction::URem:
1215                     result = L.GetRawBits64(0) % R.GetRawBits64(1);
1216                     break;
1217                 case Instruction::Shl:
1218                     result = L << R;
1219                     break;
1220                 case Instruction::AShr:
1221                     result = L >> R;
1222                     break;
1223                 case Instruction::LShr:
1224                     result = L;
1225                     result.ShiftRightLogical(R);
1226                     break;
1227                 case Instruction::And:
1228                     result = L & R;
1229                     break;
1230                 case Instruction::Or:
1231                     result = L | R;
1232                     break;
1233                 case Instruction::Xor:
1234                     result = L ^ R;
1235                     break;
1236                 }
1237 
1238                 frame.AssignValue(inst, result, llvm_module);
1239 
1240                 if (log)
1241                 {
1242                     log->Printf("Interpreted a %s", inst->getOpcodeName());
1243                     log->Printf("  L : %s", frame.SummarizeValue(lhs).c_str());
1244                     log->Printf("  R : %s", frame.SummarizeValue(rhs).c_str());
1245                     log->Printf("  = : %s", frame.SummarizeValue(inst).c_str());
1246                 }
1247             }
1248             break;
1249         case Instruction::Alloca:
1250             {
1251                 const AllocaInst *alloca_inst = dyn_cast<AllocaInst>(inst);
1252 
1253                 if (!alloca_inst)
1254                 {
1255                     if (log)
1256                         log->Printf("getOpcode() returns Alloca, but instruction is not an AllocaInst");
1257                     err.SetErrorToGenericError();
1258                     err.SetErrorString(interpreter_internal_error);
1259                     return false;
1260                 }
1261 
1262                 if (alloca_inst->isArrayAllocation())
1263                 {
1264                     if (log)
1265                         log->Printf("AllocaInsts are not handled if isArrayAllocation() is true");
1266                     err.SetErrorToGenericError();
1267                     err.SetErrorString(unsupported_opcode_error);
1268                     return false;
1269                 }
1270 
1271                 // The semantics of Alloca are:
1272                 //   Create a region R of virtual memory of type T, backed by a data buffer
1273                 //   Create a region P of virtual memory of type T*, backed by a data buffer
1274                 //   Write the virtual address of R into P
1275 
1276                 Type *T = alloca_inst->getAllocatedType();
1277                 Type *Tptr = alloca_inst->getType();
1278 
1279                 Memory::Region R = memory.Malloc(T);
1280 
1281                 if (R.IsInvalid())
1282                 {
1283                     if (log)
1284                         log->Printf("Couldn't allocate memory for an AllocaInst");
1285                     err.SetErrorToGenericError();
1286                     err.SetErrorString(memory_allocation_error);
1287                     return false;
1288                 }
1289 
1290                 Memory::Region P = memory.Malloc(Tptr);
1291 
1292                 if (P.IsInvalid())
1293                 {
1294                     if (log)
1295                         log->Printf("Couldn't allocate the result pointer for an AllocaInst");
1296                     err.SetErrorToGenericError();
1297                     err.SetErrorString(memory_allocation_error);
1298                     return false;
1299                 }
1300 
1301                 DataEncoderSP P_encoder = memory.GetEncoder(P);
1302 
1303                 if (P_encoder->PutAddress(0, R.m_base) == UINT32_MAX)
1304                 {
1305                     if (log)
1306                         log->Printf("Couldn't write the result pointer for an AllocaInst");
1307                     err.SetErrorToGenericError();
1308                     err.SetErrorString(memory_write_error);
1309                     return false;
1310                 }
1311 
1312                 frame.m_values[alloca_inst] = P;
1313 
1314                 if (log)
1315                 {
1316                     log->Printf("Interpreted an AllocaInst");
1317                     log->Printf("  R : %s", memory.SummarizeRegion(R).c_str());
1318                     log->Printf("  P : %s", frame.SummarizeValue(alloca_inst).c_str());
1319                 }
1320             }
1321             break;
1322         case Instruction::BitCast:
1323         case Instruction::ZExt:
1324             {
1325                 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
1326 
1327                 if (!cast_inst)
1328                 {
1329                     if (log)
1330                         log->Printf("getOpcode() returns %s, but instruction is not a BitCastInst", cast_inst->getOpcodeName());
1331                     err.SetErrorToGenericError();
1332                     err.SetErrorString(interpreter_internal_error);
1333                     return false;
1334                 }
1335 
1336                 Value *source = cast_inst->getOperand(0);
1337 
1338                 lldb_private::Scalar S;
1339 
1340                 if (!frame.EvaluateValue(S, source, llvm_module))
1341                 {
1342                     if (log)
1343                         log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
1344                     err.SetErrorToGenericError();
1345                     err.SetErrorString(bad_value_error);
1346                     return false;
1347                 }
1348 
1349                 frame.AssignValue(inst, S, llvm_module);
1350             }
1351             break;
1352         case Instruction::Br:
1353             {
1354                 const BranchInst *br_inst = dyn_cast<BranchInst>(inst);
1355 
1356                 if (!br_inst)
1357                 {
1358                     if (log)
1359                         log->Printf("getOpcode() returns Br, but instruction is not a BranchInst");
1360                     err.SetErrorToGenericError();
1361                     err.SetErrorString(interpreter_internal_error);
1362                     return false;
1363                 }
1364 
1365                 if (br_inst->isConditional())
1366                 {
1367                     Value *condition = br_inst->getCondition();
1368 
1369                     lldb_private::Scalar C;
1370 
1371                     if (!frame.EvaluateValue(C, condition, llvm_module))
1372                     {
1373                         if (log)
1374                             log->Printf("Couldn't evaluate %s", PrintValue(condition).c_str());
1375                         err.SetErrorToGenericError();
1376                         err.SetErrorString(bad_value_error);
1377                         return false;
1378                     }
1379 
1380                     if (C.GetRawBits64(0))
1381                         frame.Jump(br_inst->getSuccessor(0));
1382                     else
1383                         frame.Jump(br_inst->getSuccessor(1));
1384 
1385                     if (log)
1386                     {
1387                         log->Printf("Interpreted a BrInst with a condition");
1388                         log->Printf("  cond : %s", frame.SummarizeValue(condition).c_str());
1389                     }
1390                 }
1391                 else
1392                 {
1393                     frame.Jump(br_inst->getSuccessor(0));
1394 
1395                     if (log)
1396                     {
1397                         log->Printf("Interpreted a BrInst with no condition");
1398                     }
1399                 }
1400             }
1401             continue;
1402         case Instruction::GetElementPtr:
1403             {
1404                 const GetElementPtrInst *gep_inst = dyn_cast<GetElementPtrInst>(inst);
1405 
1406                 if (!gep_inst)
1407                 {
1408                     if (log)
1409                         log->Printf("getOpcode() returns GetElementPtr, but instruction is not a GetElementPtrInst");
1410                     err.SetErrorToGenericError();
1411                     err.SetErrorString(interpreter_internal_error);
1412                     return false;
1413                 }
1414 
1415                 const Value *pointer_operand = gep_inst->getPointerOperand();
1416                 Type *pointer_type = pointer_operand->getType();
1417 
1418                 lldb_private::Scalar P;
1419 
1420                 if (!frame.EvaluateValue(P, pointer_operand, llvm_module))
1421                 {
1422                     if (log)
1423                         log->Printf("Couldn't evaluate %s", PrintValue(pointer_operand).c_str());
1424                     err.SetErrorToGenericError();
1425                     err.SetErrorString(bad_value_error);
1426                     return false;
1427                 }
1428 
1429                 typedef SmallVector <Value *, 8> IndexVector;
1430                 typedef IndexVector::iterator IndexIterator;
1431 
1432                 SmallVector <Value *, 8> indices (gep_inst->idx_begin(),
1433                                                   gep_inst->idx_end());
1434 
1435                 SmallVector <Value *, 8> const_indices;
1436 
1437                 for (IndexIterator ii = indices.begin(), ie = indices.end();
1438                      ii != ie;
1439                      ++ii)
1440                 {
1441                     ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1442 
1443                     if (!constant_index)
1444                     {
1445                         lldb_private::Scalar I;
1446 
1447                         if (!frame.EvaluateValue(I, *ii, llvm_module))
1448                         {
1449                             if (log)
1450                                 log->Printf("Couldn't evaluate %s", PrintValue(*ii).c_str());
1451                             err.SetErrorToGenericError();
1452                             err.SetErrorString(bad_value_error);
1453                             return false;
1454                         }
1455 
1456                         if (log)
1457                             log->Printf("Evaluated constant index %s as %llu", PrintValue(*ii).c_str(), I.ULongLong(LLDB_INVALID_ADDRESS));
1458 
1459                         constant_index = cast<ConstantInt>(ConstantInt::get((*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1460                     }
1461 
1462                     const_indices.push_back(constant_index);
1463                 }
1464 
1465                 uint64_t offset = target_data.getIndexedOffset(pointer_type, const_indices);
1466 
1467                 lldb_private::Scalar Poffset = P + offset;
1468 
1469                 frame.AssignValue(inst, Poffset, llvm_module);
1470 
1471                 if (log)
1472                 {
1473                     log->Printf("Interpreted a GetElementPtrInst");
1474                     log->Printf("  P       : %s", frame.SummarizeValue(pointer_operand).c_str());
1475                     log->Printf("  Poffset : %s", frame.SummarizeValue(inst).c_str());
1476                 }
1477             }
1478             break;
1479         case Instruction::ICmp:
1480             {
1481                 const ICmpInst *icmp_inst = dyn_cast<ICmpInst>(inst);
1482 
1483                 if (!icmp_inst)
1484                 {
1485                     if (log)
1486                         log->Printf("getOpcode() returns ICmp, but instruction is not an ICmpInst");
1487                     err.SetErrorToGenericError();
1488                     err.SetErrorString(interpreter_internal_error);
1489                     return false;
1490                 }
1491 
1492                 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1493 
1494                 Value *lhs = inst->getOperand(0);
1495                 Value *rhs = inst->getOperand(1);
1496 
1497                 lldb_private::Scalar L;
1498                 lldb_private::Scalar R;
1499 
1500                 if (!frame.EvaluateValue(L, lhs, llvm_module))
1501                 {
1502                     if (log)
1503                         log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1504                     err.SetErrorToGenericError();
1505                     err.SetErrorString(bad_value_error);
1506                     return false;
1507                 }
1508 
1509                 if (!frame.EvaluateValue(R, rhs, llvm_module))
1510                 {
1511                     if (log)
1512                         log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1513                     err.SetErrorToGenericError();
1514                     err.SetErrorString(bad_value_error);
1515                     return false;
1516                 }
1517 
1518                 lldb_private::Scalar result;
1519 
1520                 switch (predicate)
1521                 {
1522                 default:
1523                     return false;
1524                 case CmpInst::ICMP_EQ:
1525                     result = (L == R);
1526                     break;
1527                 case CmpInst::ICMP_NE:
1528                     result = (L != R);
1529                     break;
1530                 case CmpInst::ICMP_UGT:
1531                     result = (L.GetRawBits64(0) > R.GetRawBits64(0));
1532                     break;
1533                 case CmpInst::ICMP_UGE:
1534                     result = (L.GetRawBits64(0) >= R.GetRawBits64(0));
1535                     break;
1536                 case CmpInst::ICMP_ULT:
1537                     result = (L.GetRawBits64(0) < R.GetRawBits64(0));
1538                     break;
1539                 case CmpInst::ICMP_ULE:
1540                     result = (L.GetRawBits64(0) <= R.GetRawBits64(0));
1541                     break;
1542                 case CmpInst::ICMP_SGT:
1543                     result = (L > R);
1544                     break;
1545                 case CmpInst::ICMP_SGE:
1546                     result = (L >= R);
1547                     break;
1548                 case CmpInst::ICMP_SLT:
1549                     result = (L < R);
1550                     break;
1551                 case CmpInst::ICMP_SLE:
1552                     result = (L <= R);
1553                     break;
1554                 }
1555 
1556                 frame.AssignValue(inst, result, llvm_module);
1557 
1558                 if (log)
1559                 {
1560                     log->Printf("Interpreted an ICmpInst");
1561                     log->Printf("  L : %s", frame.SummarizeValue(lhs).c_str());
1562                     log->Printf("  R : %s", frame.SummarizeValue(rhs).c_str());
1563                     log->Printf("  = : %s", frame.SummarizeValue(inst).c_str());
1564                 }
1565             }
1566             break;
1567         case Instruction::IntToPtr:
1568             {
1569                 const IntToPtrInst *int_to_ptr_inst = dyn_cast<IntToPtrInst>(inst);
1570 
1571                 if (!int_to_ptr_inst)
1572                 {
1573                     if (log)
1574                         log->Printf("getOpcode() returns IntToPtr, but instruction is not an IntToPtrInst");
1575                     err.SetErrorToGenericError();
1576                     err.SetErrorString(interpreter_internal_error);
1577                     return false;
1578                 }
1579 
1580                 Value *src_operand = int_to_ptr_inst->getOperand(0);
1581 
1582                 lldb_private::Scalar I;
1583 
1584                 if (!frame.EvaluateValue(I, src_operand, llvm_module))
1585                 {
1586                     if (log)
1587                         log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1588                     err.SetErrorToGenericError();
1589                     err.SetErrorString(bad_value_error);
1590                     return false;
1591                 }
1592 
1593                 frame.AssignValue(inst, I, llvm_module);
1594 
1595                 if (log)
1596                 {
1597                     log->Printf("Interpreted an IntToPtr");
1598                     log->Printf("  Src : %s", frame.SummarizeValue(src_operand).c_str());
1599                     log->Printf("  =   : %s", frame.SummarizeValue(inst).c_str());
1600                 }
1601             }
1602             break;
1603         case Instruction::PtrToInt:
1604             {
1605                 const PtrToIntInst *ptr_to_int_inst = dyn_cast<PtrToIntInst>(inst);
1606 
1607                 if (!ptr_to_int_inst)
1608                 {
1609                     if (log)
1610                         log->Printf("getOpcode() returns PtrToInt, but instruction is not an PtrToIntInst");
1611                     err.SetErrorToGenericError();
1612                     err.SetErrorString(interpreter_internal_error);
1613                     return false;
1614                 }
1615 
1616                 Value *src_operand = ptr_to_int_inst->getOperand(0);
1617 
1618                 lldb_private::Scalar I;
1619 
1620                 if (!frame.EvaluateValue(I, src_operand, llvm_module))
1621                 {
1622                     if (log)
1623                         log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1624                     err.SetErrorToGenericError();
1625                     err.SetErrorString(bad_value_error);
1626                     return false;
1627                 }
1628 
1629                 frame.AssignValue(inst, I, llvm_module);
1630 
1631                 if (log)
1632                 {
1633                     log->Printf("Interpreted a PtrToInt");
1634                     log->Printf("  Src : %s", frame.SummarizeValue(src_operand).c_str());
1635                     log->Printf("  =   : %s", frame.SummarizeValue(inst).c_str());
1636                 }
1637             }
1638             break;
1639         case Instruction::Load:
1640             {
1641                 const LoadInst *load_inst = dyn_cast<LoadInst>(inst);
1642 
1643                 if (!load_inst)
1644                 {
1645                     if (log)
1646                         log->Printf("getOpcode() returns Load, but instruction is not a LoadInst");
1647                     err.SetErrorToGenericError();
1648                     err.SetErrorString(interpreter_internal_error);
1649                     return false;
1650                 }
1651 
1652                 // The semantics of Load are:
1653                 //   Create a region D that will contain the loaded data
1654                 //   Resolve the region P containing a pointer
1655                 //   Dereference P to get the region R that the data should be loaded from
1656                 //   Transfer a unit of type type(D) from R to D
1657 
1658                 const Value *pointer_operand = load_inst->getPointerOperand();
1659 
1660                 Type *pointer_ty = pointer_operand->getType();
1661                 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1662                 if (!pointer_ptr_ty)
1663                 {
1664                     if (log)
1665                         log->Printf("getPointerOperand()->getType() is not a PointerType");
1666                     err.SetErrorToGenericError();
1667                     err.SetErrorString(interpreter_internal_error);
1668                     return false;
1669                 }
1670                 Type *target_ty = pointer_ptr_ty->getElementType();
1671 
1672                 Memory::Region D = frame.ResolveValue(load_inst, llvm_module);
1673                 Memory::Region P = frame.ResolveValue(pointer_operand, llvm_module);
1674 
1675                 if (D.IsInvalid())
1676                 {
1677                     if (log)
1678                         log->Printf("LoadInst's value doesn't resolve to anything");
1679                     err.SetErrorToGenericError();
1680                     err.SetErrorString(bad_value_error);
1681                     return false;
1682                 }
1683 
1684                 if (P.IsInvalid())
1685                 {
1686                     if (log)
1687                         log->Printf("LoadInst's pointer doesn't resolve to anything");
1688                     err.SetErrorToGenericError();
1689                     err.SetErrorString(bad_value_error);
1690                     return false;
1691                 }
1692 
1693                 DataExtractorSP P_extractor(memory.GetExtractor(P));
1694                 DataEncoderSP D_encoder(memory.GetEncoder(D));
1695 
1696                 lldb::offset_t offset = 0;
1697                 lldb::addr_t pointer = P_extractor->GetAddress(&offset);
1698 
1699                 Memory::Region R = memory.Lookup(pointer, target_ty);
1700 
1701                 if (R.IsValid())
1702                 {
1703                     if (!memory.Read(D_encoder->GetDataStart(), R.m_base, target_data.getTypeStoreSize(target_ty)))
1704                     {
1705                         if (log)
1706                             log->Printf("Couldn't read from a region on behalf of a LoadInst");
1707                         err.SetErrorToGenericError();
1708                         err.SetErrorString(memory_read_error);
1709                         return false;
1710                     }
1711                 }
1712                 else
1713                 {
1714                     if (!memory.ReadFromRawPtr(D_encoder->GetDataStart(), pointer, target_data.getTypeStoreSize(target_ty)))
1715                     {
1716                         if (log)
1717                             log->Printf("Couldn't read from a raw pointer on behalf of a LoadInst");
1718                         err.SetErrorToGenericError();
1719                         err.SetErrorString(memory_read_error);
1720                         return false;
1721                     }
1722                 }
1723 
1724                 if (log)
1725                 {
1726                     log->Printf("Interpreted a LoadInst");
1727                     log->Printf("  P : %s", frame.SummarizeValue(pointer_operand).c_str());
1728                     if (R.IsValid())
1729                         log->Printf("  R : %s", memory.SummarizeRegion(R).c_str());
1730                     else
1731                         log->Printf("  R : raw pointer 0x%llx", (unsigned long long)pointer);
1732                     log->Printf("  D : %s", frame.SummarizeValue(load_inst).c_str());
1733                 }
1734             }
1735             break;
1736         case Instruction::Ret:
1737             {
1738                 if (result_name.IsEmpty())
1739                     return true;
1740 
1741                 GlobalValue *result_value = llvm_module.getNamedValue(result_name.GetCString());
1742 
1743                 if (!frame.ConstructResult(result, result_value, result_name, result_type, llvm_module))
1744                 {
1745                     if (log)
1746                         log->Printf("Couldn't construct the expression's result");
1747                     err.SetErrorToGenericError();
1748                     err.SetErrorString(bad_result_error);
1749                     return false;
1750                 }
1751 
1752                 return true;
1753             }
1754         case Instruction::Store:
1755             {
1756                 const StoreInst *store_inst = dyn_cast<StoreInst>(inst);
1757 
1758                 if (!store_inst)
1759                 {
1760                     if (log)
1761                         log->Printf("getOpcode() returns Store, but instruction is not a StoreInst");
1762                     err.SetErrorToGenericError();
1763                     err.SetErrorString(interpreter_internal_error);
1764                     return false;
1765                 }
1766 
1767                 // The semantics of Store are:
1768                 //   Resolve the region D containing the data to be stored
1769                 //   Resolve the region P containing a pointer
1770                 //   Dereference P to get the region R that the data should be stored in
1771                 //   Transfer a unit of type type(D) from D to R
1772 
1773                 const Value *value_operand = store_inst->getValueOperand();
1774                 const Value *pointer_operand = store_inst->getPointerOperand();
1775 
1776                 Type *pointer_ty = pointer_operand->getType();
1777                 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1778                 if (!pointer_ptr_ty)
1779                     return false;
1780                 Type *target_ty = pointer_ptr_ty->getElementType();
1781 
1782                 Memory::Region D = frame.ResolveValue(value_operand, llvm_module);
1783                 Memory::Region P = frame.ResolveValue(pointer_operand, llvm_module);
1784 
1785                 if (D.IsInvalid())
1786                 {
1787                     if (log)
1788                         log->Printf("StoreInst's value doesn't resolve to anything");
1789                     err.SetErrorToGenericError();
1790                     err.SetErrorString(bad_value_error);
1791                     return false;
1792                 }
1793 
1794                 if (P.IsInvalid())
1795                 {
1796                     if (log)
1797                         log->Printf("StoreInst's pointer doesn't resolve to anything");
1798                     err.SetErrorToGenericError();
1799                     err.SetErrorString(bad_value_error);
1800                     return false;
1801                 }
1802 
1803                 DataExtractorSP P_extractor(memory.GetExtractor(P));
1804                 DataExtractorSP D_extractor(memory.GetExtractor(D));
1805 
1806                 if (!P_extractor || !D_extractor)
1807                     return false;
1808 
1809                 lldb::offset_t offset = 0;
1810                 lldb::addr_t pointer = P_extractor->GetAddress(&offset);
1811 
1812                 Memory::Region R = memory.Lookup(pointer, target_ty);
1813 
1814                 if (R.IsValid())
1815                 {
1816                     if (!memory.Write(R.m_base, D_extractor->GetDataStart(), target_data.getTypeStoreSize(target_ty)))
1817                     {
1818                         if (log)
1819                             log->Printf("Couldn't write to a region on behalf of a LoadInst");
1820                         err.SetErrorToGenericError();
1821                         err.SetErrorString(memory_write_error);
1822                         return false;
1823                     }
1824                 }
1825                 else
1826                 {
1827                     if (!memory.WriteToRawPtr(pointer, D_extractor->GetDataStart(), target_data.getTypeStoreSize(target_ty)))
1828                     {
1829                         if (log)
1830                             log->Printf("Couldn't write to a raw pointer on behalf of a LoadInst");
1831                         err.SetErrorToGenericError();
1832                         err.SetErrorString(memory_write_error);
1833                         return false;
1834                     }
1835                 }
1836 
1837 
1838                 if (log)
1839                 {
1840                     log->Printf("Interpreted a StoreInst");
1841                     log->Printf("  D : %s", frame.SummarizeValue(value_operand).c_str());
1842                     log->Printf("  P : %s", frame.SummarizeValue(pointer_operand).c_str());
1843                     log->Printf("  R : %s", memory.SummarizeRegion(R).c_str());
1844                 }
1845             }
1846             break;
1847         }
1848 
1849         ++frame.m_ii;
1850     }
1851 
1852     if (num_insts >= 4096)
1853     {
1854         err.SetErrorToGenericError();
1855         err.SetErrorString(infinite_loop_error);
1856         return false;
1857     }
1858 
1859     return false;
1860 }
1861