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