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