Coverage Report

Created: 2018-07-16 14:58

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