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