Coverage Report

Created: 2022-01-25 06:29

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