blob: e51c9ee07b9ff68af310a3dac127a7bf3a00f7b1 [file] [log] [blame]
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan2ab712f22010-07-03 01:35:46 +00002//
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
Sean Callanan4dbb2712015-09-25 20:35:58 +000010#include "IRForTarget.h"
11
12#include "ClangExpressionDeclMap.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000013
Chandler Carruth1e157582013-01-02 12:20:07 +000014#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"
Ilia Kc9a475d2015-02-13 10:49:18 +000019#include "llvm/IR/LegacyPassManager.h"
Zachary Turner543afa12014-12-09 22:29:47 +000020#include "llvm/IR/Metadata.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "llvm/IR/Module.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000022#include "llvm/IR/ValueSymbolTable.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000023#include "llvm/Support/raw_ostream.h"
24#include "llvm/Transforms/IPO.h"
Sean Callanan549c9f72010-07-13 21:41:46 +000025
26#include "clang/AST/ASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000027
Sean Callanan2ab712f22010-07-03 01:35:46 +000028#include "lldb/Core/Scalar.h"
Zachary Turnerd133f6a2016-03-28 22:53:41 +000029#include "lldb/Core/dwarf.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000030#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000031#include "lldb/Expression/IRInterpreter.h"
Sean Callanan63697e52011-05-07 01:06:41 +000032#include "lldb/Symbol/ClangASTContext.h"
Zachary Turnerd133f6a2016-03-28 22:53:41 +000033#include "lldb/Symbol/ClangUtil.h"
Greg Claytona1e5dc82015-08-11 22:53:00 +000034#include "lldb/Symbol/CompilerType.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000035#include "lldb/Utility/ConstString.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000036#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner01c32432017-02-14 19:06:07 +000037#include "lldb/Utility/Endian.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000038#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000039#include "lldb/Utility/StreamString.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000040
41#include <map>
42
43using namespace llvm;
44
Sean Callananeaacbc92010-08-18 18:50:51 +000045static char ID;
46
Kate Stoneb9c1b512016-09-06 20:57:50 +000047IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker)
48 : m_maker(maker), m_values() {}
Sean Callanan1f9db3e2013-06-28 21:44:15 +000049
Kate Stoneb9c1b512016-09-06 20:57:50 +000050IRForTarget::FunctionValueCache::~FunctionValueCache() {}
Sean Callanan1f9db3e2013-06-28 21:44:15 +000051
Greg Clayton526ae042015-02-12 00:34:25 +000052llvm::Value *
Kate Stoneb9c1b512016-09-06 20:57:50 +000053IRForTarget::FunctionValueCache::GetValue(llvm::Function *function) {
54 if (!m_values.count(function)) {
55 llvm::Value *ret = m_maker(function);
56 m_values[function] = ret;
57 return ret;
58 }
59 return m_values[function];
Sean Callanan1f9db3e2013-06-28 21:44:15 +000060}
61
Kate Stoneb9c1b512016-09-06 20:57:50 +000062static llvm::Value *FindEntryInstruction(llvm::Function *function) {
63 if (function->empty())
64 return NULL;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000065
Kate Stoneb9c1b512016-09-06 20:57:50 +000066 return function->getEntryBlock().getFirstNonPHIOrDbg();
Sean Callanan1f9db3e2013-06-28 21:44:15 +000067}
68
Kate Stoneb9c1b512016-09-06 20:57:50 +000069IRForTarget::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),
Sean Callananac900582016-09-29 00:45:33 +000076 m_sel_registerName(NULL), m_objc_getClass(NULL), m_intptr_ty(NULL),
77 m_error_stream(error_stream),
Kate Stoneb9c1b512016-09-06 20:57:50 +000078 m_execution_unit(execution_unit), m_result_store(NULL),
79 m_result_is_pointer(false), m_reloc_placeholder(NULL),
80 m_entry_instruction_finder(FindEntryInstruction) {}
Sean Callanan2ab712f22010-07-03 01:35:46 +000081
Sean Callanan038df5032010-09-30 21:18:25 +000082/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +000083
Kate Stoneb9c1b512016-09-06 20:57:50 +000084static std::string PrintValue(const Value *value, bool truncate = false) {
85 std::string s;
86 if (value) {
Sean Callanan038df5032010-09-30 21:18:25 +000087 raw_string_ostream rso(s);
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 value->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +000089 rso.flush();
90 if (truncate)
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 s.resize(s.length() - 1);
92 }
93 return s;
Sean Callanan038df5032010-09-30 21:18:25 +000094}
95
Kate Stoneb9c1b512016-09-06 20:57:50 +000096static std::string PrintType(const llvm::Type *type, bool truncate = false) {
97 std::string s;
98 raw_string_ostream rso(s);
99 type->print(rso);
100 rso.flush();
101 if (truncate)
102 s.resize(s.length() - 1);
103 return s;
Sean Callanan2ab712f22010-07-03 01:35:46 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106IRForTarget::~IRForTarget() {}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) {
109 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
110
111 return true;
Sean Callanan79763a42011-05-23 21:40:23 +0000112}
113
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114clang::NamedDecl *IRForTarget::DeclForGlobal(const GlobalValue *global_val,
115 Module *module) {
116 NamedMDNode *named_metadata =
117 module->getNamedMetadata("clang.global.decl.ptrs");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 if (!named_metadata)
Sean Callanan63697e52011-05-07 01:06:41 +0000120 return NULL;
Sean Callanan63697e52011-05-07 01:06:41 +0000121
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 unsigned num_nodes = named_metadata->getNumOperands();
123 unsigned node_index;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 for (node_index = 0; node_index < num_nodes; ++node_index) {
126 llvm::MDNode *metadata_node =
127 dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
128 if (!metadata_node)
129 return NULL;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 if (metadata_node->getNumOperands() != 2)
132 continue;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000133
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 if (mdconst::dyn_extract_or_null<GlobalValue>(
135 metadata_node->getOperand(0)) != global_val)
136 continue;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 ConstantInt *constant_int =
139 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000140
Sean Callanan2235f322010-08-11 03:57:18 +0000141 if (!constant_int)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 return NULL;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000143
Sean Callanan2235f322010-08-11 03:57:18 +0000144 uintptr_t ptr = constant_int->getZExtValue();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 return reinterpret_cast<clang::NamedDecl *>(ptr);
147 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 return NULL;
150}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) {
153 return DeclForGlobal(global_val, m_module);
154}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) {
157 lldb_private::Log *log(
158 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 if (!m_resolve_vars)
161 return true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000162
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 // Find the result variable. If it doesn't exist, we can give up right here.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167 std::string result_name_str;
168 const char *result_name = NULL;
Sean Callanan2235f322010-08-11 03:57:18 +0000169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
171 ve = value_symbol_table.end();
172 vi != ve; ++vi) {
173 result_name_str = vi->first().str();
174 const char *value_name = result_name_str.c_str();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
177 strncmp(value_name, "_ZGV", 4)) {
178 result_name = value_name;
179 m_result_is_pointer = true;
180 break;
181 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 if (strstr(value_name, "$__lldb_expr_result") &&
184 strncmp(value_name, "_ZGV", 4)) {
185 result_name = value_name;
186 m_result_is_pointer = false;
187 break;
188 }
189 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000190
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191 if (!result_name) {
Sean Callanane1175b72011-01-13 21:23:32 +0000192 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 log->PutCString("Couldn't find result variable");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000194
Sean Callanan2235f322010-08-11 03:57:18 +0000195 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 }
Sean Callanan2235f322010-08-11 03:57:18 +0000197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 if (log)
199 log->Printf("Result name: \"%s\"", result_name);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 Value *result_value = m_module->getNamedValue(result_name);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 if (!result_value) {
204 if (log)
205 log->PutCString("Result variable had no data");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 m_error_stream.Printf("Internal error [IRForTarget]: Result variable's "
208 "name (%s) exists, but not its definition\n",
209 result_name);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000210
Sean Callananc70ed462011-10-25 18:36:40 +0000211 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 }
Sean Callananc70ed462011-10-25 18:36:40 +0000213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 if (log)
215 log->Printf("Found result in the IR: \"%s\"",
216 PrintValue(result_value, false).c_str());
217
218 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
219
220 if (!result_global) {
221 if (log)
222 log->PutCString("Result variable isn't a GlobalVariable");
223
224 m_error_stream.Printf("Internal error [IRForTarget]: Result variable (%s) "
225 "is defined, but is not a global variable\n",
226 result_name);
227
228 return false;
229 }
230
231 clang::NamedDecl *result_decl = DeclForGlobal(result_global);
232 if (!result_decl) {
233 if (log)
234 log->PutCString("Result variable doesn't have a corresponding Decl");
235
236 m_error_stream.Printf("Internal error [IRForTarget]: Result variable (%s) "
237 "does not have a corresponding Clang entity\n",
238 result_name);
239
240 return false;
241 }
242
243 if (log) {
244 std::string decl_desc_str;
245 raw_string_ostream decl_desc_stream(decl_desc_str);
246 result_decl->print(decl_desc_stream);
247 decl_desc_stream.flush();
248
249 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
250 }
251
252 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
253 if (!result_var) {
254 if (log)
255 log->PutCString("Result variable Decl isn't a VarDecl");
256
257 m_error_stream.Printf("Internal error [IRForTarget]: Result variable "
258 "(%s)'s corresponding Clang entity isn't a "
259 "variable\n",
260 result_name);
261
262 return false;
263 }
264
265 // Get the next available result name from m_decl_map and create the
Adrian Prantl05097242018-04-30 16:49:04 +0000266 // persistent variable for it
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267
268 // If the result is an Lvalue, it is emitted as a pointer; see
269 // ASTResultSynthesizer::SynthesizeBodyResult.
270 if (m_result_is_pointer) {
271 clang::QualType pointer_qual_type = result_var->getType();
272 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
273
274 const clang::PointerType *pointer_pointertype =
275 pointer_type->getAs<clang::PointerType>();
276 const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
277 pointer_type->getAs<clang::ObjCObjectPointerType>();
278
279 if (pointer_pointertype) {
280 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
281
282 m_result_type = lldb_private::TypeFromParser(
283 element_qual_type.getAsOpaquePtr(),
284 lldb_private::ClangASTContext::GetASTContext(
285 &result_decl->getASTContext()));
286 } else if (pointer_objcobjpointertype) {
287 clang::QualType element_qual_type =
288 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
289
290 m_result_type = lldb_private::TypeFromParser(
291 element_qual_type.getAsOpaquePtr(),
292 lldb_private::ClangASTContext::GetASTContext(
293 &result_decl->getASTContext()));
294 } else {
295 if (log)
296 log->PutCString("Expected result to have pointer type, but it did not");
297
298 m_error_stream.Printf("Internal error [IRForTarget]: Lvalue result (%s) "
299 "is not a pointer variable\n",
300 result_name);
301
302 return false;
303 }
304 } else {
305 m_result_type = lldb_private::TypeFromParser(
306 result_var->getType().getAsOpaquePtr(),
307 lldb_private::ClangASTContext::GetASTContext(
308 &result_decl->getASTContext()));
309 }
310
311 lldb::TargetSP target_sp(m_execution_unit.GetTarget());
312 lldb_private::ExecutionContext exe_ctx(target_sp, true);
313 if (m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope()) == 0) {
314 lldb_private::StreamString type_desc_stream;
315 m_result_type.DumpTypeDescription(&type_desc_stream);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000316
Sean Callanand7a1ca22010-12-02 19:47:57 +0000317 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 log->Printf("Result type has size 0");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000319
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 m_error_stream.Printf("Error [IRForTarget]: Size of result type '%s' "
321 "couldn't be determined\n",
322 type_desc_stream.GetData());
323 return false;
324 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 if (log) {
327 lldb_private::StreamString type_desc_stream;
328 m_result_type.DumpTypeDescription(&type_desc_stream);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000329
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
331 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000332
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 if (log)
336 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
337 m_result_name.GetCString(), m_result_type.GetByteSize(nullptr));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000338
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 // Construct a new result global and set up its metadata
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000340
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 GlobalVariable *new_result_global = new GlobalVariable(
342 (*m_module), result_global->getType()->getElementType(),
343 false, /* not constant */
344 GlobalValue::ExternalLinkage, NULL, /* no initializer */
345 m_result_name.GetCString());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000346
Adrian Prantl05097242018-04-30 16:49:04 +0000347 // It's too late in compilation to create a new VarDecl for this, but we
348 // don't need to. We point the metadata at the old VarDecl. This creates an
349 // odd anomaly: a variable with a Value whose name is something like $0 and a
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 // Decl whose name is $__lldb_expr_result. This condition is handled in
351 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
352 // fixed up.
Greg Clayton57ee3062013-07-11 22:46:58 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 ConstantInt *new_constant_int =
355 ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
356 reinterpret_cast<uint64_t>(result_decl), false);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000357
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 llvm::Metadata *values[2];
359 values[0] = ConstantAsMetadata::get(new_result_global);
360 values[1] = ConstantAsMetadata::get(new_constant_int);
Greg Clayton57ee3062013-07-11 22:46:58 +0000361
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 ArrayRef<Metadata *> value_ref(values, 2);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000363
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
365 NamedMDNode *named_metadata =
366 m_module->getNamedMetadata("clang.global.decl.ptrs");
367 named_metadata->addOperand(persistent_global_md);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 if (log)
370 log->Printf("Replacing \"%s\" with \"%s\"",
371 PrintValue(result_global).c_str(),
372 PrintValue(new_result_global).c_str());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 if (result_global->use_empty()) {
375 // We need to synthesize a store for this variable, because otherwise
376 // there's nothing to put into its equivalent persistent variable.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000377
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000378 BasicBlock &entry_block(llvm_function.getEntryBlock());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 if (!first_entry_instruction)
382 return false;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 if (!result_global->hasInitializer()) {
385 if (log)
386 log->Printf("Couldn't find initializer for unused variable");
387
388 m_error_stream.Printf("Internal error [IRForTarget]: Result variable "
389 "(%s) has no writes and no initializer\n",
390 result_name);
391
392 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +0000393 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 Constant *initializer = result_global->getInitializer();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 StoreInst *synthesized_store =
398 new StoreInst(initializer, new_result_global, first_entry_instruction);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 if (log)
401 log->Printf("Synthesized result store \"%s\"\n",
402 PrintValue(synthesized_store).c_str());
403 } else {
404 result_global->replaceAllUsesWith(new_result_global);
405 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000406
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 if (!m_decl_map->AddPersistentVariable(
408 result_decl, m_result_name, m_result_type, true, m_result_is_pointer))
409 return false;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 result_global->eraseFromParent();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 return true;
414}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str,
417 llvm::GlobalVariable *cstr) {
418 lldb_private::Log *log(
419 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000420
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 Type *ns_str_ty = ns_str->getType();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000422
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
424 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
425 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000426
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 if (!m_CFStringCreateWithBytes) {
428 lldb::addr_t CFStringCreateWithBytes_addr;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000429
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 static lldb_private::ConstString g_CFStringCreateWithBytes_str(
431 "CFStringCreateWithBytes");
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000432
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 CFStringCreateWithBytes_addr =
434 m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str);
435 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS) {
436 if (log)
437 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C "
440 "constant string requires "
441 "CFStringCreateWithBytes\n");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 return false;
Sean Callanan549c9f72010-07-13 21:41:46 +0000444 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000445
Sean Callanan549c9f72010-07-13 21:41:46 +0000446 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64,
448 CFStringCreateWithBytes_addr);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000449
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 // Build the function type:
451 //
452 // CFStringRef CFStringCreateWithBytes (
453 // CFAllocatorRef alloc,
454 // const UInt8 *bytes,
455 // CFIndex numBytes,
456 // CFStringEncoding encoding,
457 // Boolean isExternalRepresentation
458 // );
459 //
460 // We make the following substitutions:
461 //
462 // CFStringRef -> i8*
463 // CFAllocatorRef -> i8*
464 // UInt8 * -> i8*
465 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its
Adrian Prantl05097242018-04-30 16:49:04 +0000466 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467
468 Type *arg_type_array[5];
469
470 arg_type_array[0] = i8_ptr_ty;
471 arg_type_array[1] = i8_ptr_ty;
472 arg_type_array[2] = m_intptr_ty;
473 arg_type_array[3] = i32_ty;
474 arg_type_array[4] = i8_ty;
475
476 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
477
478 llvm::Type *CFSCWB_ty =
479 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
480
481 // Build the constant containing the pointer to the function
482 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
483 Constant *CFSCWB_addr_int =
484 ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
485 m_CFStringCreateWithBytes =
486 ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
487 }
488
489 ConstantDataSequential *string_array = NULL;
490
491 if (cstr)
492 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
493
494 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
495 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty)
496 : Constant::getNullValue(i8_ptr_ty);
497 Constant *numBytes_arg = ConstantInt::get(
Sean Callanancd1eb722016-12-01 17:46:51 +0000498 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false);
499 int encoding_flags = 0;
Sean Callanan01341522016-12-01 19:14:55 +0000500 switch (cstr ? string_array->getElementByteSize() : 1) {
Sean Callanancd1eb722016-12-01 17:46:51 +0000501 case 1:
502 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */
503 break;
504 case 2:
505 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */
506 break;
507 case 4:
508 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */
509 break;
510 default:
511 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */
Pavel Labath107d9bb2017-01-18 11:00:26 +0000512 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual "
Luke Drummond63dea592016-12-22 19:15:07 +0000513 "element size {0}",
Pavel Labath107d9bb2017-01-18 11:00:26 +0000514 string_array->getElementByteSize());
Sean Callanancd1eb722016-12-01 17:46:51 +0000515 }
516 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false);
517 Constant *isExternal_arg =
518 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519
Sean Callanancd1eb722016-12-01 17:46:51 +0000520 Value *argument_array[5];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521
Sean Callanancd1eb722016-12-01 17:46:51 +0000522 argument_array[0] = alloc_arg;
523 argument_array[1] = bytes_arg;
524 argument_array[2] = numBytes_arg;
525 argument_array[3] = encoding_arg;
526 argument_array[4] = isExternal_arg;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527
Sean Callanancd1eb722016-12-01 17:46:51 +0000528 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529
Sean Callanancd1eb722016-12-01 17:46:51 +0000530 FunctionValueCache CFSCWB_Caller(
531 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
532 return CallInst::Create(
533 m_CFStringCreateWithBytes, CFSCWB_arguments,
534 "CFStringCreateWithBytes",
535 llvm::cast<Instruction>(
536 m_entry_instruction_finder.GetValue(function)));
537 });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538
Sean Callanancd1eb722016-12-01 17:46:51 +0000539 if (!UnfoldConstant(ns_str, nullptr, CFSCWB_Caller, m_entry_instruction_finder,
540 m_error_stream)) {
541 if (log)
542 log->PutCString(
543 "Couldn't replace the NSString with the result of the call");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544
Sean Callanancd1eb722016-12-01 17:46:51 +0000545 m_error_stream.Printf("error [IRForTarget internal]: Couldn't replace an "
546 "Objective-C constant string with a dynamic "
547 "string\n");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548
Sean Callanancd1eb722016-12-01 17:46:51 +0000549 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 }
551
552 ns_str->eraseFromParent();
553
554 return true;
Sean Callanan549c9f72010-07-13 21:41:46 +0000555}
556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557bool IRForTarget::RewriteObjCConstStrings() {
558 lldb_private::Log *log(
559 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
564 ve = value_symbol_table.end();
565 vi != ve; ++vi) {
566 std::string value_name = vi->first().str();
567 const char *value_name_cstr = value_name.c_str();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000568
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 if (strstr(value_name_cstr, "_unnamed_cfstring_")) {
570 Value *nsstring_value = vi->second;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 GlobalVariable *nsstring_global =
573 dyn_cast<GlobalVariable>(nsstring_value);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000574
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 if (!nsstring_global) {
576 if (log)
577 log->PutCString("NSString variable is not a GlobalVariable");
578
579 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
580 "constant string is not a global variable\n");
581
582 return false;
583 }
584
585 if (!nsstring_global->hasInitializer()) {
586 if (log)
587 log->PutCString("NSString variable does not have an initializer");
588
589 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
590 "constant string does not have an initializer\n");
591
592 return false;
593 }
594
595 ConstantStruct *nsstring_struct =
596 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
597
598 if (!nsstring_struct) {
599 if (log)
600 log->PutCString(
601 "NSString variable's initializer is not a ConstantStruct");
602
603 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
604 "constant string is not a structure constant\n");
605
606 return false;
607 }
608
609 // We expect the following structure:
610 //
611 // struct {
612 // int *isa;
613 // int flags;
614 // char *str;
615 // long length;
616 // };
617
618 if (nsstring_struct->getNumOperands() != 4) {
619 if (log)
620 log->Printf("NSString variable's initializer structure has an "
621 "unexpected number of members. Should be 4, is %d",
622 nsstring_struct->getNumOperands());
623
624 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an "
625 "Objective-C constant string is not as "
626 "expected\n");
627
628 return false;
629 }
630
631 Constant *nsstring_member = nsstring_struct->getOperand(2);
632
633 if (!nsstring_member) {
634 if (log)
635 log->PutCString("NSString initializer's str element was empty");
636
637 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
638 "constant string does not have a string "
639 "initializer\n");
640
641 return false;
642 }
643
644 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
645
646 if (!nsstring_expr) {
647 if (log)
648 log->PutCString(
649 "NSString initializer's str element is not a ConstantExpr");
650
651 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
652 "constant string's string initializer is not "
653 "constant\n");
654
655 return false;
656 }
657
Sean Callanancd1eb722016-12-01 17:46:51 +0000658 GlobalVariable *cstr_global = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659
Sean Callanancd1eb722016-12-01 17:46:51 +0000660 if (nsstring_expr->getOpcode() == Instruction::GetElementPtr) {
661 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
662 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
663 } else if (nsstring_expr->getOpcode() == Instruction::BitCast) {
664 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
665 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 }
667
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 if (!cstr_global) {
669 if (log)
670 log->PutCString(
671 "NSString initializer's str element is not a GlobalVariable");
672
Sean Callanancd1eb722016-12-01 17:46:51 +0000673 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled"
674 "constant string initializer\n");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675
676 return false;
677 }
678
679 if (!cstr_global->hasInitializer()) {
680 if (log)
681 log->PutCString("NSString initializer's str element does not have an "
682 "initializer");
683
684 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
685 "constant string's string initializer doesn't "
686 "point to initialized data\n");
687
688 return false;
689 }
690
691 /*
692 if (!cstr_array)
693 {
694 if (log)
695 log->PutCString("NSString initializer's str element is not a
696 ConstantArray");
697
698 if (m_error_stream)
699 m_error_stream.Printf("Internal error [IRForTarget]: An
700 Objective-C constant string's string initializer doesn't point to an
701 array\n");
702
703 return false;
704 }
705
706 if (!cstr_array->isCString())
707 {
708 if (log)
709 log->PutCString("NSString initializer's str element is not a C
710 string array");
711
712 if (m_error_stream)
713 m_error_stream.Printf("Internal error [IRForTarget]: An
714 Objective-C constant string's string initializer doesn't point to a C
715 string\n");
716
717 return false;
718 }
719 */
720
721 ConstantDataArray *cstr_array =
722 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
723
724 if (log) {
725 if (cstr_array)
726 log->Printf("Found NSString constant %s, which contains \"%s\"",
727 value_name_cstr, cstr_array->getAsString().str().c_str());
728 else
729 log->Printf("Found NSString constant %s, which contains \"\"",
730 value_name_cstr);
731 }
732
733 if (!cstr_array)
734 cstr_global = NULL;
735
736 if (!RewriteObjCConstString(nsstring_global, cstr_global)) {
737 if (log)
738 log->PutCString("Error rewriting the constant string");
739
740 // We don't print an error message here because RewriteObjCConstString
741 // has done so for us.
742
743 return false;
744 }
745 }
746 }
747
748 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
749 ve = value_symbol_table.end();
750 vi != ve; ++vi) {
751 std::string value_name = vi->first().str();
752 const char *value_name_cstr = value_name.c_str();
753
754 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference")) {
755 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
756
757 if (!gv) {
758 if (log)
759 log->PutCString(
760 "__CFConstantStringClassReference is not a global variable");
761
762 m_error_stream.Printf("Internal error [IRForTarget]: Found a "
763 "CFConstantStringClassReference, but it is not a "
764 "global object\n");
765
766 return false;
767 }
768
769 gv->eraseFromParent();
770
771 break;
772 }
773 }
774
775 return true;
Sean Callanan79763a42011-05-23 21:40:23 +0000776}
777
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778static bool IsObjCSelectorRef(Value *value) {
779 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000780
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 if (!global_variable || !global_variable->hasName() ||
782 !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_"))
783 return false;
784
785 return true;
786}
787
788// This function does not report errors; its callers are responsible.
789bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) {
790 lldb_private::Log *log(
791 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
792
793 LoadInst *load = dyn_cast<LoadInst>(selector_load);
794
795 if (!load)
796 return false;
797
798 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend
799 // gets represented as
800 //
Adrian Prantl05097242018-04-30 16:49:04 +0000801 // %tmp = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> %call = call
802 // i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 //
804 // where %obj is the object pointer and %tmp is the selector.
805 //
806 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called
807 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
808 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
809
810 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr)
811 // and get the string from its target
812
813 GlobalVariable *_objc_selector_references_ =
814 dyn_cast<GlobalVariable>(load->getPointerOperand());
815
816 if (!_objc_selector_references_ ||
817 !_objc_selector_references_->hasInitializer())
818 return false;
819
820 Constant *osr_initializer = _objc_selector_references_->getInitializer();
821
822 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
823
824 if (!osr_initializer_expr ||
825 osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
826 return false;
827
828 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
829
830 if (!osr_initializer_base)
831 return false;
832
833 // Find the string's initializer (a ConstantArray) and get the string from it
834
835 GlobalVariable *_objc_meth_var_name_ =
836 dyn_cast<GlobalVariable>(osr_initializer_base);
837
838 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
839 return false;
840
841 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
842
843 ConstantDataArray *omvn_initializer_array =
844 dyn_cast<ConstantDataArray>(omvn_initializer);
845
846 if (!omvn_initializer_array->isString())
847 return false;
848
849 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
850
851 if (log)
852 log->Printf("Found Objective-C selector reference \"%s\"",
853 omvn_initializer_string.c_str());
854
855 // Construct a call to sel_registerName
856
857 if (!m_sel_registerName) {
858 lldb::addr_t sel_registerName_addr;
859
860 static lldb_private::ConstString g_sel_registerName_str("sel_registerName");
861 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str);
862 if (sel_registerName_addr == LLDB_INVALID_ADDRESS)
863 return false;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000864
Sean Callananc70ed462011-10-25 18:36:40 +0000865 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 log->Printf("Found sel_registerName at 0x%" PRIx64,
867 sel_registerName_addr);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000868
Adrian Prantl05097242018-04-30 16:49:04 +0000869 // Build the function type: struct objc_selector
870 // *sel_registerName(uint8_t*)
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000871
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 // The below code would be "more correct," but in actuality what's required
873 // is uint8_t*
874 // Type *sel_type = StructType::get(m_module->getContext());
875 // Type *sel_ptr_type = PointerType::getUnqual(sel_type);
876 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000877
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 Type *type_array[1];
879
880 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
881
882 ArrayRef<Type *> srN_arg_types(type_array, 1);
883
884 llvm::Type *srN_type =
885 FunctionType::get(sel_ptr_type, srN_arg_types, false);
886
887 // Build the constant containing the pointer to the function
888 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
889 Constant *srN_addr_int =
890 ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
891 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
892 }
893
894 Value *argument_array[1];
895
896 Constant *omvn_pointer = ConstantExpr::getBitCast(
897 _objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
898
899 argument_array[0] = omvn_pointer;
900
901 ArrayRef<Value *> srN_arguments(argument_array, 1);
902
903 CallInst *srN_call = CallInst::Create(m_sel_registerName, srN_arguments,
904 "sel_registerName", selector_load);
905
906 // Replace the load with the call in all users
907
908 selector_load->replaceAllUsesWith(srN_call);
909
910 selector_load->eraseFromParent();
911
912 return true;
913}
914
915bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) {
916 lldb_private::Log *log(
917 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
918
919 BasicBlock::iterator ii;
920
921 typedef SmallVector<Instruction *, 2> InstrList;
922 typedef InstrList::iterator InstrIterator;
923
924 InstrList selector_loads;
925
926 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
927 Instruction &inst = *ii;
928
929 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
930 if (IsObjCSelectorRef(load->getPointerOperand()))
931 selector_loads.push_back(&inst);
932 }
933
934 InstrIterator iter;
935
936 for (iter = selector_loads.begin(); iter != selector_loads.end(); ++iter) {
937 if (!RewriteObjCSelector(*iter)) {
938 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
939 "static reference to an Objective-C selector to a "
940 "dynamic reference\n");
941
942 if (log)
943 log->PutCString(
944 "Couldn't rewrite a reference to an Objective-C selector");
945
946 return false;
Sean Callananc70ed462011-10-25 18:36:40 +0000947 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000949
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 return true;
951}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000952
Sean Callananac900582016-09-29 00:45:33 +0000953static bool IsObjCClassReference(Value *value) {
954 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
955
956 if (!global_variable || !global_variable->hasName() ||
957 !global_variable->getName().startswith("OBJC_CLASS_REFERENCES_"))
958 return false;
959
960 return true;
961}
962
963// This function does not report errors; its callers are responsible.
964bool IRForTarget::RewriteObjCClassReference(Instruction *class_load) {
965 lldb_private::Log *log(
966 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
967
968 LoadInst *load = dyn_cast<LoadInst>(class_load);
969
970 if (!load)
971 return false;
972
973 // Unpack the class name from the reference. In LLVM IR, a reference to an
974 // Objective-C class gets represented as
975 //
976 // %tmp = load %struct._objc_class*,
977 // %struct._objc_class** @OBJC_CLASS_REFERENCES_, align 4
978 //
979 // @"OBJC_CLASS_REFERENCES_ is a bitcast of a character array called
Adrian Prantl05097242018-04-30 16:49:04 +0000980 // @OBJC_CLASS_NAME_. @OBJC_CLASS_NAME contains the string.
Sean Callananac900582016-09-29 00:45:33 +0000981
Adrian Prantl05097242018-04-30 16:49:04 +0000982 // Find the pointer's initializer (a ConstantExpr with opcode BitCast) and
983 // get the string from its target
Sean Callananac900582016-09-29 00:45:33 +0000984
985 GlobalVariable *_objc_class_references_ =
986 dyn_cast<GlobalVariable>(load->getPointerOperand());
987
988 if (!_objc_class_references_ ||
989 !_objc_class_references_->hasInitializer())
990 return false;
991
992 Constant *ocr_initializer = _objc_class_references_->getInitializer();
993
994 ConstantExpr *ocr_initializer_expr = dyn_cast<ConstantExpr>(ocr_initializer);
995
996 if (!ocr_initializer_expr ||
997 ocr_initializer_expr->getOpcode() != Instruction::BitCast)
998 return false;
999
1000 Value *ocr_initializer_base = ocr_initializer_expr->getOperand(0);
1001
1002 if (!ocr_initializer_base)
1003 return false;
1004
1005 // Find the string's initializer (a ConstantArray) and get the string from it
1006
1007 GlobalVariable *_objc_class_name_ =
1008 dyn_cast<GlobalVariable>(ocr_initializer_base);
1009
1010 if (!_objc_class_name_ || !_objc_class_name_->hasInitializer())
1011 return false;
1012
1013 Constant *ocn_initializer = _objc_class_name_->getInitializer();
1014
1015 ConstantDataArray *ocn_initializer_array =
1016 dyn_cast<ConstantDataArray>(ocn_initializer);
1017
1018 if (!ocn_initializer_array->isString())
1019 return false;
1020
1021 std::string ocn_initializer_string = ocn_initializer_array->getAsString();
1022
1023 if (log)
1024 log->Printf("Found Objective-C class reference \"%s\"",
1025 ocn_initializer_string.c_str());
1026
1027 // Construct a call to objc_getClass
1028
1029 if (!m_objc_getClass) {
1030 lldb::addr_t objc_getClass_addr;
1031
1032 static lldb_private::ConstString g_objc_getClass_str("objc_getClass");
1033 objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str);
1034 if (objc_getClass_addr == LLDB_INVALID_ADDRESS)
1035 return false;
1036
1037 if (log)
1038 log->Printf("Found objc_getClass at 0x%" PRIx64,
1039 objc_getClass_addr);
1040
1041 // Build the function type: %struct._objc_class *objc_getClass(i8*)
1042
1043 Type *class_type = load->getType();
1044 Type *type_array[1];
1045 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1046
1047 ArrayRef<Type *> ogC_arg_types(type_array, 1);
1048
1049 llvm::Type *ogC_type =
1050 FunctionType::get(class_type, ogC_arg_types, false);
1051
1052 // Build the constant containing the pointer to the function
1053 PointerType *ogC_ptr_ty = PointerType::getUnqual(ogC_type);
1054 Constant *ogC_addr_int =
1055 ConstantInt::get(m_intptr_ty, objc_getClass_addr, false);
1056 m_objc_getClass = ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty);
1057 }
1058
1059 Value *argument_array[1];
1060
1061 Constant *ocn_pointer = ConstantExpr::getBitCast(
1062 _objc_class_name_, Type::getInt8PtrTy(m_module->getContext()));
1063
1064 argument_array[0] = ocn_pointer;
1065
1066 ArrayRef<Value *> ogC_arguments(argument_array, 1);
1067
1068 CallInst *ogC_call = CallInst::Create(m_objc_getClass, ogC_arguments,
1069 "objc_getClass", class_load);
1070
1071 // Replace the load with the call in all users
1072
1073 class_load->replaceAllUsesWith(ogC_call);
1074
1075 class_load->eraseFromParent();
1076
1077 return true;
1078}
1079
1080bool IRForTarget::RewriteObjCClassReferences(BasicBlock &basic_block) {
1081 lldb_private::Log *log(
1082 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1083
1084 BasicBlock::iterator ii;
1085
1086 typedef SmallVector<Instruction *, 2> InstrList;
1087 typedef InstrList::iterator InstrIterator;
1088
1089 InstrList class_loads;
1090
1091 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1092 Instruction &inst = *ii;
1093
1094 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1095 if (IsObjCClassReference(load->getPointerOperand()))
1096 class_loads.push_back(&inst);
1097 }
1098
1099 InstrIterator iter;
1100
1101 for (iter = class_loads.begin(); iter != class_loads.end(); ++iter) {
1102 if (!RewriteObjCClassReference(*iter)) {
1103 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
1104 "static reference to an Objective-C class to a "
1105 "dynamic reference\n");
1106
1107 if (log)
1108 log->PutCString(
1109 "Couldn't rewrite a reference to an Objective-C class");
1110
1111 return false;
1112 }
1113 }
1114
1115 return true;
1116}
1117
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118// This function does not report errors; its callers are responsible.
1119bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) {
1120 lldb_private::Log *log(
1121 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001122
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00001124
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001126
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 if (!alloc_md || !alloc_md->getNumOperands())
1128 return false;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001129
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 ConstantInt *constant_int =
1131 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001132
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 if (!constant_int)
1134 return false;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001135
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 // We attempt to register this as a new persistent variable with the DeclMap.
Sean Callanan1f9db3e2013-06-28 21:44:15 +00001137
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 uintptr_t ptr = constant_int->getZExtValue();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001139
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001141
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 lldb_private::TypeFromParser result_decl_type(
1143 decl->getType().getAsOpaquePtr(),
1144 lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext()));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001145
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 StringRef decl_name(decl->getName());
1147 lldb_private::ConstString persistent_variable_name(decl_name.data(),
1148 decl_name.size());
1149 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
1150 result_decl_type, false, false))
1151 return false;
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001152
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 GlobalVariable *persistent_global = new GlobalVariable(
1154 (*m_module), alloc->getType(), false, /* not constant */
1155 GlobalValue::ExternalLinkage, NULL, /* no initializer */
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001156 alloc->getName().str());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001157
Adrian Prantl05097242018-04-30 16:49:04 +00001158 // What we're going to do here is make believe this was a regular old
1159 // external variable. That means we need to make the metadata valid.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001160
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161 NamedMDNode *named_metadata =
1162 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001163
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 llvm::Metadata *values[2];
1165 values[0] = ConstantAsMetadata::get(persistent_global);
1166 values[1] = ConstantAsMetadata::get(constant_int);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001167
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 ArrayRef<llvm::Metadata *> value_ref(values, 2);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001169
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1171 named_metadata->addOperand(persistent_global_md);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001172
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 // Now, since the variable is a pointer variable, we will drop in a load of
Adrian Prantl05097242018-04-30 16:49:04 +00001174 // that pointer variable.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001175
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176 LoadInst *persistent_load = new LoadInst(persistent_global, "", alloc);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001177
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178 if (log)
1179 log->Printf("Replacing \"%s\" with \"%s\"", PrintValue(alloc).c_str(),
1180 PrintValue(persistent_load).c_str());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001181
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 alloc->replaceAllUsesWith(persistent_load);
1183 alloc->eraseFromParent();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001184
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 return true;
1186}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001187
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) {
1189 if (!m_resolve_vars)
1190 return true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001191
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 lldb_private::Log *log(
1193 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001194
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 BasicBlock::iterator ii;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001196
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 typedef SmallVector<Instruction *, 2> InstrList;
1198 typedef InstrList::iterator InstrIterator;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001199
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 InstrList pvar_allocs;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001201
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1203 Instruction &inst = *ii;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001204
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
1206 llvm::StringRef alloc_name = alloc->getName();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001207
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208 if (alloc_name.startswith("$") && !alloc_name.startswith("$__lldb")) {
1209 if (alloc_name.find_first_of("0123456789") == 1) {
1210 if (log)
1211 log->Printf("Rejecting a numeric persistent variable.");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001212
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, "
1214 "$1, ... are reserved for use as result "
1215 "names\n");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001216
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 return false;
Sean Callanan00294b32016-03-22 21:05:51 +00001218 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 pvar_allocs.push_back(alloc);
1221 }
Sean Callanan17827832010-12-13 22:46:15 +00001222 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001224
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225 InstrIterator iter;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001226
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 for (iter = pvar_allocs.begin(); iter != pvar_allocs.end(); ++iter) {
1228 if (!RewritePersistentAlloc(*iter)) {
1229 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1230 "the creation of a persistent variable\n");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001231
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232 if (log)
1233 log->PutCString(
1234 "Couldn't rewrite the creation of a persistent variable");
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001237 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 }
1239
1240 return true;
1241}
1242
1243bool IRForTarget::MaterializeInitializer(uint8_t *data, Constant *initializer) {
1244 if (!initializer)
1245 return true;
1246
1247 lldb_private::Log *log(
1248 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1249
1250 if (log && log->GetVerbose())
1251 log->Printf(" MaterializeInitializer(%p, %s)", (void *)data,
1252 PrintValue(initializer).c_str());
1253
1254 Type *initializer_type = initializer->getType();
1255
1256 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer)) {
1257 size_t constant_size = m_target_data->getTypeStoreSize(initializer_type);
1258 lldb_private::Scalar scalar = int_initializer->getValue().zextOrTrunc(
1259 llvm::NextPowerOf2(constant_size) * 8);
1260
Zachary Turner97206d52017-05-12 04:51:55 +00001261 lldb_private::Status get_data_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 if (!scalar.GetAsMemoryData(data, constant_size,
1263 lldb_private::endian::InlHostByteOrder(),
1264 get_data_error))
1265 return false;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001266
1267 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 } else if (ConstantDataArray *array_initializer =
1269 dyn_cast<ConstantDataArray>(initializer)) {
1270 if (array_initializer->isString()) {
1271 std::string array_initializer_string = array_initializer->getAsString();
1272 memcpy(data, array_initializer_string.c_str(),
1273 m_target_data->getTypeStoreSize(initializer_type));
1274 } else {
1275 ArrayType *array_initializer_type = array_initializer->getType();
1276 Type *array_element_type = array_initializer_type->getElementType();
1277
1278 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1279
1280 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i) {
1281 Value *operand_value = array_initializer->getOperand(i);
1282 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1283
1284 if (!operand_constant)
1285 return false;
1286
1287 if (!MaterializeInitializer(data + (i * element_size),
1288 operand_constant))
1289 return false;
1290 }
1291 }
1292 return true;
1293 } else if (ConstantStruct *struct_initializer =
1294 dyn_cast<ConstantStruct>(initializer)) {
1295 StructType *struct_initializer_type = struct_initializer->getType();
1296 const StructLayout *struct_layout =
1297 m_target_data->getStructLayout(struct_initializer_type);
1298
1299 for (unsigned i = 0; i < struct_initializer->getNumOperands(); ++i) {
1300 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i),
1301 struct_initializer->getOperand(i)))
1302 return false;
1303 }
1304 return true;
1305 } else if (isa<ConstantAggregateZero>(initializer)) {
1306 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1307 return true;
1308 }
1309 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001310}
1311
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312// This function does not report errors; its callers are responsible.
1313bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) {
1314 lldb_private::Log *log(
1315 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1316
1317 if (log)
1318 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1319
1320 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
1321 switch (constant_expr->getOpcode()) {
1322 default:
1323 break;
1324 case Instruction::GetElementPtr:
1325 case Instruction::BitCast:
1326 Value *s = constant_expr->getOperand(0);
1327 if (!MaybeHandleVariable(s))
1328 return false;
1329 }
1330 } else if (GlobalVariable *global_variable =
1331 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
1332 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1333 return true;
1334
1335 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1336
1337 if (!named_decl) {
1338 if (IsObjCSelectorRef(llvm_value_ptr))
1339 return true;
1340
1341 if (!global_variable->hasExternalLinkage())
1342 return true;
1343
1344 if (log)
1345 log->Printf("Found global variable \"%s\" without metadata",
1346 global_variable->getName().str().c_str());
1347
1348 return false;
1349 }
1350
1351 std::string name(named_decl->getName().str());
1352
1353 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1354 if (value_decl == NULL)
1355 return false;
1356
1357 lldb_private::CompilerType compiler_type(&value_decl->getASTContext(),
1358 value_decl->getType());
1359
1360 const Type *value_type = NULL;
1361
1362 if (name[0] == '$') {
1363 // The $__lldb_expr_result name indicates the return value has allocated
Adrian Prantl05097242018-04-30 16:49:04 +00001364 // as a static variable. Per the comment at
1365 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static
1366 // variable need to be redirected to the result of dereferencing a
1367 // pointer that is passed in as one of the arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 //
1369 // Consequently, when reporting the size of the type, we report a pointer
Adrian Prantl05097242018-04-30 16:49:04 +00001370 // type pointing to the type of $__lldb_expr_result, not the type itself.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 //
1372 // We also do this for any user-declared persistent variables.
1373 compiler_type = compiler_type.GetPointerType();
1374 value_type = PointerType::get(global_variable->getType(), 0);
1375 } else {
1376 value_type = global_variable->getType();
1377 }
1378
1379 const uint64_t value_size = compiler_type.GetByteSize(nullptr);
1380 lldb::offset_t value_alignment =
1381 (compiler_type.GetTypeBitAlign() + 7ull) / 8ull;
1382
1383 if (log) {
1384 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64
1385 ", align %" PRIu64 "]",
1386 name.c_str(),
1387 lldb_private::ClangUtil::GetQualType(compiler_type)
1388 .getAsString()
1389 .c_str(),
1390 PrintType(value_type).c_str(), value_size, value_alignment);
1391 }
1392
1393 if (named_decl &&
1394 !m_decl_map->AddValueToStruct(
1395 named_decl, lldb_private::ConstString(name.c_str()), llvm_value_ptr,
1396 value_size, value_alignment)) {
1397 if (!global_variable->hasExternalLinkage())
1398 return true;
1399 else
1400 return true;
1401 }
1402 } else if (dyn_cast<llvm::Function>(llvm_value_ptr)) {
1403 if (log)
1404 log->Printf("Function pointers aren't handled right now");
1405
1406 return false;
1407 }
1408
1409 return true;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001410}
1411
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412// This function does not report errors; its callers are responsible.
1413bool IRForTarget::HandleSymbol(Value *symbol) {
1414 lldb_private::Log *log(
1415 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1416
1417 lldb_private::ConstString name(symbol->getName().str().c_str());
1418
1419 lldb::addr_t symbol_addr =
1420 m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny);
1421
1422 if (symbol_addr == LLDB_INVALID_ADDRESS) {
1423 if (log)
1424 log->Printf("Symbol \"%s\" had no address", name.GetCString());
1425
1426 return false;
1427 }
1428
1429 if (log)
1430 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1431
1432 Type *symbol_type = symbol->getType();
1433
1434 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1435
1436 Value *symbol_addr_ptr =
1437 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1438
1439 if (log)
1440 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(),
1441 PrintValue(symbol_addr_ptr).c_str());
1442
1443 symbol->replaceAllUsesWith(symbol_addr_ptr);
1444
1445 return true;
1446}
1447
1448bool IRForTarget::MaybeHandleCallArguments(CallInst *Old) {
1449 lldb_private::Log *log(
1450 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1451
1452 if (log)
1453 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1454
1455 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1456 op_index < num_ops; ++op_index)
1457 if (!MaybeHandleVariable(Old->getArgOperand(
1458 op_index))) // conservatively believe that this is a store
1459 {
1460 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1461 "one of the arguments of a function call.\n");
1462
1463 return false;
1464 }
1465
1466 return true;
1467}
1468
1469bool IRForTarget::HandleObjCClass(Value *classlist_reference) {
1470 lldb_private::Log *log(
1471 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1472
1473 GlobalVariable *global_variable =
1474 dyn_cast<GlobalVariable>(classlist_reference);
1475
1476 if (!global_variable)
1477 return false;
1478
1479 Constant *initializer = global_variable->getInitializer();
1480
1481 if (!initializer)
1482 return false;
1483
1484 if (!initializer->hasName())
1485 return false;
1486
1487 StringRef name(initializer->getName());
1488 lldb_private::ConstString name_cstr(name.str().c_str());
1489 lldb::addr_t class_ptr =
1490 m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1491
1492 if (log)
1493 log->Printf("Found reference to Objective-C class %s (0x%llx)",
1494 name_cstr.AsCString(), (unsigned long long)class_ptr);
1495
1496 if (class_ptr == LLDB_INVALID_ADDRESS)
1497 return false;
1498
1499 if (global_variable->use_empty())
1500 return false;
1501
1502 SmallVector<LoadInst *, 2> load_instructions;
1503
1504 for (llvm::User *u : global_variable->users()) {
1505 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1506 load_instructions.push_back(load_instruction);
1507 }
1508
1509 if (load_instructions.empty())
1510 return false;
1511
1512 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1513
1514 for (LoadInst *load_instruction : load_instructions) {
1515 Constant *class_bitcast =
1516 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1517
1518 load_instruction->replaceAllUsesWith(class_bitcast);
1519
1520 load_instruction->eraseFromParent();
1521 }
1522
1523 return true;
1524}
1525
1526bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) {
1527 BasicBlock::iterator ii;
1528
1529 std::vector<CallInst *> calls_to_remove;
1530
1531 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1532 Instruction &inst = *ii;
1533
1534 CallInst *call = dyn_cast<CallInst>(&inst);
1535
1536 // MaybeHandleCallArguments handles error reporting; we are silent here
1537 if (!call)
1538 continue;
1539
1540 bool remove = false;
1541
1542 llvm::Function *func = call->getCalledFunction();
1543
1544 if (func && func->getName() == "__cxa_atexit")
1545 remove = true;
1546
1547 llvm::Value *val = call->getCalledValue();
1548
1549 if (val && val->getName() == "__cxa_atexit")
1550 remove = true;
1551
1552 if (remove)
1553 calls_to_remove.push_back(call);
1554 }
1555
1556 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(),
1557 ce = calls_to_remove.end();
1558 ci != ce; ++ci) {
1559 (*ci)->eraseFromParent();
1560 }
1561
1562 return true;
1563}
1564
1565bool IRForTarget::ResolveCalls(BasicBlock &basic_block) {
1566 /////////////////////////////////////////////////////////////////////////
1567 // Prepare the current basic block for execution in the remote process
1568 //
1569
1570 BasicBlock::iterator ii;
1571
1572 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1573 Instruction &inst = *ii;
1574
1575 CallInst *call = dyn_cast<CallInst>(&inst);
1576
1577 // MaybeHandleCallArguments handles error reporting; we are silent here
1578 if (call && !MaybeHandleCallArguments(call))
1579 return false;
1580 }
1581
1582 return true;
1583}
1584
1585bool IRForTarget::ResolveExternals(Function &llvm_function) {
1586 lldb_private::Log *log(
1587 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1588
1589 for (GlobalVariable &global_var : m_module->globals()) {
1590 std::string global_name = global_var.getName().str();
1591
1592 if (log)
1593 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1594 global_name.c_str(),
1595 static_cast<void *>(DeclForGlobal(&global_var)));
1596
1597 if (global_name.find("OBJC_IVAR") == 0) {
1598 if (!HandleSymbol(&global_var)) {
1599 m_error_stream.Printf("Error [IRForTarget]: Couldn't find Objective-C "
1600 "indirect ivar symbol %s\n",
1601 global_name.c_str());
1602
1603 return false;
1604 }
1605 } else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") !=
1606 global_name.npos) {
1607 if (!HandleObjCClass(&global_var)) {
1608 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1609 "for an Objective-C static method call\n");
1610
1611 return false;
1612 }
1613 } else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") !=
1614 global_name.npos) {
1615 if (!HandleObjCClass(&global_var)) {
1616 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1617 "for an Objective-C static method call\n");
1618
1619 return false;
1620 }
1621 } else if (DeclForGlobal(&global_var)) {
1622 if (!MaybeHandleVariable(&global_var)) {
1623 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1624 "external variable %s\n",
1625 global_name.c_str());
1626
1627 return false;
1628 }
1629 }
1630 }
1631
1632 return true;
1633}
1634
1635static bool isGuardVariableRef(Value *V) {
1636 Constant *Old = NULL;
1637
1638 if (!(Old = dyn_cast<Constant>(V)))
1639 return false;
1640
1641 ConstantExpr *CE = NULL;
1642
1643 if ((CE = dyn_cast<ConstantExpr>(V))) {
1644 if (CE->getOpcode() != Instruction::BitCast)
1645 return false;
1646
1647 Old = CE->getOperand(0);
1648 }
1649
1650 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
1651
1652 if (!GV || !GV->hasName() ||
1653 (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable
1654 !GV->getName().endswith("@4IA"))) // Microsoft ABI guard variable
1655 {
1656 return false;
1657 }
1658
1659 return true;
1660}
1661
1662void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) {
1663 Constant *zero(Constant::getNullValue(guard_load->getType()));
1664 guard_load->replaceAllUsesWith(zero);
1665 guard_load->eraseFromParent();
1666}
1667
1668static void ExciseGuardStore(Instruction *guard_store) {
1669 guard_store->eraseFromParent();
1670}
1671
1672bool IRForTarget::RemoveGuards(BasicBlock &basic_block) {
1673 ///////////////////////////////////////////////////////
1674 // Eliminate any reference to guard variables found.
1675 //
1676
1677 BasicBlock::iterator ii;
1678
1679 typedef SmallVector<Instruction *, 2> InstrList;
1680 typedef InstrList::iterator InstrIterator;
1681
1682 InstrList guard_loads;
1683 InstrList guard_stores;
1684
1685 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1686 Instruction &inst = *ii;
1687
1688 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1689 if (isGuardVariableRef(load->getPointerOperand()))
1690 guard_loads.push_back(&inst);
1691
1692 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1693 if (isGuardVariableRef(store->getPointerOperand()))
1694 guard_stores.push_back(&inst);
1695 }
1696
1697 InstrIterator iter;
1698
1699 for (iter = guard_loads.begin(); iter != guard_loads.end(); ++iter)
1700 TurnGuardLoadIntoZero(*iter);
1701
1702 for (iter = guard_stores.begin(); iter != guard_stores.end(); ++iter)
1703 ExciseGuardStore(*iter);
1704
1705 return true;
1706}
1707
1708// This function does not report errors; its callers are responsible.
1709bool IRForTarget::UnfoldConstant(Constant *old_constant,
1710 llvm::Function *llvm_function,
1711 FunctionValueCache &value_maker,
1712 FunctionValueCache &entry_instruction_finder,
1713 lldb_private::Stream &error_stream) {
1714 SmallVector<User *, 16> users;
1715
1716 // We do this because the use list might change, invalidating our iterator.
1717 // Much better to keep a work list ourselves.
1718 for (llvm::User *u : old_constant->users())
1719 users.push_back(u);
1720
1721 for (size_t i = 0; i < users.size(); ++i) {
1722 User *user = users[i];
1723
1724 if (Constant *constant = dyn_cast<Constant>(user)) {
1725 // synthesize a new non-constant equivalent of the constant
1726
1727 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1728 switch (constant_expr->getOpcode()) {
1729 default:
1730 error_stream.Printf("error [IRForTarget internal]: Unhandled "
1731 "constant expression type: \"%s\"",
1732 PrintValue(constant_expr).c_str());
1733 return false;
1734 case Instruction::BitCast: {
1735 FunctionValueCache bit_cast_maker(
1736 [&value_maker, &entry_instruction_finder, old_constant,
1737 constant_expr](llvm::Function *function) -> llvm::Value * {
1738 // UnaryExpr
1739 // OperandList[0] is value
1740
1741 if (constant_expr->getOperand(0) != old_constant)
1742 return constant_expr;
1743
1744 return new BitCastInst(
1745 value_maker.GetValue(function), constant_expr->getType(),
1746 "", llvm::cast<Instruction>(
1747 entry_instruction_finder.GetValue(function)));
1748 });
1749
1750 if (!UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1751 entry_instruction_finder, error_stream))
1752 return false;
1753 } break;
1754 case Instruction::GetElementPtr: {
1755 // GetElementPtrConstantExpr
1756 // OperandList[0] is base
1757 // OperandList[1]... are indices
1758
1759 FunctionValueCache get_element_pointer_maker(
1760 [&value_maker, &entry_instruction_finder, old_constant,
1761 constant_expr](llvm::Function *function) -> llvm::Value * {
1762 Value *ptr = constant_expr->getOperand(0);
1763
1764 if (ptr == old_constant)
1765 ptr = value_maker.GetValue(function);
1766
1767 std::vector<Value *> index_vector;
1768
1769 unsigned operand_index;
1770 unsigned num_operands = constant_expr->getNumOperands();
1771
1772 for (operand_index = 1; operand_index < num_operands;
1773 ++operand_index) {
1774 Value *operand = constant_expr->getOperand(operand_index);
1775
1776 if (operand == old_constant)
1777 operand = value_maker.GetValue(function);
1778
1779 index_vector.push_back(operand);
1780 }
1781
1782 ArrayRef<Value *> indices(index_vector);
1783
1784 return GetElementPtrInst::Create(
1785 nullptr, ptr, indices, "",
1786 llvm::cast<Instruction>(
1787 entry_instruction_finder.GetValue(function)));
1788 });
1789
1790 if (!UnfoldConstant(constant_expr, llvm_function,
1791 get_element_pointer_maker,
1792 entry_instruction_finder, error_stream))
1793 return false;
1794 } break;
1795 }
1796 } else {
1797 error_stream.Printf(
1798 "error [IRForTarget internal]: Unhandled constant type: \"%s\"",
1799 PrintValue(constant).c_str());
1800 return false;
1801 }
1802 } else {
1803 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1804 if (llvm_function && inst->getParent()->getParent() != llvm_function) {
1805 error_stream.PutCString("error: Capturing non-local variables in "
1806 "expressions is unsupported.\n");
1807 return false;
1808 }
1809 inst->replaceUsesOfWith(
1810 old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1811 } else {
1812 error_stream.Printf(
1813 "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"",
1814 PrintValue(user).c_str());
1815 return false;
1816 }
1817 }
1818 }
1819
1820 if (!isa<GlobalValue>(old_constant)) {
1821 old_constant->destroyConstant();
1822 }
1823
1824 return true;
1825}
1826
1827bool IRForTarget::ReplaceVariables(Function &llvm_function) {
1828 if (!m_resolve_vars)
1829 return true;
1830
1831 lldb_private::Log *log(
1832 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1833
1834 m_decl_map->DoStructLayout();
1835
1836 if (log)
1837 log->Printf("Element arrangement:");
1838
1839 uint32_t num_elements;
1840 uint32_t element_index;
1841
1842 size_t size;
1843 lldb::offset_t alignment;
1844
1845 if (!m_decl_map->GetStructInfo(num_elements, size, alignment))
1846 return false;
1847
Reid Kleckner20670ba2017-03-16 23:13:49 +00001848 Function::arg_iterator iter(llvm_function.arg_begin());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849
Reid Kleckner20670ba2017-03-16 23:13:49 +00001850 if (iter == llvm_function.arg_end()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes no "
1852 "arguments (should take at least a struct pointer)");
1853
1854 return false;
1855 }
1856
1857 Argument *argument = &*iter;
1858
1859 if (argument->getName().equals("this")) {
1860 ++iter;
1861
Reid Kleckner20670ba2017-03-16 23:13:49 +00001862 if (iter == llvm_function.arg_end()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001863 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1864 "'this' argument (should take a struct pointer "
1865 "too)");
1866
1867 return false;
1868 }
1869
1870 argument = &*iter;
1871 } else if (argument->getName().equals("self")) {
1872 ++iter;
1873
Reid Kleckner20670ba2017-03-16 23:13:49 +00001874 if (iter == llvm_function.arg_end()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1876 "'self' argument (should take '_cmd' and a struct "
1877 "pointer too)");
1878
1879 return false;
1880 }
1881
1882 if (!iter->getName().equals("_cmd")) {
1883 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes '%s' "
1884 "after 'self' argument (should take '_cmd')",
1885 iter->getName().str().c_str());
1886
1887 return false;
1888 }
1889
1890 ++iter;
1891
Reid Kleckner20670ba2017-03-16 23:13:49 +00001892 if (iter == llvm_function.arg_end()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001893 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1894 "'self' and '_cmd' arguments (should take a struct "
1895 "pointer too)");
1896
1897 return false;
1898 }
1899
1900 argument = &*iter;
1901 }
1902
1903 if (!argument->getName().equals("$__lldb_arg")) {
1904 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes an "
1905 "argument named '%s' instead of the struct pointer",
1906 argument->getName().str().c_str());
1907
1908 return false;
1909 }
1910
1911 if (log)
1912 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
1913
1914 BasicBlock &entry_block(llvm_function.getEntryBlock());
1915 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
1916
1917 if (!FirstEntryInstruction) {
1918 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the "
1919 "first instruction in the wrapper for use in "
1920 "rewriting");
1921
1922 return false;
1923 }
1924
1925 LLVMContext &context(m_module->getContext());
1926 IntegerType *offset_type(Type::getInt32Ty(context));
1927
1928 if (!offset_type) {
1929 m_error_stream.Printf(
1930 "Internal error [IRForTarget]: Couldn't produce an offset type");
1931
1932 return false;
1933 }
1934
1935 for (element_index = 0; element_index < num_elements; ++element_index) {
1936 const clang::NamedDecl *decl = NULL;
1937 Value *value = NULL;
1938 lldb::offset_t offset;
1939 lldb_private::ConstString name;
1940
1941 if (!m_decl_map->GetStructElement(decl, value, offset, name,
1942 element_index)) {
1943 m_error_stream.Printf(
1944 "Internal error [IRForTarget]: Structure information is incomplete");
1945
1946 return false;
1947 }
1948
1949 if (log)
1950 log->Printf(" \"%s\" (\"%s\") placed at %" PRIu64, name.GetCString(),
1951 decl->getNameAsString().c_str(), offset);
1952
1953 if (value) {
1954 if (log)
1955 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
1956
1957 FunctionValueCache body_result_maker(
1958 [this, name, offset_type, offset, argument,
1959 value](llvm::Function *function) -> llvm::Value * {
Adrian Prantl05097242018-04-30 16:49:04 +00001960 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1961 // in cases where the result variable is an rvalue, we have to
1962 // synthesize a dereference of the appropriate structure entry in
1963 // order to produce the static variable that the AST thinks it is
1964 // accessing.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965
1966 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1967 m_entry_instruction_finder.GetValue(function));
1968
1969 ConstantInt *offset_int(
1970 ConstantInt::get(offset_type, offset, true));
1971 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(
1972 nullptr, argument, offset_int, "", entry_instruction);
1973
1974 if (name == m_result_name && !m_result_is_pointer) {
1975 BitCastInst *bit_cast = new BitCastInst(
1976 get_element_ptr, value->getType()->getPointerTo(), "",
1977 entry_instruction);
1978
1979 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
1980
1981 return load;
1982 } else {
1983 BitCastInst *bit_cast = new BitCastInst(
1984 get_element_ptr, value->getType(), "", entry_instruction);
1985
1986 return bit_cast;
1987 }
1988 });
1989
1990 if (Constant *constant = dyn_cast<Constant>(value)) {
1991 if (!UnfoldConstant(constant, &llvm_function, body_result_maker,
1992 m_entry_instruction_finder, m_error_stream)) {
1993 return false;
1994 }
1995 } else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1996 if (instruction->getParent()->getParent() != &llvm_function) {
1997 m_error_stream.PutCString("error: Capturing non-local variables in "
1998 "expressions is unsupported.\n");
1999 return false;
2000 }
2001 value->replaceAllUsesWith(
2002 body_result_maker.GetValue(instruction->getParent()->getParent()));
2003 } else {
2004 if (log)
2005 log->Printf("Unhandled non-constant type: \"%s\"",
2006 PrintValue(value).c_str());
2007 return false;
2008 }
2009
2010 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2011 var->eraseFromParent();
2012 }
2013 }
2014
2015 if (log)
2016 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]",
2017 (int64_t)alignment, (uint64_t)size);
2018
2019 return true;
2020}
2021
2022llvm::Constant *IRForTarget::BuildRelocation(llvm::Type *type,
2023 uint64_t offset) {
2024 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
2025
2026 llvm::Constant *offset_array[1];
2027
2028 offset_array[0] = offset_int;
2029
2030 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2031 llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext());
2032 llvm::Type *char_pointer_type = char_type->getPointerTo();
2033
2034 llvm::Constant *reloc_placeholder_bitcast =
2035 ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type);
2036 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(
2037 char_type, reloc_placeholder_bitcast, offsets);
2038 llvm::Constant *reloc_bitcast =
2039 ConstantExpr::getBitCast(reloc_getelementptr, type);
2040
2041 return reloc_bitcast;
2042}
2043
2044bool IRForTarget::runOnModule(Module &llvm_module) {
2045 lldb_private::Log *log(
2046 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2047
2048 m_module = &llvm_module;
2049 m_target_data.reset(new DataLayout(m_module));
2050 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(),
2051 m_target_data->getPointerSizeInBits());
2052
2053 if (log) {
2054 std::string s;
2055 raw_string_ostream oss(s);
2056
2057 m_module->print(oss, NULL);
2058
2059 oss.flush();
2060
2061 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2062 }
2063
2064 Function *const main_function =
2065 m_func_name.IsEmpty() ? nullptr
2066 : m_module->getFunction(m_func_name.GetStringRef());
2067
2068 if (!m_func_name.IsEmpty() && !main_function) {
2069 if (log)
2070 log->Printf("Couldn't find \"%s()\" in the module",
2071 m_func_name.AsCString());
2072
2073 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find wrapper "
2074 "'%s' in the module",
2075 m_func_name.AsCString());
2076
2077 return false;
2078 }
2079
2080 if (main_function) {
2081 if (!FixFunctionLinkage(*main_function)) {
2082 if (log)
2083 log->Printf("Couldn't fix the linkage for the function");
2084
2085 return false;
2086 }
2087 }
2088
2089 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
2090
2091 m_reloc_placeholder = new llvm::GlobalVariable(
2092 (*m_module), int8_ty, false /* IsConstant */,
2093 GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty),
2094 "reloc_placeholder", NULL /* InsertBefore */,
2095 GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */);
2096
2097 ////////////////////////////////////////////////////////////
2098 // Replace $__lldb_expr_result with a persistent variable
2099 //
2100
2101 if (main_function) {
2102 if (!CreateResultVariable(*main_function)) {
2103 if (log)
2104 log->Printf("CreateResultVariable() failed");
2105
2106 // CreateResultVariable() reports its own errors, so we don't do so here
2107
2108 return false;
2109 }
2110 }
2111
2112 if (log && log->GetVerbose()) {
2113 std::string s;
2114 raw_string_ostream oss(s);
2115
2116 m_module->print(oss, NULL);
2117
2118 oss.flush();
2119
2120 log->Printf("Module after creating the result variable: \n\"%s\"",
2121 s.c_str());
2122 }
2123
2124 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2125 ++fi) {
2126 llvm::Function *function = &*fi;
2127
2128 if (function->begin() == function->end())
2129 continue;
2130
2131 Function::iterator bbi;
2132
2133 for (bbi = function->begin(); bbi != function->end(); ++bbi) {
2134 if (!RemoveGuards(*bbi)) {
2135 if (log)
2136 log->Printf("RemoveGuards() failed");
2137
2138 // RemoveGuards() reports its own errors, so we don't do so here
2139
2140 return false;
2141 }
2142
2143 if (!RewritePersistentAllocs(*bbi)) {
2144 if (log)
2145 log->Printf("RewritePersistentAllocs() failed");
2146
2147 // RewritePersistentAllocs() reports its own errors, so we don't do so
2148 // here
2149
2150 return false;
2151 }
2152
2153 if (!RemoveCXAAtExit(*bbi)) {
2154 if (log)
2155 log->Printf("RemoveCXAAtExit() failed");
2156
2157 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2158
2159 return false;
2160 }
2161 }
2162 }
2163
2164 ///////////////////////////////////////////////////////////////////////////////
2165 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2166 //
2167
2168 if (!RewriteObjCConstStrings()) {
2169 if (log)
2170 log->Printf("RewriteObjCConstStrings() failed");
2171
2172 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2173
2174 return false;
2175 }
2176
2177 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2178 ++fi) {
2179 llvm::Function *function = &*fi;
2180
2181 for (llvm::Function::iterator bbi = function->begin(),
2182 bbe = function->end();
2183 bbi != bbe; ++bbi) {
2184 if (!RewriteObjCSelectors(*bbi)) {
2185 if (log)
2186 log->Printf("RewriteObjCSelectors() failed");
2187
Adrian Prantl05097242018-04-30 16:49:04 +00002188 // RewriteObjCSelectors() reports its own errors, so we don't do so
2189 // here
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190
2191 return false;
2192 }
Sean Callananac900582016-09-29 00:45:33 +00002193
2194 if (!RewriteObjCClassReferences(*bbi)) {
2195 if (log)
2196 log->Printf("RewriteObjCClassReferences() failed");
2197
2198 // RewriteObjCClasses() reports its own errors, so we don't do so here
2199
2200 return false;
2201 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 }
2203 }
2204
2205 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2206 ++fi) {
2207 llvm::Function *function = &*fi;
2208
2209 for (llvm::Function::iterator bbi = function->begin(),
2210 bbe = function->end();
2211 bbi != bbe; ++bbi) {
2212 if (!ResolveCalls(*bbi)) {
2213 if (log)
2214 log->Printf("ResolveCalls() failed");
2215
2216 // ResolveCalls() reports its own errors, so we don't do so here
2217
2218 return false;
2219 }
2220 }
2221 }
2222
2223 ////////////////////////////////////////////////////////////////////////
2224 // Run function-level passes that only make sense on the main function
2225 //
2226
2227 if (main_function) {
2228 if (!ResolveExternals(*main_function)) {
2229 if (log)
2230 log->Printf("ResolveExternals() failed");
2231
2232 // ResolveExternals() reports its own errors, so we don't do so here
2233
2234 return false;
2235 }
2236
2237 if (!ReplaceVariables(*main_function)) {
2238 if (log)
2239 log->Printf("ReplaceVariables() failed");
2240
2241 // ReplaceVariables() reports its own errors, so we don't do so here
2242
2243 return false;
2244 }
2245 }
2246
2247 if (log && log->GetVerbose()) {
2248 std::string s;
2249 raw_string_ostream oss(s);
2250
2251 m_module->print(oss, NULL);
2252
2253 oss.flush();
2254
2255 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2256 }
2257
2258 return true;
2259}
2260
2261void IRForTarget::assignPassManager(PMStack &pass_mgr_stack,
2262 PassManagerType pass_mgr_type) {}
2263
2264PassManagerType IRForTarget::getPotentialPassManagerType() const {
2265 return PMT_ModulePassManager;
Sean Callanan2ab712f22010-07-03 01:35:46 +00002266}