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