1 //===-- IRForTarget.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 "IRForTarget.h"
11 
12 #include "ClangExpressionDeclMap.h"
13 
14 #include "llvm/IR/Constants.h"
15 #include "llvm/IR/DataLayout.h"
16 #include "llvm/IR/InstrTypes.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/ValueSymbolTable.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Transforms/IPO.h"
25 
26 #include "clang/AST/ASTContext.h"
27 
28 #include "lldb/Core/dwarf.h"
29 #include "lldb/Expression/IRExecutionUnit.h"
30 #include "lldb/Expression/IRInterpreter.h"
31 #include "lldb/Symbol/ClangASTContext.h"
32 #include "lldb/Symbol/ClangUtil.h"
33 #include "lldb/Symbol/CompilerType.h"
34 #include "lldb/Utility/ConstString.h"
35 #include "lldb/Utility/DataBufferHeap.h"
36 #include "lldb/Utility/Endian.h"
37 #include "lldb/Utility/Log.h"
38 #include "lldb/Utility/Scalar.h"
39 #include "lldb/Utility/StreamString.h"
40 
41 #include <map>
42 
43 using namespace llvm;
44 
45 static char ID;
46 
FunctionValueCache(Maker const & maker)47 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker)
48     : m_maker(maker), m_values() {}
49 
~FunctionValueCache()50 IRForTarget::FunctionValueCache::~FunctionValueCache() {}
51 
52 llvm::Value *
GetValue(llvm::Function * function)53 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function) {
54   if (!m_values.count(function)) {
55     llvm::Value *ret = m_maker(function);
56     m_values[function] = ret;
57     return ret;
58   }
59   return m_values[function];
60 }
61 
FindEntryInstruction(llvm::Function * function)62 static llvm::Value *FindEntryInstruction(llvm::Function *function) {
63   if (function->empty())
64     return NULL;
65 
66   return function->getEntryBlock().getFirstNonPHIOrDbg();
67 }
68 
IRForTarget(lldb_private::ClangExpressionDeclMap * decl_map,bool resolve_vars,lldb_private::IRExecutionUnit & execution_unit,lldb_private::Stream & error_stream,const char * func_name)69 IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
70                          bool resolve_vars,
71                          lldb_private::IRExecutionUnit &execution_unit,
72                          lldb_private::Stream &error_stream,
73                          const char *func_name)
74     : ModulePass(ID), m_resolve_vars(resolve_vars), m_func_name(func_name),
75       m_module(NULL), m_decl_map(decl_map), m_CFStringCreateWithBytes(NULL),
76       m_sel_registerName(NULL), m_objc_getClass(NULL), m_intptr_ty(NULL),
77       m_error_stream(error_stream),
78       m_execution_unit(execution_unit), m_result_store(NULL),
79       m_result_is_pointer(false), m_reloc_placeholder(NULL),
80       m_entry_instruction_finder(FindEntryInstruction) {}
81 
82 /* Handy utility functions used at several places in the code */
83 
PrintValue(const Value * value,bool truncate=false)84 static std::string PrintValue(const Value *value, bool truncate = false) {
85   std::string s;
86   if (value) {
87     raw_string_ostream rso(s);
88     value->print(rso);
89     rso.flush();
90     if (truncate)
91       s.resize(s.length() - 1);
92   }
93   return s;
94 }
95 
PrintType(const llvm::Type * type,bool truncate=false)96 static std::string PrintType(const llvm::Type *type, bool truncate = false) {
97   std::string s;
98   raw_string_ostream rso(s);
99   type->print(rso);
100   rso.flush();
101   if (truncate)
102     s.resize(s.length() - 1);
103   return s;
104 }
105 
~IRForTarget()106 IRForTarget::~IRForTarget() {}
107 
FixFunctionLinkage(llvm::Function & llvm_function)108 bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) {
109   llvm_function.setLinkage(GlobalValue::ExternalLinkage);
110 
111   return true;
112 }
113 
DeclForGlobal(const GlobalValue * global_val,Module * module)114 clang::NamedDecl *IRForTarget::DeclForGlobal(const GlobalValue *global_val,
115                                              Module *module) {
116   NamedMDNode *named_metadata =
117       module->getNamedMetadata("clang.global.decl.ptrs");
118 
119   if (!named_metadata)
120     return NULL;
121 
122   unsigned num_nodes = named_metadata->getNumOperands();
123   unsigned node_index;
124 
125   for (node_index = 0; node_index < num_nodes; ++node_index) {
126     llvm::MDNode *metadata_node =
127         dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
128     if (!metadata_node)
129       return NULL;
130 
131     if (metadata_node->getNumOperands() != 2)
132       continue;
133 
134     if (mdconst::dyn_extract_or_null<GlobalValue>(
135             metadata_node->getOperand(0)) != global_val)
136       continue;
137 
138     ConstantInt *constant_int =
139         mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
140 
141     if (!constant_int)
142       return NULL;
143 
144     uintptr_t ptr = constant_int->getZExtValue();
145 
146     return reinterpret_cast<clang::NamedDecl *>(ptr);
147   }
148 
149   return NULL;
150 }
151 
DeclForGlobal(GlobalValue * global_val)152 clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) {
153   return DeclForGlobal(global_val, m_module);
154 }
155 
CreateResultVariable(llvm::Function & llvm_function)156 bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) {
157   lldb_private::Log *log(
158       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
159 
160   if (!m_resolve_vars)
161     return true;
162 
163   // Find the result variable.  If it doesn't exist, we can give up right here.
164 
165   ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
166 
167   std::string result_name_str;
168   const char *result_name = NULL;
169 
170   for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
171                                   ve = value_symbol_table.end();
172        vi != ve; ++vi) {
173     result_name_str = vi->first().str();
174     const char *value_name = result_name_str.c_str();
175 
176     if (strstr(value_name, "$__lldb_expr_result_ptr") &&
177         strncmp(value_name, "_ZGV", 4)) {
178       result_name = value_name;
179       m_result_is_pointer = true;
180       break;
181     }
182 
183     if (strstr(value_name, "$__lldb_expr_result") &&
184         strncmp(value_name, "_ZGV", 4)) {
185       result_name = value_name;
186       m_result_is_pointer = false;
187       break;
188     }
189   }
190 
191   if (!result_name) {
192     if (log)
193       log->PutCString("Couldn't find result variable");
194 
195     return true;
196   }
197 
198   if (log)
199     log->Printf("Result name: \"%s\"", result_name);
200 
201   Value *result_value = m_module->getNamedValue(result_name);
202 
203   if (!result_value) {
204     if (log)
205       log->PutCString("Result variable had no data");
206 
207     m_error_stream.Printf("Internal error [IRForTarget]: Result variable's "
208                           "name (%s) exists, but not its definition\n",
209                           result_name);
210 
211     return false;
212   }
213 
214   if (log)
215     log->Printf("Found result in the IR: \"%s\"",
216                 PrintValue(result_value, false).c_str());
217 
218   GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
219 
220   if (!result_global) {
221     if (log)
222       log->PutCString("Result variable isn't a GlobalVariable");
223 
224     m_error_stream.Printf("Internal error [IRForTarget]: Result variable (%s) "
225                           "is defined, but is not a global variable\n",
226                           result_name);
227 
228     return false;
229   }
230 
231   clang::NamedDecl *result_decl = DeclForGlobal(result_global);
232   if (!result_decl) {
233     if (log)
234       log->PutCString("Result variable doesn't have a corresponding Decl");
235 
236     m_error_stream.Printf("Internal error [IRForTarget]: Result variable (%s) "
237                           "does not have a corresponding Clang entity\n",
238                           result_name);
239 
240     return false;
241   }
242 
243   if (log) {
244     std::string decl_desc_str;
245     raw_string_ostream decl_desc_stream(decl_desc_str);
246     result_decl->print(decl_desc_stream);
247     decl_desc_stream.flush();
248 
249     log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
250   }
251 
252   clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
253   if (!result_var) {
254     if (log)
255       log->PutCString("Result variable Decl isn't a VarDecl");
256 
257     m_error_stream.Printf("Internal error [IRForTarget]: Result variable "
258                           "(%s)'s corresponding Clang entity isn't a "
259                           "variable\n",
260                           result_name);
261 
262     return false;
263   }
264 
265   // Get the next available result name from m_decl_map and create the
266   // persistent variable for it
267 
268   // If the result is an Lvalue, it is emitted as a pointer; see
269   // ASTResultSynthesizer::SynthesizeBodyResult.
270   if (m_result_is_pointer) {
271     clang::QualType pointer_qual_type = result_var->getType();
272     const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
273 
274     const clang::PointerType *pointer_pointertype =
275         pointer_type->getAs<clang::PointerType>();
276     const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
277         pointer_type->getAs<clang::ObjCObjectPointerType>();
278 
279     if (pointer_pointertype) {
280       clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
281 
282       m_result_type = lldb_private::TypeFromParser(
283           element_qual_type.getAsOpaquePtr(),
284           lldb_private::ClangASTContext::GetASTContext(
285               &result_decl->getASTContext()));
286     } else if (pointer_objcobjpointertype) {
287       clang::QualType element_qual_type =
288           clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
289 
290       m_result_type = lldb_private::TypeFromParser(
291           element_qual_type.getAsOpaquePtr(),
292           lldb_private::ClangASTContext::GetASTContext(
293               &result_decl->getASTContext()));
294     } else {
295       if (log)
296         log->PutCString("Expected result to have pointer type, but it did not");
297 
298       m_error_stream.Printf("Internal error [IRForTarget]: Lvalue result (%s) "
299                             "is not a pointer variable\n",
300                             result_name);
301 
302       return false;
303     }
304   } else {
305     m_result_type = lldb_private::TypeFromParser(
306         result_var->getType().getAsOpaquePtr(),
307         lldb_private::ClangASTContext::GetASTContext(
308             &result_decl->getASTContext()));
309   }
310 
311   lldb::TargetSP target_sp(m_execution_unit.GetTarget());
312   lldb_private::ExecutionContext exe_ctx(target_sp, true);
313   llvm::Optional<uint64_t> bit_size =
314       m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope());
315   if (!bit_size) {
316     lldb_private::StreamString type_desc_stream;
317     m_result_type.DumpTypeDescription(&type_desc_stream);
318 
319     if (log)
320       log->Printf("Result type has unknown size");
321 
322     m_error_stream.Printf("Error [IRForTarget]: Size of result type '%s' "
323                           "couldn't be determined\n",
324                           type_desc_stream.GetData());
325     return false;
326   }
327 
328   if (log) {
329     lldb_private::StreamString type_desc_stream;
330     m_result_type.DumpTypeDescription(&type_desc_stream);
331 
332     log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
333   }
334 
335   m_result_name = lldb_private::ConstString("$RESULT_NAME");
336 
337   if (log)
338     log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
339                 m_result_name.GetCString(),
340                 m_result_type.GetByteSize(nullptr).getValueOr(0));
341 
342   // Construct a new result global and set up its metadata
343 
344   GlobalVariable *new_result_global = new GlobalVariable(
345       (*m_module), result_global->getType()->getElementType(),
346       false,                              /* not constant */
347       GlobalValue::ExternalLinkage, NULL, /* no initializer */
348       m_result_name.GetCString());
349 
350   // It's too late in compilation to create a new VarDecl for this, but we
351   // don't need to.  We point the metadata at the old VarDecl.  This creates an
352   // odd anomaly: a variable with a Value whose name is something like $0 and a
353   // Decl whose name is $__lldb_expr_result.  This condition is handled in
354   // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
355   // fixed up.
356 
357   ConstantInt *new_constant_int =
358       ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
359                        reinterpret_cast<uint64_t>(result_decl), false);
360 
361   llvm::Metadata *values[2];
362   values[0] = ConstantAsMetadata::get(new_result_global);
363   values[1] = ConstantAsMetadata::get(new_constant_int);
364 
365   ArrayRef<Metadata *> value_ref(values, 2);
366 
367   MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
368   NamedMDNode *named_metadata =
369       m_module->getNamedMetadata("clang.global.decl.ptrs");
370   named_metadata->addOperand(persistent_global_md);
371 
372   if (log)
373     log->Printf("Replacing \"%s\" with \"%s\"",
374                 PrintValue(result_global).c_str(),
375                 PrintValue(new_result_global).c_str());
376 
377   if (result_global->use_empty()) {
378     // We need to synthesize a store for this variable, because otherwise
379     // there's nothing to put into its equivalent persistent variable.
380 
381     BasicBlock &entry_block(llvm_function.getEntryBlock());
382     Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
383 
384     if (!first_entry_instruction)
385       return false;
386 
387     if (!result_global->hasInitializer()) {
388       if (log)
389         log->Printf("Couldn't find initializer for unused variable");
390 
391       m_error_stream.Printf("Internal error [IRForTarget]: Result variable "
392                             "(%s) has no writes and no initializer\n",
393                             result_name);
394 
395       return false;
396     }
397 
398     Constant *initializer = result_global->getInitializer();
399 
400     StoreInst *synthesized_store =
401         new StoreInst(initializer, new_result_global, first_entry_instruction);
402 
403     if (log)
404       log->Printf("Synthesized result store \"%s\"\n",
405                   PrintValue(synthesized_store).c_str());
406   } else {
407     result_global->replaceAllUsesWith(new_result_global);
408   }
409 
410   if (!m_decl_map->AddPersistentVariable(
411           result_decl, m_result_name, m_result_type, true, m_result_is_pointer))
412     return false;
413 
414   result_global->eraseFromParent();
415 
416   return true;
417 }
418 
RewriteObjCConstString(llvm::GlobalVariable * ns_str,llvm::GlobalVariable * cstr)419 bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str,
420                                          llvm::GlobalVariable *cstr) {
421   lldb_private::Log *log(
422       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
423 
424   Type *ns_str_ty = ns_str->getType();
425 
426   Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
427   Type *i32_ty = Type::getInt32Ty(m_module->getContext());
428   Type *i8_ty = Type::getInt8Ty(m_module->getContext());
429 
430   if (!m_CFStringCreateWithBytes) {
431     lldb::addr_t CFStringCreateWithBytes_addr;
432 
433     static lldb_private::ConstString g_CFStringCreateWithBytes_str(
434         "CFStringCreateWithBytes");
435 
436     CFStringCreateWithBytes_addr =
437         m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str);
438     if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS) {
439       if (log)
440         log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
441 
442       m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C "
443                             "constant string requires "
444                             "CFStringCreateWithBytes\n");
445 
446       return false;
447     }
448 
449     if (log)
450       log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64,
451                   CFStringCreateWithBytes_addr);
452 
453     // Build the function type:
454     //
455     // CFStringRef CFStringCreateWithBytes (
456     //   CFAllocatorRef alloc,
457     //   const UInt8 *bytes,
458     //   CFIndex numBytes,
459     //   CFStringEncoding encoding,
460     //   Boolean isExternalRepresentation
461     // );
462     //
463     // We make the following substitutions:
464     //
465     // CFStringRef -> i8*
466     // CFAllocatorRef -> i8*
467     // UInt8 * -> i8*
468     // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its
469     // pointer size for now) CFStringEncoding -> i32 Boolean -> i8
470 
471     Type *arg_type_array[5];
472 
473     arg_type_array[0] = i8_ptr_ty;
474     arg_type_array[1] = i8_ptr_ty;
475     arg_type_array[2] = m_intptr_ty;
476     arg_type_array[3] = i32_ty;
477     arg_type_array[4] = i8_ty;
478 
479     ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
480 
481     llvm::Type *CFSCWB_ty =
482         FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
483 
484     // Build the constant containing the pointer to the function
485     PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
486     Constant *CFSCWB_addr_int =
487         ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
488     m_CFStringCreateWithBytes =
489         ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
490   }
491 
492   ConstantDataSequential *string_array = NULL;
493 
494   if (cstr)
495     string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
496 
497   Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
498   Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty)
499                              : Constant::getNullValue(i8_ptr_ty);
500   Constant *numBytes_arg = ConstantInt::get(
501       m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false);
502  int encoding_flags = 0;
503  switch (cstr ? string_array->getElementByteSize() : 1) {
504  case 1:
505    encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */
506    break;
507  case 2:
508    encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */
509    break;
510  case 4:
511    encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */
512    break;
513  default:
514    encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */
515    LLDB_LOG(log, "Encountered an Objective-C constant string with unusual "
516                  "element size {0}",
517             string_array->getElementByteSize());
518  }
519  Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false);
520  Constant *isExternal_arg =
521      ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
522 
523  Value *argument_array[5];
524 
525  argument_array[0] = alloc_arg;
526  argument_array[1] = bytes_arg;
527  argument_array[2] = numBytes_arg;
528  argument_array[3] = encoding_arg;
529  argument_array[4] = isExternal_arg;
530 
531  ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
532 
533  FunctionValueCache CFSCWB_Caller(
534      [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
535        return CallInst::Create(
536            m_CFStringCreateWithBytes, CFSCWB_arguments,
537            "CFStringCreateWithBytes",
538            llvm::cast<Instruction>(
539                m_entry_instruction_finder.GetValue(function)));
540      });
541 
542  if (!UnfoldConstant(ns_str, nullptr, CFSCWB_Caller, m_entry_instruction_finder,
543                      m_error_stream)) {
544    if (log)
545      log->PutCString(
546          "Couldn't replace the NSString with the result of the call");
547 
548    m_error_stream.Printf("error [IRForTarget internal]: Couldn't replace an "
549                          "Objective-C constant string with a dynamic "
550                          "string\n");
551 
552    return false;
553   }
554 
555   ns_str->eraseFromParent();
556 
557   return true;
558 }
559 
RewriteObjCConstStrings()560 bool IRForTarget::RewriteObjCConstStrings() {
561   lldb_private::Log *log(
562       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
563 
564   ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
565 
566   for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
567                                   ve = value_symbol_table.end();
568        vi != ve; ++vi) {
569     std::string value_name = vi->first().str();
570     const char *value_name_cstr = value_name.c_str();
571 
572     if (strstr(value_name_cstr, "_unnamed_cfstring_")) {
573       Value *nsstring_value = vi->second;
574 
575       GlobalVariable *nsstring_global =
576           dyn_cast<GlobalVariable>(nsstring_value);
577 
578       if (!nsstring_global) {
579         if (log)
580           log->PutCString("NSString variable is not a GlobalVariable");
581 
582         m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
583                               "constant string is not a global variable\n");
584 
585         return false;
586       }
587 
588       if (!nsstring_global->hasInitializer()) {
589         if (log)
590           log->PutCString("NSString variable does not have an initializer");
591 
592         m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
593                               "constant string does not have an initializer\n");
594 
595         return false;
596       }
597 
598       ConstantStruct *nsstring_struct =
599           dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
600 
601       if (!nsstring_struct) {
602         if (log)
603           log->PutCString(
604               "NSString variable's initializer is not a ConstantStruct");
605 
606         m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
607                               "constant string is not a structure constant\n");
608 
609         return false;
610       }
611 
612       // We expect the following structure:
613       //
614       // struct {
615       //   int *isa;
616       //   int flags;
617       //   char *str;
618       //   long length;
619       // };
620 
621       if (nsstring_struct->getNumOperands() != 4) {
622         if (log)
623           log->Printf("NSString variable's initializer structure has an "
624                       "unexpected number of members.  Should be 4, is %d",
625                       nsstring_struct->getNumOperands());
626 
627         m_error_stream.Printf("Internal error [IRForTarget]: The struct for an "
628                               "Objective-C constant string is not as "
629                               "expected\n");
630 
631         return false;
632       }
633 
634       Constant *nsstring_member = nsstring_struct->getOperand(2);
635 
636       if (!nsstring_member) {
637         if (log)
638           log->PutCString("NSString initializer's str element was empty");
639 
640         m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
641                               "constant string does not have a string "
642                               "initializer\n");
643 
644         return false;
645       }
646 
647       ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
648 
649       if (!nsstring_expr) {
650         if (log)
651           log->PutCString(
652               "NSString initializer's str element is not a ConstantExpr");
653 
654         m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
655                               "constant string's string initializer is not "
656                               "constant\n");
657 
658         return false;
659       }
660 
661       GlobalVariable *cstr_global = nullptr;
662 
663       if (nsstring_expr->getOpcode() == Instruction::GetElementPtr) {
664         Constant *nsstring_cstr = nsstring_expr->getOperand(0);
665         cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
666       } else if (nsstring_expr->getOpcode() == Instruction::BitCast) {
667         Constant *nsstring_cstr = nsstring_expr->getOperand(0);
668         cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
669       }
670 
671       if (!cstr_global) {
672         if (log)
673           log->PutCString(
674               "NSString initializer's str element is not a GlobalVariable");
675 
676         m_error_stream.Printf("Internal error [IRForTarget]: Unhandled"
677                               "constant string initializer\n");
678 
679         return false;
680       }
681 
682       if (!cstr_global->hasInitializer()) {
683         if (log)
684           log->PutCString("NSString initializer's str element does not have an "
685                           "initializer");
686 
687         m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
688                               "constant string's string initializer doesn't "
689                               "point to initialized data\n");
690 
691         return false;
692       }
693 
694       /*
695       if (!cstr_array)
696       {
697           if (log)
698               log->PutCString("NSString initializer's str element is not a
699       ConstantArray");
700 
701           if (m_error_stream)
702               m_error_stream.Printf("Internal error [IRForTarget]: An
703       Objective-C constant string's string initializer doesn't point to an
704       array\n");
705 
706           return false;
707       }
708 
709       if (!cstr_array->isCString())
710       {
711           if (log)
712               log->PutCString("NSString initializer's str element is not a C
713       string array");
714 
715           if (m_error_stream)
716               m_error_stream.Printf("Internal error [IRForTarget]: An
717       Objective-C constant string's string initializer doesn't point to a C
718       string\n");
719 
720           return false;
721       }
722       */
723 
724       ConstantDataArray *cstr_array =
725           dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
726 
727       if (log) {
728         if (cstr_array)
729           log->Printf("Found NSString constant %s, which contains \"%s\"",
730                       value_name_cstr, cstr_array->getAsString().str().c_str());
731         else
732           log->Printf("Found NSString constant %s, which contains \"\"",
733                       value_name_cstr);
734       }
735 
736       if (!cstr_array)
737         cstr_global = NULL;
738 
739       if (!RewriteObjCConstString(nsstring_global, cstr_global)) {
740         if (log)
741           log->PutCString("Error rewriting the constant string");
742 
743         // We don't print an error message here because RewriteObjCConstString
744         // has done so for us.
745 
746         return false;
747       }
748     }
749   }
750 
751   for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
752                                   ve = value_symbol_table.end();
753        vi != ve; ++vi) {
754     std::string value_name = vi->first().str();
755     const char *value_name_cstr = value_name.c_str();
756 
757     if (!strcmp(value_name_cstr, "__CFConstantStringClassReference")) {
758       GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
759 
760       if (!gv) {
761         if (log)
762           log->PutCString(
763               "__CFConstantStringClassReference is not a global variable");
764 
765         m_error_stream.Printf("Internal error [IRForTarget]: Found a "
766                               "CFConstantStringClassReference, but it is not a "
767                               "global object\n");
768 
769         return false;
770       }
771 
772       gv->eraseFromParent();
773 
774       break;
775     }
776   }
777 
778   return true;
779 }
780 
IsObjCSelectorRef(Value * value)781 static bool IsObjCSelectorRef(Value *value) {
782   GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
783 
784   return !(!global_variable || !global_variable->hasName() ||
785            !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_"));
786 }
787 
788 // This function does not report errors; its callers are responsible.
RewriteObjCSelector(Instruction * selector_load)789 bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) {
790   lldb_private::Log *log(
791       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
792 
793   LoadInst *load = dyn_cast<LoadInst>(selector_load);
794 
795   if (!load)
796     return false;
797 
798   // Unpack the message name from the selector.  In LLVM IR, an objc_msgSend
799   // gets represented as
800   //
801   // %tmp     = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> %call    = call
802   // i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
803   //
804   // where %obj is the object pointer and %tmp is the selector.
805   //
806   // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called
807   // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
808   // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
809 
810   // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr)
811   // and get the string from its target
812 
813   GlobalVariable *_objc_selector_references_ =
814       dyn_cast<GlobalVariable>(load->getPointerOperand());
815 
816   if (!_objc_selector_references_ ||
817       !_objc_selector_references_->hasInitializer())
818     return false;
819 
820   Constant *osr_initializer = _objc_selector_references_->getInitializer();
821 
822   ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
823 
824   if (!osr_initializer_expr ||
825       osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
826     return false;
827 
828   Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
829 
830   if (!osr_initializer_base)
831     return false;
832 
833   // Find the string's initializer (a ConstantArray) and get the string from it
834 
835   GlobalVariable *_objc_meth_var_name_ =
836       dyn_cast<GlobalVariable>(osr_initializer_base);
837 
838   if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
839     return false;
840 
841   Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
842 
843   ConstantDataArray *omvn_initializer_array =
844       dyn_cast<ConstantDataArray>(omvn_initializer);
845 
846   if (!omvn_initializer_array->isString())
847     return false;
848 
849   std::string omvn_initializer_string = omvn_initializer_array->getAsString();
850 
851   if (log)
852     log->Printf("Found Objective-C selector reference \"%s\"",
853                 omvn_initializer_string.c_str());
854 
855   // Construct a call to sel_registerName
856 
857   if (!m_sel_registerName) {
858     lldb::addr_t sel_registerName_addr;
859 
860     static lldb_private::ConstString g_sel_registerName_str("sel_registerName");
861     sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str);
862     if (sel_registerName_addr == LLDB_INVALID_ADDRESS)
863       return false;
864 
865     if (log)
866       log->Printf("Found sel_registerName at 0x%" PRIx64,
867                   sel_registerName_addr);
868 
869     // Build the function type: struct objc_selector
870     // *sel_registerName(uint8_t*)
871 
872     // The below code would be "more correct," but in actuality what's required
873     // is uint8_t*
874     // Type *sel_type = StructType::get(m_module->getContext());
875     // Type *sel_ptr_type = PointerType::getUnqual(sel_type);
876     Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
877 
878     Type *type_array[1];
879 
880     type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
881 
882     ArrayRef<Type *> srN_arg_types(type_array, 1);
883 
884     llvm::Type *srN_type =
885         FunctionType::get(sel_ptr_type, srN_arg_types, false);
886 
887     // Build the constant containing the pointer to the function
888     PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
889     Constant *srN_addr_int =
890         ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
891     m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
892   }
893 
894   Value *argument_array[1];
895 
896   Constant *omvn_pointer = ConstantExpr::getBitCast(
897       _objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
898 
899   argument_array[0] = omvn_pointer;
900 
901   ArrayRef<Value *> srN_arguments(argument_array, 1);
902 
903   CallInst *srN_call = CallInst::Create(m_sel_registerName, srN_arguments,
904                                         "sel_registerName", selector_load);
905 
906   // Replace the load with the call in all users
907 
908   selector_load->replaceAllUsesWith(srN_call);
909 
910   selector_load->eraseFromParent();
911 
912   return true;
913 }
914 
RewriteObjCSelectors(BasicBlock & basic_block)915 bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) {
916   lldb_private::Log *log(
917       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
918 
919   BasicBlock::iterator ii;
920 
921   typedef SmallVector<Instruction *, 2> InstrList;
922   typedef InstrList::iterator InstrIterator;
923 
924   InstrList selector_loads;
925 
926   for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
927     Instruction &inst = *ii;
928 
929     if (LoadInst *load = dyn_cast<LoadInst>(&inst))
930       if (IsObjCSelectorRef(load->getPointerOperand()))
931         selector_loads.push_back(&inst);
932   }
933 
934   InstrIterator iter;
935 
936   for (iter = selector_loads.begin(); iter != selector_loads.end(); ++iter) {
937     if (!RewriteObjCSelector(*iter)) {
938       m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
939                             "static reference to an Objective-C selector to a "
940                             "dynamic reference\n");
941 
942       if (log)
943         log->PutCString(
944             "Couldn't rewrite a reference to an Objective-C selector");
945 
946       return false;
947     }
948   }
949 
950   return true;
951 }
952 
IsObjCClassReference(Value * value)953 static bool IsObjCClassReference(Value *value) {
954   GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
955 
956   return !(!global_variable || !global_variable->hasName() ||
957            !global_variable->getName().startswith("OBJC_CLASS_REFERENCES_"));
958 }
959 
960 // This function does not report errors; its callers are responsible.
RewriteObjCClassReference(Instruction * class_load)961 bool IRForTarget::RewriteObjCClassReference(Instruction *class_load) {
962   lldb_private::Log *log(
963       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
964 
965   LoadInst *load = dyn_cast<LoadInst>(class_load);
966 
967   if (!load)
968     return false;
969 
970   // Unpack the class name from the reference.  In LLVM IR, a reference to an
971   // Objective-C class gets represented as
972   //
973   // %tmp     = load %struct._objc_class*,
974   //            %struct._objc_class** @OBJC_CLASS_REFERENCES_, align 4
975   //
976   // @"OBJC_CLASS_REFERENCES_ is a bitcast of a character array called
977   // @OBJC_CLASS_NAME_. @OBJC_CLASS_NAME contains the string.
978 
979   // Find the pointer's initializer (a ConstantExpr with opcode BitCast) and
980   // get the string from its target
981 
982   GlobalVariable *_objc_class_references_ =
983       dyn_cast<GlobalVariable>(load->getPointerOperand());
984 
985   if (!_objc_class_references_ ||
986       !_objc_class_references_->hasInitializer())
987     return false;
988 
989   Constant *ocr_initializer = _objc_class_references_->getInitializer();
990 
991   ConstantExpr *ocr_initializer_expr = dyn_cast<ConstantExpr>(ocr_initializer);
992 
993   if (!ocr_initializer_expr ||
994       ocr_initializer_expr->getOpcode() != Instruction::BitCast)
995     return false;
996 
997   Value *ocr_initializer_base = ocr_initializer_expr->getOperand(0);
998 
999   if (!ocr_initializer_base)
1000     return false;
1001 
1002   // Find the string's initializer (a ConstantArray) and get the string from it
1003 
1004   GlobalVariable *_objc_class_name_ =
1005       dyn_cast<GlobalVariable>(ocr_initializer_base);
1006 
1007   if (!_objc_class_name_ || !_objc_class_name_->hasInitializer())
1008     return false;
1009 
1010   Constant *ocn_initializer = _objc_class_name_->getInitializer();
1011 
1012   ConstantDataArray *ocn_initializer_array =
1013       dyn_cast<ConstantDataArray>(ocn_initializer);
1014 
1015   if (!ocn_initializer_array->isString())
1016     return false;
1017 
1018   std::string ocn_initializer_string = ocn_initializer_array->getAsString();
1019 
1020   if (log)
1021     log->Printf("Found Objective-C class reference \"%s\"",
1022                 ocn_initializer_string.c_str());
1023 
1024   // Construct a call to objc_getClass
1025 
1026   if (!m_objc_getClass) {
1027     lldb::addr_t objc_getClass_addr;
1028 
1029     static lldb_private::ConstString g_objc_getClass_str("objc_getClass");
1030     objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str);
1031     if (objc_getClass_addr == LLDB_INVALID_ADDRESS)
1032       return false;
1033 
1034     if (log)
1035       log->Printf("Found objc_getClass at 0x%" PRIx64,
1036                   objc_getClass_addr);
1037 
1038     // Build the function type: %struct._objc_class *objc_getClass(i8*)
1039 
1040     Type *class_type = load->getType();
1041     Type *type_array[1];
1042     type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1043 
1044     ArrayRef<Type *> ogC_arg_types(type_array, 1);
1045 
1046     llvm::Type *ogC_type =
1047         FunctionType::get(class_type, ogC_arg_types, false);
1048 
1049     // Build the constant containing the pointer to the function
1050     PointerType *ogC_ptr_ty = PointerType::getUnqual(ogC_type);
1051     Constant *ogC_addr_int =
1052         ConstantInt::get(m_intptr_ty, objc_getClass_addr, false);
1053     m_objc_getClass = ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty);
1054   }
1055 
1056   Value *argument_array[1];
1057 
1058   Constant *ocn_pointer = ConstantExpr::getBitCast(
1059       _objc_class_name_, Type::getInt8PtrTy(m_module->getContext()));
1060 
1061   argument_array[0] = ocn_pointer;
1062 
1063   ArrayRef<Value *> ogC_arguments(argument_array, 1);
1064 
1065   CallInst *ogC_call = CallInst::Create(m_objc_getClass, ogC_arguments,
1066                                         "objc_getClass", class_load);
1067 
1068   // Replace the load with the call in all users
1069 
1070   class_load->replaceAllUsesWith(ogC_call);
1071 
1072   class_load->eraseFromParent();
1073 
1074   return true;
1075 }
1076 
RewriteObjCClassReferences(BasicBlock & basic_block)1077 bool IRForTarget::RewriteObjCClassReferences(BasicBlock &basic_block) {
1078   lldb_private::Log *log(
1079       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1080 
1081   BasicBlock::iterator ii;
1082 
1083   typedef SmallVector<Instruction *, 2> InstrList;
1084   typedef InstrList::iterator InstrIterator;
1085 
1086   InstrList class_loads;
1087 
1088   for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1089     Instruction &inst = *ii;
1090 
1091     if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1092       if (IsObjCClassReference(load->getPointerOperand()))
1093         class_loads.push_back(&inst);
1094   }
1095 
1096   InstrIterator iter;
1097 
1098   for (iter = class_loads.begin(); iter != class_loads.end(); ++iter) {
1099     if (!RewriteObjCClassReference(*iter)) {
1100       m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
1101                             "static reference to an Objective-C class to a "
1102                             "dynamic reference\n");
1103 
1104       if (log)
1105         log->PutCString(
1106             "Couldn't rewrite a reference to an Objective-C class");
1107 
1108       return false;
1109     }
1110   }
1111 
1112   return true;
1113 }
1114 
1115 // This function does not report errors; its callers are responsible.
RewritePersistentAlloc(llvm::Instruction * persistent_alloc)1116 bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) {
1117   lldb_private::Log *log(
1118       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1119 
1120   AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1121 
1122   MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1123 
1124   if (!alloc_md || !alloc_md->getNumOperands())
1125     return false;
1126 
1127   ConstantInt *constant_int =
1128       mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
1129 
1130   if (!constant_int)
1131     return false;
1132 
1133   // We attempt to register this as a new persistent variable with the DeclMap.
1134 
1135   uintptr_t ptr = constant_int->getZExtValue();
1136 
1137   clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1138 
1139   lldb_private::TypeFromParser result_decl_type(
1140       decl->getType().getAsOpaquePtr(),
1141       lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext()));
1142 
1143   StringRef decl_name(decl->getName());
1144   lldb_private::ConstString persistent_variable_name(decl_name.data(),
1145                                                      decl_name.size());
1146   if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
1147                                          result_decl_type, false, false))
1148     return false;
1149 
1150   GlobalVariable *persistent_global = new GlobalVariable(
1151       (*m_module), alloc->getType(), false, /* not constant */
1152       GlobalValue::ExternalLinkage, NULL,   /* no initializer */
1153       alloc->getName().str());
1154 
1155   // What we're going to do here is make believe this was a regular old
1156   // external variable.  That means we need to make the metadata valid.
1157 
1158   NamedMDNode *named_metadata =
1159       m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1160 
1161   llvm::Metadata *values[2];
1162   values[0] = ConstantAsMetadata::get(persistent_global);
1163   values[1] = ConstantAsMetadata::get(constant_int);
1164 
1165   ArrayRef<llvm::Metadata *> value_ref(values, 2);
1166 
1167   MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1168   named_metadata->addOperand(persistent_global_md);
1169 
1170   // Now, since the variable is a pointer variable, we will drop in a load of
1171   // that pointer variable.
1172 
1173   LoadInst *persistent_load = new LoadInst(persistent_global, "", alloc);
1174 
1175   if (log)
1176     log->Printf("Replacing \"%s\" with \"%s\"", PrintValue(alloc).c_str(),
1177                 PrintValue(persistent_load).c_str());
1178 
1179   alloc->replaceAllUsesWith(persistent_load);
1180   alloc->eraseFromParent();
1181 
1182   return true;
1183 }
1184 
RewritePersistentAllocs(llvm::BasicBlock & basic_block)1185 bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) {
1186   if (!m_resolve_vars)
1187     return true;
1188 
1189   lldb_private::Log *log(
1190       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1191 
1192   BasicBlock::iterator ii;
1193 
1194   typedef SmallVector<Instruction *, 2> InstrList;
1195   typedef InstrList::iterator InstrIterator;
1196 
1197   InstrList pvar_allocs;
1198 
1199   for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1200     Instruction &inst = *ii;
1201 
1202     if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
1203       llvm::StringRef alloc_name = alloc->getName();
1204 
1205       if (alloc_name.startswith("$") && !alloc_name.startswith("$__lldb")) {
1206         if (alloc_name.find_first_of("0123456789") == 1) {
1207           if (log)
1208             log->Printf("Rejecting a numeric persistent variable.");
1209 
1210           m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, "
1211                                 "$1, ... are reserved for use as result "
1212                                 "names\n");
1213 
1214           return false;
1215         }
1216 
1217         pvar_allocs.push_back(alloc);
1218       }
1219     }
1220   }
1221 
1222   InstrIterator iter;
1223 
1224   for (iter = pvar_allocs.begin(); iter != pvar_allocs.end(); ++iter) {
1225     if (!RewritePersistentAlloc(*iter)) {
1226       m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1227                             "the creation of a persistent variable\n");
1228 
1229       if (log)
1230         log->PutCString(
1231             "Couldn't rewrite the creation of a persistent variable");
1232 
1233       return false;
1234     }
1235   }
1236 
1237   return true;
1238 }
1239 
MaterializeInitializer(uint8_t * data,Constant * initializer)1240 bool IRForTarget::MaterializeInitializer(uint8_t *data, Constant *initializer) {
1241   if (!initializer)
1242     return true;
1243 
1244   lldb_private::Log *log(
1245       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1246 
1247   if (log && log->GetVerbose())
1248     log->Printf("  MaterializeInitializer(%p, %s)", (void *)data,
1249                 PrintValue(initializer).c_str());
1250 
1251   Type *initializer_type = initializer->getType();
1252 
1253   if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer)) {
1254     size_t constant_size = m_target_data->getTypeStoreSize(initializer_type);
1255     lldb_private::Scalar scalar = int_initializer->getValue().zextOrTrunc(
1256         llvm::NextPowerOf2(constant_size) * 8);
1257 
1258     lldb_private::Status get_data_error;
1259     return scalar.GetAsMemoryData(data, constant_size,
1260                                   lldb_private::endian::InlHostByteOrder(),
1261                                   get_data_error) != 0;
1262   } else if (ConstantDataArray *array_initializer =
1263                  dyn_cast<ConstantDataArray>(initializer)) {
1264     if (array_initializer->isString()) {
1265       std::string array_initializer_string = array_initializer->getAsString();
1266       memcpy(data, array_initializer_string.c_str(),
1267              m_target_data->getTypeStoreSize(initializer_type));
1268     } else {
1269       ArrayType *array_initializer_type = array_initializer->getType();
1270       Type *array_element_type = array_initializer_type->getElementType();
1271 
1272       size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1273 
1274       for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i) {
1275         Value *operand_value = array_initializer->getOperand(i);
1276         Constant *operand_constant = dyn_cast<Constant>(operand_value);
1277 
1278         if (!operand_constant)
1279           return false;
1280 
1281         if (!MaterializeInitializer(data + (i * element_size),
1282                                     operand_constant))
1283           return false;
1284       }
1285     }
1286     return true;
1287   } else if (ConstantStruct *struct_initializer =
1288                  dyn_cast<ConstantStruct>(initializer)) {
1289     StructType *struct_initializer_type = struct_initializer->getType();
1290     const StructLayout *struct_layout =
1291         m_target_data->getStructLayout(struct_initializer_type);
1292 
1293     for (unsigned i = 0; i < struct_initializer->getNumOperands(); ++i) {
1294       if (!MaterializeInitializer(data + struct_layout->getElementOffset(i),
1295                                   struct_initializer->getOperand(i)))
1296         return false;
1297     }
1298     return true;
1299   } else if (isa<ConstantAggregateZero>(initializer)) {
1300     memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1301     return true;
1302   }
1303   return false;
1304 }
1305 
1306 // This function does not report errors; its callers are responsible.
MaybeHandleVariable(Value * llvm_value_ptr)1307 bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) {
1308   lldb_private::Log *log(
1309       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1310 
1311   if (log)
1312     log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1313 
1314   if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
1315     switch (constant_expr->getOpcode()) {
1316     default:
1317       break;
1318     case Instruction::GetElementPtr:
1319     case Instruction::BitCast:
1320       Value *s = constant_expr->getOperand(0);
1321       if (!MaybeHandleVariable(s))
1322         return false;
1323     }
1324   } else if (GlobalVariable *global_variable =
1325                  dyn_cast<GlobalVariable>(llvm_value_ptr)) {
1326     if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1327       return true;
1328 
1329     clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1330 
1331     if (!named_decl) {
1332       if (IsObjCSelectorRef(llvm_value_ptr))
1333         return true;
1334 
1335       if (!global_variable->hasExternalLinkage())
1336         return true;
1337 
1338       if (log)
1339         log->Printf("Found global variable \"%s\" without metadata",
1340                     global_variable->getName().str().c_str());
1341 
1342       return false;
1343     }
1344 
1345     std::string name(named_decl->getName().str());
1346 
1347     clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1348     if (value_decl == NULL)
1349       return false;
1350 
1351     lldb_private::CompilerType compiler_type(&value_decl->getASTContext(),
1352                                              value_decl->getType());
1353 
1354     const Type *value_type = NULL;
1355 
1356     if (name[0] == '$') {
1357       // The $__lldb_expr_result name indicates the return value has allocated
1358       // as a static variable.  Per the comment at
1359       // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static
1360       // variable need to be redirected to the result of dereferencing a
1361       // pointer that is passed in as one of the arguments.
1362       //
1363       // Consequently, when reporting the size of the type, we report a pointer
1364       // type pointing to the type of $__lldb_expr_result, not the type itself.
1365       //
1366       // We also do this for any user-declared persistent variables.
1367       compiler_type = compiler_type.GetPointerType();
1368       value_type = PointerType::get(global_variable->getType(), 0);
1369     } else {
1370       value_type = global_variable->getType();
1371     }
1372 
1373     llvm::Optional<uint64_t> value_size = compiler_type.GetByteSize(nullptr);
1374     if (!value_size)
1375       return false;
1376     lldb::offset_t value_alignment =
1377         (compiler_type.GetTypeBitAlign() + 7ull) / 8ull;
1378 
1379     if (log) {
1380       log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64
1381                   ", align %" PRIu64 "]",
1382                   name.c_str(),
1383                   lldb_private::ClangUtil::GetQualType(compiler_type)
1384                       .getAsString()
1385                       .c_str(),
1386                   PrintType(value_type).c_str(), *value_size, value_alignment);
1387     }
1388 
1389     if (named_decl &&
1390         !m_decl_map->AddValueToStruct(
1391             named_decl, lldb_private::ConstString(name.c_str()), llvm_value_ptr,
1392             *value_size, value_alignment)) {
1393       if (!global_variable->hasExternalLinkage())
1394         return true;
1395       else
1396         return true;
1397     }
1398   } else if (dyn_cast<llvm::Function>(llvm_value_ptr)) {
1399     if (log)
1400       log->Printf("Function pointers aren't handled right now");
1401 
1402     return false;
1403   }
1404 
1405   return true;
1406 }
1407 
1408 // This function does not report errors; its callers are responsible.
HandleSymbol(Value * symbol)1409 bool IRForTarget::HandleSymbol(Value *symbol) {
1410   lldb_private::Log *log(
1411       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1412 
1413   lldb_private::ConstString name(symbol->getName().str().c_str());
1414 
1415   lldb::addr_t symbol_addr =
1416       m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny);
1417 
1418   if (symbol_addr == LLDB_INVALID_ADDRESS) {
1419     if (log)
1420       log->Printf("Symbol \"%s\" had no address", name.GetCString());
1421 
1422     return false;
1423   }
1424 
1425   if (log)
1426     log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1427 
1428   Type *symbol_type = symbol->getType();
1429 
1430   Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1431 
1432   Value *symbol_addr_ptr =
1433       ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1434 
1435   if (log)
1436     log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(),
1437                 PrintValue(symbol_addr_ptr).c_str());
1438 
1439   symbol->replaceAllUsesWith(symbol_addr_ptr);
1440 
1441   return true;
1442 }
1443 
MaybeHandleCallArguments(CallInst * Old)1444 bool IRForTarget::MaybeHandleCallArguments(CallInst *Old) {
1445   lldb_private::Log *log(
1446       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1447 
1448   if (log)
1449     log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1450 
1451   for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1452        op_index < num_ops; ++op_index)
1453     if (!MaybeHandleVariable(Old->getArgOperand(
1454             op_index))) // conservatively believe that this is a store
1455     {
1456       m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1457                             "one of the arguments of a function call.\n");
1458 
1459       return false;
1460     }
1461 
1462   return true;
1463 }
1464 
HandleObjCClass(Value * classlist_reference)1465 bool IRForTarget::HandleObjCClass(Value *classlist_reference) {
1466   lldb_private::Log *log(
1467       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1468 
1469   GlobalVariable *global_variable =
1470       dyn_cast<GlobalVariable>(classlist_reference);
1471 
1472   if (!global_variable)
1473     return false;
1474 
1475   Constant *initializer = global_variable->getInitializer();
1476 
1477   if (!initializer)
1478     return false;
1479 
1480   if (!initializer->hasName())
1481     return false;
1482 
1483   StringRef name(initializer->getName());
1484   lldb_private::ConstString name_cstr(name.str().c_str());
1485   lldb::addr_t class_ptr =
1486       m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1487 
1488   if (log)
1489     log->Printf("Found reference to Objective-C class %s (0x%llx)",
1490                 name_cstr.AsCString(), (unsigned long long)class_ptr);
1491 
1492   if (class_ptr == LLDB_INVALID_ADDRESS)
1493     return false;
1494 
1495   if (global_variable->use_empty())
1496     return false;
1497 
1498   SmallVector<LoadInst *, 2> load_instructions;
1499 
1500   for (llvm::User *u : global_variable->users()) {
1501     if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1502       load_instructions.push_back(load_instruction);
1503   }
1504 
1505   if (load_instructions.empty())
1506     return false;
1507 
1508   Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1509 
1510   for (LoadInst *load_instruction : load_instructions) {
1511     Constant *class_bitcast =
1512         ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1513 
1514     load_instruction->replaceAllUsesWith(class_bitcast);
1515 
1516     load_instruction->eraseFromParent();
1517   }
1518 
1519   return true;
1520 }
1521 
RemoveCXAAtExit(BasicBlock & basic_block)1522 bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) {
1523   BasicBlock::iterator ii;
1524 
1525   std::vector<CallInst *> calls_to_remove;
1526 
1527   for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1528     Instruction &inst = *ii;
1529 
1530     CallInst *call = dyn_cast<CallInst>(&inst);
1531 
1532     // MaybeHandleCallArguments handles error reporting; we are silent here
1533     if (!call)
1534       continue;
1535 
1536     bool remove = false;
1537 
1538     llvm::Function *func = call->getCalledFunction();
1539 
1540     if (func && func->getName() == "__cxa_atexit")
1541       remove = true;
1542 
1543     llvm::Value *val = call->getCalledValue();
1544 
1545     if (val && val->getName() == "__cxa_atexit")
1546       remove = true;
1547 
1548     if (remove)
1549       calls_to_remove.push_back(call);
1550   }
1551 
1552   for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(),
1553                                          ce = calls_to_remove.end();
1554        ci != ce; ++ci) {
1555     (*ci)->eraseFromParent();
1556   }
1557 
1558   return true;
1559 }
1560 
ResolveCalls(BasicBlock & basic_block)1561 bool IRForTarget::ResolveCalls(BasicBlock &basic_block) {
1562   /////////////////////////////////////////////////////////////////////////
1563   // Prepare the current basic block for execution in the remote process
1564   //
1565 
1566   BasicBlock::iterator ii;
1567 
1568   for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1569     Instruction &inst = *ii;
1570 
1571     CallInst *call = dyn_cast<CallInst>(&inst);
1572 
1573     // MaybeHandleCallArguments handles error reporting; we are silent here
1574     if (call && !MaybeHandleCallArguments(call))
1575       return false;
1576   }
1577 
1578   return true;
1579 }
1580 
ResolveExternals(Function & llvm_function)1581 bool IRForTarget::ResolveExternals(Function &llvm_function) {
1582   lldb_private::Log *log(
1583       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1584 
1585   for (GlobalVariable &global_var : m_module->globals()) {
1586     std::string global_name = global_var.getName().str();
1587 
1588     if (log)
1589       log->Printf("Examining %s, DeclForGlobalValue returns %p",
1590                   global_name.c_str(),
1591                   static_cast<void *>(DeclForGlobal(&global_var)));
1592 
1593     if (global_name.find("OBJC_IVAR") == 0) {
1594       if (!HandleSymbol(&global_var)) {
1595         m_error_stream.Printf("Error [IRForTarget]: Couldn't find Objective-C "
1596                               "indirect ivar symbol %s\n",
1597                               global_name.c_str());
1598 
1599         return false;
1600       }
1601     } else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") !=
1602                global_name.npos) {
1603       if (!HandleObjCClass(&global_var)) {
1604         m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1605                               "for an Objective-C static method call\n");
1606 
1607         return false;
1608       }
1609     } else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") !=
1610                global_name.npos) {
1611       if (!HandleObjCClass(&global_var)) {
1612         m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1613                               "for an Objective-C static method call\n");
1614 
1615         return false;
1616       }
1617     } else if (DeclForGlobal(&global_var)) {
1618       if (!MaybeHandleVariable(&global_var)) {
1619         m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1620                               "external variable %s\n",
1621                               global_name.c_str());
1622 
1623         return false;
1624       }
1625     }
1626   }
1627 
1628   return true;
1629 }
1630 
isGuardVariableRef(Value * V)1631 static bool isGuardVariableRef(Value *V) {
1632   Constant *Old = NULL;
1633 
1634   if (!(Old = dyn_cast<Constant>(V)))
1635     return false;
1636 
1637   ConstantExpr *CE = NULL;
1638 
1639   if ((CE = dyn_cast<ConstantExpr>(V))) {
1640     if (CE->getOpcode() != Instruction::BitCast)
1641       return false;
1642 
1643     Old = CE->getOperand(0);
1644   }
1645 
1646   GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
1647 
1648   if (!GV || !GV->hasName() ||
1649       (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable
1650        !GV->getName().endswith("@4IA")))    // Microsoft ABI guard variable
1651   {
1652     return false;
1653   }
1654 
1655   return true;
1656 }
1657 
TurnGuardLoadIntoZero(llvm::Instruction * guard_load)1658 void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) {
1659   Constant *zero(Constant::getNullValue(guard_load->getType()));
1660   guard_load->replaceAllUsesWith(zero);
1661   guard_load->eraseFromParent();
1662 }
1663 
ExciseGuardStore(Instruction * guard_store)1664 static void ExciseGuardStore(Instruction *guard_store) {
1665   guard_store->eraseFromParent();
1666 }
1667 
RemoveGuards(BasicBlock & basic_block)1668 bool IRForTarget::RemoveGuards(BasicBlock &basic_block) {
1669   ///////////////////////////////////////////////////////
1670   // Eliminate any reference to guard variables found.
1671   //
1672 
1673   BasicBlock::iterator ii;
1674 
1675   typedef SmallVector<Instruction *, 2> InstrList;
1676   typedef InstrList::iterator InstrIterator;
1677 
1678   InstrList guard_loads;
1679   InstrList guard_stores;
1680 
1681   for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1682     Instruction &inst = *ii;
1683 
1684     if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1685       if (isGuardVariableRef(load->getPointerOperand()))
1686         guard_loads.push_back(&inst);
1687 
1688     if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1689       if (isGuardVariableRef(store->getPointerOperand()))
1690         guard_stores.push_back(&inst);
1691   }
1692 
1693   InstrIterator iter;
1694 
1695   for (iter = guard_loads.begin(); iter != guard_loads.end(); ++iter)
1696     TurnGuardLoadIntoZero(*iter);
1697 
1698   for (iter = guard_stores.begin(); iter != guard_stores.end(); ++iter)
1699     ExciseGuardStore(*iter);
1700 
1701   return true;
1702 }
1703 
1704 // This function does not report errors; its callers are responsible.
UnfoldConstant(Constant * old_constant,llvm::Function * llvm_function,FunctionValueCache & value_maker,FunctionValueCache & entry_instruction_finder,lldb_private::Stream & error_stream)1705 bool IRForTarget::UnfoldConstant(Constant *old_constant,
1706                                  llvm::Function *llvm_function,
1707                                  FunctionValueCache &value_maker,
1708                                  FunctionValueCache &entry_instruction_finder,
1709                                  lldb_private::Stream &error_stream) {
1710   SmallVector<User *, 16> users;
1711 
1712   // We do this because the use list might change, invalidating our iterator.
1713   // Much better to keep a work list ourselves.
1714   for (llvm::User *u : old_constant->users())
1715     users.push_back(u);
1716 
1717   for (size_t i = 0; i < users.size(); ++i) {
1718     User *user = users[i];
1719 
1720     if (Constant *constant = dyn_cast<Constant>(user)) {
1721       // synthesize a new non-constant equivalent of the constant
1722 
1723       if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1724         switch (constant_expr->getOpcode()) {
1725         default:
1726           error_stream.Printf("error [IRForTarget internal]: Unhandled "
1727                               "constant expression type: \"%s\"",
1728                               PrintValue(constant_expr).c_str());
1729           return false;
1730         case Instruction::BitCast: {
1731           FunctionValueCache bit_cast_maker(
1732               [&value_maker, &entry_instruction_finder, old_constant,
1733                constant_expr](llvm::Function *function) -> llvm::Value * {
1734                 // UnaryExpr
1735                 //   OperandList[0] is value
1736 
1737                 if (constant_expr->getOperand(0) != old_constant)
1738                   return constant_expr;
1739 
1740                 return new BitCastInst(
1741                     value_maker.GetValue(function), constant_expr->getType(),
1742                     "", llvm::cast<Instruction>(
1743                             entry_instruction_finder.GetValue(function)));
1744               });
1745 
1746           if (!UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1747                               entry_instruction_finder, error_stream))
1748             return false;
1749         } break;
1750         case Instruction::GetElementPtr: {
1751           // GetElementPtrConstantExpr
1752           //   OperandList[0] is base
1753           //   OperandList[1]... are indices
1754 
1755           FunctionValueCache get_element_pointer_maker(
1756               [&value_maker, &entry_instruction_finder, old_constant,
1757                constant_expr](llvm::Function *function) -> llvm::Value * {
1758                 Value *ptr = constant_expr->getOperand(0);
1759 
1760                 if (ptr == old_constant)
1761                   ptr = value_maker.GetValue(function);
1762 
1763                 std::vector<Value *> index_vector;
1764 
1765                 unsigned operand_index;
1766                 unsigned num_operands = constant_expr->getNumOperands();
1767 
1768                 for (operand_index = 1; operand_index < num_operands;
1769                      ++operand_index) {
1770                   Value *operand = constant_expr->getOperand(operand_index);
1771 
1772                   if (operand == old_constant)
1773                     operand = value_maker.GetValue(function);
1774 
1775                   index_vector.push_back(operand);
1776                 }
1777 
1778                 ArrayRef<Value *> indices(index_vector);
1779 
1780                 return GetElementPtrInst::Create(
1781                     nullptr, ptr, indices, "",
1782                     llvm::cast<Instruction>(
1783                         entry_instruction_finder.GetValue(function)));
1784               });
1785 
1786           if (!UnfoldConstant(constant_expr, llvm_function,
1787                               get_element_pointer_maker,
1788                               entry_instruction_finder, error_stream))
1789             return false;
1790         } break;
1791         }
1792       } else {
1793         error_stream.Printf(
1794             "error [IRForTarget internal]: Unhandled constant type: \"%s\"",
1795             PrintValue(constant).c_str());
1796         return false;
1797       }
1798     } else {
1799       if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1800         if (llvm_function && inst->getParent()->getParent() != llvm_function) {
1801           error_stream.PutCString("error: Capturing non-local variables in "
1802                                   "expressions is unsupported.\n");
1803           return false;
1804         }
1805         inst->replaceUsesOfWith(
1806             old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1807       } else {
1808         error_stream.Printf(
1809             "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"",
1810             PrintValue(user).c_str());
1811         return false;
1812       }
1813     }
1814   }
1815 
1816   if (!isa<GlobalValue>(old_constant)) {
1817     old_constant->destroyConstant();
1818   }
1819 
1820   return true;
1821 }
1822 
ReplaceVariables(Function & llvm_function)1823 bool IRForTarget::ReplaceVariables(Function &llvm_function) {
1824   if (!m_resolve_vars)
1825     return true;
1826 
1827   lldb_private::Log *log(
1828       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1829 
1830   m_decl_map->DoStructLayout();
1831 
1832   if (log)
1833     log->Printf("Element arrangement:");
1834 
1835   uint32_t num_elements;
1836   uint32_t element_index;
1837 
1838   size_t size;
1839   lldb::offset_t alignment;
1840 
1841   if (!m_decl_map->GetStructInfo(num_elements, size, alignment))
1842     return false;
1843 
1844   Function::arg_iterator iter(llvm_function.arg_begin());
1845 
1846   if (iter == llvm_function.arg_end()) {
1847     m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes no "
1848                           "arguments (should take at least a struct pointer)");
1849 
1850     return false;
1851   }
1852 
1853   Argument *argument = &*iter;
1854 
1855   if (argument->getName().equals("this")) {
1856     ++iter;
1857 
1858     if (iter == llvm_function.arg_end()) {
1859       m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1860                             "'this' argument (should take a struct pointer "
1861                             "too)");
1862 
1863       return false;
1864     }
1865 
1866     argument = &*iter;
1867   } else if (argument->getName().equals("self")) {
1868     ++iter;
1869 
1870     if (iter == llvm_function.arg_end()) {
1871       m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1872                             "'self' argument (should take '_cmd' and a struct "
1873                             "pointer too)");
1874 
1875       return false;
1876     }
1877 
1878     if (!iter->getName().equals("_cmd")) {
1879       m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes '%s' "
1880                             "after 'self' argument (should take '_cmd')",
1881                             iter->getName().str().c_str());
1882 
1883       return false;
1884     }
1885 
1886     ++iter;
1887 
1888     if (iter == llvm_function.arg_end()) {
1889       m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1890                             "'self' and '_cmd' arguments (should take a struct "
1891                             "pointer too)");
1892 
1893       return false;
1894     }
1895 
1896     argument = &*iter;
1897   }
1898 
1899   if (!argument->getName().equals("$__lldb_arg")) {
1900     m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes an "
1901                           "argument named '%s' instead of the struct pointer",
1902                           argument->getName().str().c_str());
1903 
1904     return false;
1905   }
1906 
1907   if (log)
1908     log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
1909 
1910   BasicBlock &entry_block(llvm_function.getEntryBlock());
1911   Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
1912 
1913   if (!FirstEntryInstruction) {
1914     m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the "
1915                           "first instruction in the wrapper for use in "
1916                           "rewriting");
1917 
1918     return false;
1919   }
1920 
1921   LLVMContext &context(m_module->getContext());
1922   IntegerType *offset_type(Type::getInt32Ty(context));
1923 
1924   if (!offset_type) {
1925     m_error_stream.Printf(
1926         "Internal error [IRForTarget]: Couldn't produce an offset type");
1927 
1928     return false;
1929   }
1930 
1931   for (element_index = 0; element_index < num_elements; ++element_index) {
1932     const clang::NamedDecl *decl = NULL;
1933     Value *value = NULL;
1934     lldb::offset_t offset;
1935     lldb_private::ConstString name;
1936 
1937     if (!m_decl_map->GetStructElement(decl, value, offset, name,
1938                                       element_index)) {
1939       m_error_stream.Printf(
1940           "Internal error [IRForTarget]: Structure information is incomplete");
1941 
1942       return false;
1943     }
1944 
1945     if (log)
1946       log->Printf("  \"%s\" (\"%s\") placed at %" PRIu64, name.GetCString(),
1947                   decl->getNameAsString().c_str(), offset);
1948 
1949     if (value) {
1950       if (log)
1951         log->Printf("    Replacing [%s]", PrintValue(value).c_str());
1952 
1953       FunctionValueCache body_result_maker(
1954           [this, name, offset_type, offset, argument,
1955            value](llvm::Function *function) -> llvm::Value * {
1956             // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1957             // in cases where the result variable is an rvalue, we have to
1958             // synthesize a dereference of the appropriate structure entry in
1959             // order to produce the static variable that the AST thinks it is
1960             // accessing.
1961 
1962             llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1963                 m_entry_instruction_finder.GetValue(function));
1964 
1965             ConstantInt *offset_int(
1966                 ConstantInt::get(offset_type, offset, true));
1967             GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(
1968                 nullptr, argument, offset_int, "", entry_instruction);
1969 
1970             if (name == m_result_name && !m_result_is_pointer) {
1971               BitCastInst *bit_cast = new BitCastInst(
1972                   get_element_ptr, value->getType()->getPointerTo(), "",
1973                   entry_instruction);
1974 
1975               LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
1976 
1977               return load;
1978             } else {
1979               BitCastInst *bit_cast = new BitCastInst(
1980                   get_element_ptr, value->getType(), "", entry_instruction);
1981 
1982               return bit_cast;
1983             }
1984           });
1985 
1986       if (Constant *constant = dyn_cast<Constant>(value)) {
1987         if (!UnfoldConstant(constant, &llvm_function, body_result_maker,
1988                             m_entry_instruction_finder, m_error_stream)) {
1989           return false;
1990         }
1991       } else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1992         if (instruction->getParent()->getParent() != &llvm_function) {
1993           m_error_stream.PutCString("error: Capturing non-local variables in "
1994                                     "expressions is unsupported.\n");
1995           return false;
1996         }
1997         value->replaceAllUsesWith(
1998             body_result_maker.GetValue(instruction->getParent()->getParent()));
1999       } else {
2000         if (log)
2001           log->Printf("Unhandled non-constant type: \"%s\"",
2002                       PrintValue(value).c_str());
2003         return false;
2004       }
2005 
2006       if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2007         var->eraseFromParent();
2008     }
2009   }
2010 
2011   if (log)
2012     log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]",
2013                 (int64_t)alignment, (uint64_t)size);
2014 
2015   return true;
2016 }
2017 
BuildRelocation(llvm::Type * type,uint64_t offset)2018 llvm::Constant *IRForTarget::BuildRelocation(llvm::Type *type,
2019                                              uint64_t offset) {
2020   llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
2021 
2022   llvm::Constant *offset_array[1];
2023 
2024   offset_array[0] = offset_int;
2025 
2026   llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2027   llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext());
2028   llvm::Type *char_pointer_type = char_type->getPointerTo();
2029 
2030   llvm::Constant *reloc_placeholder_bitcast =
2031       ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type);
2032   llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(
2033       char_type, reloc_placeholder_bitcast, offsets);
2034   llvm::Constant *reloc_bitcast =
2035       ConstantExpr::getBitCast(reloc_getelementptr, type);
2036 
2037   return reloc_bitcast;
2038 }
2039 
runOnModule(Module & llvm_module)2040 bool IRForTarget::runOnModule(Module &llvm_module) {
2041   lldb_private::Log *log(
2042       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2043 
2044   m_module = &llvm_module;
2045   m_target_data.reset(new DataLayout(m_module));
2046   m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(),
2047                                       m_target_data->getPointerSizeInBits());
2048 
2049   if (log) {
2050     std::string s;
2051     raw_string_ostream oss(s);
2052 
2053     m_module->print(oss, NULL);
2054 
2055     oss.flush();
2056 
2057     log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2058   }
2059 
2060   Function *const main_function =
2061       m_func_name.IsEmpty() ? nullptr
2062                             : m_module->getFunction(m_func_name.GetStringRef());
2063 
2064   if (!m_func_name.IsEmpty() && !main_function) {
2065     if (log)
2066       log->Printf("Couldn't find \"%s()\" in the module",
2067                   m_func_name.AsCString());
2068 
2069     m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find wrapper "
2070                           "'%s' in the module",
2071                           m_func_name.AsCString());
2072 
2073     return false;
2074   }
2075 
2076   if (main_function) {
2077     if (!FixFunctionLinkage(*main_function)) {
2078       if (log)
2079         log->Printf("Couldn't fix the linkage for the function");
2080 
2081       return false;
2082     }
2083   }
2084 
2085   llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
2086 
2087   m_reloc_placeholder = new llvm::GlobalVariable(
2088       (*m_module), int8_ty, false /* IsConstant */,
2089       GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty),
2090       "reloc_placeholder", NULL /* InsertBefore */,
2091       GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */);
2092 
2093   ////////////////////////////////////////////////////////////
2094   // Replace $__lldb_expr_result with a persistent variable
2095   //
2096 
2097   if (main_function) {
2098     if (!CreateResultVariable(*main_function)) {
2099       if (log)
2100         log->Printf("CreateResultVariable() failed");
2101 
2102       // CreateResultVariable() reports its own errors, so we don't do so here
2103 
2104       return false;
2105     }
2106   }
2107 
2108   if (log && log->GetVerbose()) {
2109     std::string s;
2110     raw_string_ostream oss(s);
2111 
2112     m_module->print(oss, NULL);
2113 
2114     oss.flush();
2115 
2116     log->Printf("Module after creating the result variable: \n\"%s\"",
2117                 s.c_str());
2118   }
2119 
2120   for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2121        ++fi) {
2122     llvm::Function *function = &*fi;
2123 
2124     if (function->begin() == function->end())
2125       continue;
2126 
2127     Function::iterator bbi;
2128 
2129     for (bbi = function->begin(); bbi != function->end(); ++bbi) {
2130       if (!RemoveGuards(*bbi)) {
2131         if (log)
2132           log->Printf("RemoveGuards() failed");
2133 
2134         // RemoveGuards() reports its own errors, so we don't do so here
2135 
2136         return false;
2137       }
2138 
2139       if (!RewritePersistentAllocs(*bbi)) {
2140         if (log)
2141           log->Printf("RewritePersistentAllocs() failed");
2142 
2143         // RewritePersistentAllocs() reports its own errors, so we don't do so
2144         // here
2145 
2146         return false;
2147       }
2148 
2149       if (!RemoveCXAAtExit(*bbi)) {
2150         if (log)
2151           log->Printf("RemoveCXAAtExit() failed");
2152 
2153         // RemoveCXAAtExit() reports its own errors, so we don't do so here
2154 
2155         return false;
2156       }
2157     }
2158   }
2159 
2160   ///////////////////////////////////////////////////////////////////////////////
2161   // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2162   //
2163 
2164   if (!RewriteObjCConstStrings()) {
2165     if (log)
2166       log->Printf("RewriteObjCConstStrings() failed");
2167 
2168     // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2169 
2170     return false;
2171   }
2172 
2173   for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2174        ++fi) {
2175     llvm::Function *function = &*fi;
2176 
2177     for (llvm::Function::iterator bbi = function->begin(),
2178                                   bbe = function->end();
2179          bbi != bbe; ++bbi) {
2180       if (!RewriteObjCSelectors(*bbi)) {
2181         if (log)
2182           log->Printf("RewriteObjCSelectors() failed");
2183 
2184         // RewriteObjCSelectors() reports its own errors, so we don't do so
2185         // here
2186 
2187         return false;
2188       }
2189 
2190       if (!RewriteObjCClassReferences(*bbi)) {
2191         if (log)
2192           log->Printf("RewriteObjCClassReferences() failed");
2193 
2194         // RewriteObjCClasses() reports its own errors, so we don't do so here
2195 
2196         return false;
2197       }
2198     }
2199   }
2200 
2201   for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2202        ++fi) {
2203     llvm::Function *function = &*fi;
2204 
2205     for (llvm::Function::iterator bbi = function->begin(),
2206                                   bbe = function->end();
2207          bbi != bbe; ++bbi) {
2208       if (!ResolveCalls(*bbi)) {
2209         if (log)
2210           log->Printf("ResolveCalls() failed");
2211 
2212         // ResolveCalls() reports its own errors, so we don't do so here
2213 
2214         return false;
2215       }
2216     }
2217   }
2218 
2219   ////////////////////////////////////////////////////////////////////////
2220   // Run function-level passes that only make sense on the main function
2221   //
2222 
2223   if (main_function) {
2224     if (!ResolveExternals(*main_function)) {
2225       if (log)
2226         log->Printf("ResolveExternals() failed");
2227 
2228       // ResolveExternals() reports its own errors, so we don't do so here
2229 
2230       return false;
2231     }
2232 
2233     if (!ReplaceVariables(*main_function)) {
2234       if (log)
2235         log->Printf("ReplaceVariables() failed");
2236 
2237       // ReplaceVariables() reports its own errors, so we don't do so here
2238 
2239       return false;
2240     }
2241   }
2242 
2243   if (log && log->GetVerbose()) {
2244     std::string s;
2245     raw_string_ostream oss(s);
2246 
2247     m_module->print(oss, NULL);
2248 
2249     oss.flush();
2250 
2251     log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2252   }
2253 
2254   return true;
2255 }
2256 
assignPassManager(PMStack & pass_mgr_stack,PassManagerType pass_mgr_type)2257 void IRForTarget::assignPassManager(PMStack &pass_mgr_stack,
2258                                     PassManagerType pass_mgr_type) {}
2259 
getPotentialPassManagerType() const2260 PassManagerType IRForTarget::getPotentialPassManagerType() const {
2261   return PMT_ModulePassManager;
2262 }
2263