blob: b5e5c561f755ed9b27f45691c3a74000af0c6be2 [file] [log] [blame]
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001//===-- 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 "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
Sean Callanan2a8c3382011-04-14 02:01:31 +000013#include "llvm/Constants.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000014#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000015#include "llvm/Instructions.h"
Sean Callanan3cb1fd82010-09-28 23:55:00 +000016#include "llvm/Intrinsics.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000017#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000018#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000019#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000020
21#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000022
Greg Clayton8de27c72010-10-15 22:48:33 +000023#include "lldb/Core/ConstString.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000024#include "lldb/Core/dwarf.h"
25#include "lldb/Core/Log.h"
26#include "lldb/Core/Scalar.h"
27#include "lldb/Core/StreamString.h"
28#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callananc0492742011-05-23 21:40:23 +000029#include "lldb/Host/Endian.h"
Sean Callanan696cf5f2011-05-07 01:06:41 +000030#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000031
32#include <map>
33
34using namespace llvm;
35
Sean Callanan3351dac2010-08-18 18:50:51 +000036static char ID;
37
Sean Callananc0492742011-05-23 21:40:23 +000038IRForTarget::StaticDataAllocator::StaticDataAllocator()
39{
40}
41
42IRForTarget::StaticDataAllocator::~StaticDataAllocator()
43{
44}
45
Greg Clayton3c7feb42010-11-19 01:05:25 +000046IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
47 bool resolve_vars,
Sean Callanan696cf5f2011-05-07 01:06:41 +000048 lldb::ClangExpressionVariableSP &const_result,
Sean Callananc0492742011-05-23 21:40:23 +000049 StaticDataAllocator *data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +000050 lldb_private::Stream *error_stream,
Greg Clayton3c7feb42010-11-19 01:05:25 +000051 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000052 ModulePass(ID),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000053 m_resolve_vars(resolve_vars),
54 m_func_name(func_name),
Sean Callananc0492742011-05-23 21:40:23 +000055 m_module(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000056 m_decl_map(decl_map),
57 m_data_allocator(data_allocator),
Sean Callanan6ba533e2010-11-17 23:00:36 +000058 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000059 m_sel_registerName(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000060 m_const_result(const_result),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000061 m_error_stream(error_stream),
Sean Callanan6a925532011-01-13 08:53:35 +000062 m_has_side_effects(false),
Sean Callanan696cf5f2011-05-07 01:06:41 +000063 m_result_store(NULL),
64 m_result_is_pointer(false),
Sean Callananc0492742011-05-23 21:40:23 +000065 m_reloc_placeholder(NULL)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000066{
67}
68
Sean Callanan771131d2010-09-30 21:18:25 +000069/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000070
71static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000072PrintValue(const Value *value, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000073{
74 std::string s;
75 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000076 value->print(rso);
Sean Callanana48fe162010-08-11 03:57:18 +000077 rso.flush();
78 if (truncate)
79 s.resize(s.length() - 1);
80 return s;
81}
82
Sean Callanan771131d2010-09-30 21:18:25 +000083static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000084PrintType(const Type *type, bool truncate = false)
Sean Callanan771131d2010-09-30 21:18:25 +000085{
86 std::string s;
87 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000088 type->print(rso);
Sean Callanan771131d2010-09-30 21:18:25 +000089 rso.flush();
90 if (truncate)
91 s.resize(s.length() - 1);
92 return s;
93}
94
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000095IRForTarget::~IRForTarget()
96{
97}
98
Sean Callananc0492742011-05-23 21:40:23 +000099bool
100IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
101{
102 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
103
104 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
105
106 std::string name = llvm_function.getNameStr();
107
108 return true;
109}
110
Sean Callanan82b74c82010-08-12 01:56:52 +0000111bool
Sean Callananc0492742011-05-23 21:40:23 +0000112IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000113{
114 llvm::Function::iterator bbi;
115 BasicBlock::iterator ii;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000116
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000117 for (bbi = llvm_function.begin();
118 bbi != llvm_function.end();
119 ++bbi)
120 {
121 BasicBlock &basic_block = *bbi;
122
123 for (ii = basic_block.begin();
124 ii != basic_block.end();
125 ++ii)
126 {
127 switch (ii->getOpcode())
128 {
129 default:
130 return true;
131 case Instruction::Store:
132 {
133 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
134
135 Value *store_ptr = store_inst->getPointerOperand();
136
Sean Callanan696cf5f2011-05-07 01:06:41 +0000137 std::string ptr_name;
138
139 if (store_ptr->hasName())
140 ptr_name = store_ptr->getNameStr();
141
142 if (isa <AllocaInst> (store_ptr))
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000143 break;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000144
145 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
146 {
147 if (ptr_name.find("GV") == std::string::npos)
148 m_result_store = store_inst;
149 }
150 else
151 {
152 return true;
153 }
154
155 break;
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000156 }
157 case Instruction::Load:
158 case Instruction::Alloca:
159 case Instruction::GetElementPtr:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000160 case Instruction::BitCast:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000161 case Instruction::Ret:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000162 case Instruction::ICmp:
163 case Instruction::Br:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000164 break;
165 }
166 }
167 }
168
169 return false;
170}
171
Sean Callanan696cf5f2011-05-07 01:06:41 +0000172clang::NamedDecl *
Sean Callananc0492742011-05-23 21:40:23 +0000173IRForTarget::DeclForGlobal (GlobalValue *global_val)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000174{
175 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
176
Sean Callananc0492742011-05-23 21:40:23 +0000177 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000178
179 if (!named_metadata)
180 return NULL;
181
182 unsigned num_nodes = named_metadata->getNumOperands();
183 unsigned node_index;
184
185 for (node_index = 0;
186 node_index < num_nodes;
187 ++node_index)
188 {
189 MDNode *metadata_node = named_metadata->getOperand(node_index);
190
191 if (!metadata_node)
192 return NULL;
193
194 if (metadata_node->getNumOperands() != 2)
195 continue;
196
197 if (metadata_node->getOperand(0) != global_val)
198 continue;
199
200 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
201
202 if (!constant_int)
203 return NULL;
204
205 uintptr_t ptr = constant_int->getZExtValue();
206
207 return reinterpret_cast<clang::NamedDecl *>(ptr);
208 }
209
210 return NULL;
211}
212
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000213void
214IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
215 const lldb_private::ConstString &name,
216 lldb_private::TypeFromParser type)
217{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000218 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
219 {
220 switch (init_expr->getOpcode())
221 {
222 default:
223 return;
224 case Instruction::IntToPtr:
225 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
226 return;
227 }
228 }
229 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
230 {
231 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
232 }
233}
234
235void
Sean Callananc0492742011-05-23 21:40:23 +0000236IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000237{
238 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
239
240 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000241 return;
242
Sean Callanan696cf5f2011-05-07 01:06:41 +0000243 LoadInst *original_load = NULL;
244
245 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
246 current_value != NULL;
247 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000248 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000249 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
250 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
251
252 if (cast_inst)
253 {
254 next_value = cast_inst->getOperand(0);
255 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000256 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000257 {
258 if (isa<LoadInst>(load_inst->getPointerOperand()))
259 {
260 next_value = load_inst->getPointerOperand();
261 }
262 else
263 {
264 original_load = load_inst;
265 break;
266 }
267 }
268 else
269 {
270 return;
271 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000272 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000273
274 Value *loaded_value = original_load->getPointerOperand();
275 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
276
277 if (!loaded_global)
278 return;
279
Sean Callananc0492742011-05-23 21:40:23 +0000280 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000281
282 if (!loaded_decl)
283 return;
284
285 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
286
287 if (!loaded_var)
288 return;
289
290 if (log)
291 {
292 lldb_private::StreamString type_desc_stream;
293 type.DumpTypeDescription(&type_desc_stream);
294
295 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
296 }
297
298 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000299}
300
301bool
Sean Callananc0492742011-05-23 21:40:23 +0000302IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000303{
Greg Claytone005f2c2010-11-06 01:53:30 +0000304 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000305
Sean Callanane8a59a82010-09-13 21:34:21 +0000306 if (!m_resolve_vars)
307 return true;
308
309 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000310
Sean Callananc0492742011-05-23 21:40:23 +0000311 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000312
Sean Callanan9b6898f2011-07-30 02:42:06 +0000313 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000314 const char *result_name = NULL;
315
316 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
317 vi != ve;
318 ++vi)
319 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000320 result_name_str = vi->first().str();
321 const char *value_name = result_name_str.c_str();
322
323 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
324 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000325 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000326 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000327 m_result_is_pointer = true;
328 break;
329 }
330
Sean Callanan9b6898f2011-07-30 02:42:06 +0000331 if (strstr(value_name, "$__lldb_expr_result") &&
332 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000333 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000334 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000335 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000336 break;
337 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000338 }
339
340 if (!result_name)
341 {
342 if (log)
343 log->PutCString("Couldn't find result variable");
344
345 return true;
346 }
347
Sean Callananc04743d2010-09-28 21:13:03 +0000348 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000349 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000350
Sean Callananc0492742011-05-23 21:40:23 +0000351 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000352
353 if (!result_value)
354 {
355 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000356 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000357
Sean Callanan97c924e2011-01-27 01:07:04 +0000358 if (m_error_stream)
359 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
360
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000361 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000362 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000363
Sean Callanan82b74c82010-08-12 01:56:52 +0000364 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000365 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000366
367 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
368
369 if (!result_global)
370 {
371 if (log)
372 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000373
374 if (m_error_stream)
375 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
376
Sean Callanan82b74c82010-08-12 01:56:52 +0000377 return false;
378 }
379
Sean Callananc0492742011-05-23 21:40:23 +0000380 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000381 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000382 {
383 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000384 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000385
Sean Callanan97c924e2011-01-27 01:07:04 +0000386 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000387 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000388
Sean Callanan82b74c82010-08-12 01:56:52 +0000389 return false;
390 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000391
Sean Callanan696cf5f2011-05-07 01:06:41 +0000392 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000393 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000394 std::string decl_desc_str;
395 raw_string_ostream decl_desc_stream(decl_desc_str);
396 result_decl->print(decl_desc_stream);
397 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000398
Sean Callanan696cf5f2011-05-07 01:06:41 +0000399 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000400 }
401
Sean Callanan696cf5f2011-05-07 01:06:41 +0000402 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
403 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000404 {
405 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000406 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000407
408 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000409 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000410
Sean Callanan82b74c82010-08-12 01:56:52 +0000411 return false;
412 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000413
Sean Callanan82b74c82010-08-12 01:56:52 +0000414 // Get the next available result name from m_decl_map and create the persistent
415 // variable for it
416
Sean Callanan6a925532011-01-13 08:53:35 +0000417 lldb_private::TypeFromParser result_decl_type;
418
Sean Callanan696cf5f2011-05-07 01:06:41 +0000419 // If the result is an Lvalue, it is emitted as a pointer; see
420 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000421 if (m_result_is_pointer)
422 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000423 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000424 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
425 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000426
427 if (!pointer_pointertype)
428 {
429 if (log)
430 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000431
432 if (m_error_stream)
433 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
434
Sean Callanan6a925532011-01-13 08:53:35 +0000435 return false;
436 }
437
438 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
439
440 result_decl_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
441 &result_decl->getASTContext());
442 }
443 else
444 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000445 result_decl_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000446 &result_decl->getASTContext());
447 }
448
Sean Callanan696cf5f2011-05-07 01:06:41 +0000449 if (log)
450 {
451 lldb_private::StreamString type_desc_stream;
452 result_decl_type.DumpTypeDescription(&type_desc_stream);
453
454 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
455 }
456
Sean Callanan6a925532011-01-13 08:53:35 +0000457 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000458
459 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000460 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000461
462 // Construct a new result global and set up its metadata
463
Sean Callananc0492742011-05-23 21:40:23 +0000464 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000465 result_global->getType()->getElementType(),
466 false, /* not constant */
467 GlobalValue::ExternalLinkage,
468 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000469 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000470
471 // It's too late in compilation to create a new VarDecl for this, but we don't
472 // need to. We point the metadata at the old VarDecl. This creates an odd
473 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000474 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000475 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
476 // fixed up.
477
Sean Callananc0492742011-05-23 21:40:23 +0000478 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000479 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000480 false);
481
482 llvm::Value* values[2];
483 values[0] = new_result_global;
484 values[1] = new_constant_int;
485
Sean Callanan0de254a2011-05-15 22:34:38 +0000486 ArrayRef<Value*> value_ref(values, 2);
487
Sean Callananc0492742011-05-23 21:40:23 +0000488 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
489 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000490 named_metadata->addOperand(persistent_global_md);
491
492 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000493 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000494 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000495 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000496
497 if (result_global->hasNUses(0))
498 {
499 // We need to synthesize a store for this variable, because otherwise
500 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000501
Greg Clayton8de27c72010-10-15 22:48:33 +0000502 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000503 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
504
505 if (!first_entry_instruction)
506 return false;
507
508 if (!result_global->hasInitializer())
509 {
510 if (log)
511 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000512
513 if (m_error_stream)
514 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
515
Sean Callanan2e2db532010-09-07 22:43:19 +0000516 return false;
517 }
518
519 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000520
521 // Here we write the initializer into a result variable assuming it
522 // can be computed statically.
523
524 if (!m_has_side_effects)
525 {
526 MaybeSetConstantResult (initializer,
Sean Callanan6a925532011-01-13 08:53:35 +0000527 m_result_name,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000528 result_decl_type);
529 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000530
Greg Clayton2c344ca2011-02-05 02:28:58 +0000531 StoreInst *synthesized_store = new StoreInst(initializer,
532 new_result_global,
533 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000534
535 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000536 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000537 }
538 else
539 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000540 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (result_decl_type.GetOpaqueQualType()))
541 {
Sean Callananc0492742011-05-23 21:40:23 +0000542 MaybeSetCastResult (result_decl_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000543 }
544
Sean Callanan2e2db532010-09-07 22:43:19 +0000545 result_global->replaceAllUsesWith(new_result_global);
546 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000547
548 if (!m_const_result)
549 m_decl_map->AddPersistentVariable(result_decl,
550 m_result_name,
551 result_decl_type,
552 true,
553 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000554
Sean Callanan82b74c82010-08-12 01:56:52 +0000555 result_global->eraseFromParent();
556
557 return true;
558}
559
Greg Clayton3c7feb42010-11-19 01:05:25 +0000560static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000561{
562 if (!depth)
563 return;
564
565 depth--;
566
Greg Clayton3c7feb42010-11-19 01:05:25 +0000567 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000568
Greg Clayton3c7feb42010-11-19 01:05:25 +0000569 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000570 ui != ue;
571 ++ui)
572 {
573 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
574 DebugUsers(log, *ui, depth);
575 }
576
577 log->Printf(" <End uses>");
578}
579
580bool
Sean Callananc0492742011-05-23 21:40:23 +0000581IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000582 llvm::GlobalVariable *cstr,
583 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000584{
585 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
586
Sean Callanan9b6898f2011-07-30 02:42:06 +0000587 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000588
Sean Callanan9b6898f2011-07-30 02:42:06 +0000589 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
590 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000591 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000592 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
593 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000594
595 if (!m_CFStringCreateWithBytes)
596 {
597 lldb::addr_t CFStringCreateWithBytes_addr;
598
599 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
600
601 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
602 {
603 if (log)
604 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
605
Sean Callanan97c924e2011-01-27 01:07:04 +0000606 if (m_error_stream)
607 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
608
Sean Callanan6ba533e2010-11-17 23:00:36 +0000609 return false;
610 }
611
612 if (log)
613 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
614
615 // Build the function type:
616 //
617 // CFStringRef CFStringCreateWithBytes (
618 // CFAllocatorRef alloc,
619 // const UInt8 *bytes,
620 // CFIndex numBytes,
621 // CFStringEncoding encoding,
622 // Boolean isExternalRepresentation
623 // );
624 //
625 // We make the following substitutions:
626 //
627 // CFStringRef -> i8*
628 // CFAllocatorRef -> i8*
629 // UInt8 * -> i8*
630 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
631 // CFStringEncoding -> i32
632 // Boolean -> i8
633
Sean Callanan9b6898f2011-07-30 02:42:06 +0000634 Type *arg_type_array[5];
635
636 arg_type_array[0] = i8_ptr_ty;
637 arg_type_array[1] = i8_ptr_ty;
638 arg_type_array[2] = intptr_ty;
639 arg_type_array[3] = i32_ty;
640 arg_type_array[4] = i8_ty;
641
642 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
643
Sean Callananc0492742011-05-23 21:40:23 +0000644 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000645
646 // Build the constant containing the pointer to the function
647 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
648 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
649 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
650 }
651
Sean Callanan58baaad2011-07-08 00:39:14 +0000652 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000653
654 if (cstr)
655 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000656
Sean Callanan6ba533e2010-11-17 23:00:36 +0000657 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000658 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
659 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000660 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
661 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
662
Sean Callanan9b6898f2011-07-30 02:42:06 +0000663 Value *argument_array[5];
664
665 argument_array[0] = alloc_arg;
666 argument_array[1] = bytes_arg;
667 argument_array[2] = numBytes_arg;
668 argument_array[3] = encoding_arg;
669 argument_array[4] = isExternal_arg;
670
671 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000672
673 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000674 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000675 "CFStringCreateWithBytes",
676 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000677
Greg Clayton3c7feb42010-11-19 01:05:25 +0000678 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000679 {
680 if (log)
681 log->PutCString("Couldn't replace the NSString with the result of the call");
682
Sean Callanan97c924e2011-01-27 01:07:04 +0000683 if (m_error_stream)
684 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
685
Sean Callanan6ba533e2010-11-17 23:00:36 +0000686 return false;
687 }
688
Greg Clayton3c7feb42010-11-19 01:05:25 +0000689 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000690
691 return true;
692}
693
694bool
Sean Callananc0492742011-05-23 21:40:23 +0000695IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000696{
697 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
698
Sean Callananc0492742011-05-23 21:40:23 +0000699 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000700
Greg Clayton3c7feb42010-11-19 01:05:25 +0000701 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000702 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
703
704 if (!FirstEntryInstruction)
705 {
706 if (log)
707 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
708
Sean Callanan97c924e2011-01-27 01:07:04 +0000709 if (m_error_stream)
710 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
711
Sean Callanan6ba533e2010-11-17 23:00:36 +0000712 return false;
713 }
714
715 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
716 vi != ve;
717 ++vi)
718 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000719 std::string value_name = vi->first().str();
720 const char *value_name_cstr = value_name.c_str();
721
722 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000723 {
724 Value *nsstring_value = vi->second;
725
726 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
727
728 if (!nsstring_global)
729 {
730 if (log)
731 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000732
733 if (m_error_stream)
734 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
735
Sean Callanan6ba533e2010-11-17 23:00:36 +0000736 return false;
737 }
738
739 if (!nsstring_global->hasInitializer())
740 {
741 if (log)
742 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000743
744 if (m_error_stream)
745 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
746
Sean Callanan6ba533e2010-11-17 23:00:36 +0000747 return false;
748 }
749
750 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
751
752 if (!nsstring_struct)
753 {
754 if (log)
755 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000756
757 if (m_error_stream)
758 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
759
Sean Callanan6ba533e2010-11-17 23:00:36 +0000760 return false;
761 }
762
763 // We expect the following structure:
764 //
765 // struct {
766 // int *isa;
767 // int flags;
768 // char *str;
769 // long length;
770 // };
771
772 if (nsstring_struct->getNumOperands() != 4)
773 {
774 if (log)
775 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
Sean Callanan97c924e2011-01-27 01:07:04 +0000776
777 if (m_error_stream)
778 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
779
Sean Callanan6ba533e2010-11-17 23:00:36 +0000780 return false;
781 }
782
783 Constant *nsstring_member = nsstring_struct->getOperand(2);
784
785 if (!nsstring_member)
786 {
787 if (log)
788 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000789
790 if (m_error_stream)
791 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
792
Sean Callanan6ba533e2010-11-17 23:00:36 +0000793 return false;
794 }
795
796 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
797
798 if (!nsstring_expr)
799 {
800 if (log)
801 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +0000802
803 if (m_error_stream)
804 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
805
Sean Callanan6ba533e2010-11-17 23:00:36 +0000806 return false;
807 }
808
809 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
810 {
811 if (log)
812 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
Sean Callanan97c924e2011-01-27 01:07:04 +0000813
814 if (m_error_stream)
815 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
816
Sean Callanan6ba533e2010-11-17 23:00:36 +0000817 return false;
818 }
819
820 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
821
822 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
823
824 if (!cstr_global)
825 {
826 if (log)
827 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000828
829 if (m_error_stream)
830 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan65e2aee2010-11-20 02:06:01 +0000831
Sean Callanan6ba533e2010-11-17 23:00:36 +0000832 return false;
833 }
834
835 if (!cstr_global->hasInitializer())
836 {
837 if (log)
838 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000839
840 if (m_error_stream)
841 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
842
Sean Callanan6ba533e2010-11-17 23:00:36 +0000843 return false;
844 }
Sean Callanan0ece5262011-02-10 22:17:53 +0000845
846 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +0000847 if (!cstr_array)
848 {
849 if (log)
850 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +0000851
852 if (m_error_stream)
853 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
854
Sean Callanan6ba533e2010-11-17 23:00:36 +0000855 return false;
856 }
857
858 if (!cstr_array->isCString())
859 {
860 if (log)
861 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +0000862
863 if (m_error_stream)
864 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
865
Sean Callanan6ba533e2010-11-17 23:00:36 +0000866 return false;
867 }
Sean Callanan0ece5262011-02-10 22:17:53 +0000868 */
869
870 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000871
872 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +0000873 {
874 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000875 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +0000876 else
Sean Callanan9b6898f2011-07-30 02:42:06 +0000877 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +0000878 }
879
880 if (!cstr_array)
881 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +0000882
Sean Callananc0492742011-05-23 21:40:23 +0000883 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +0000884 {
Sean Callanan6ba533e2010-11-17 23:00:36 +0000885 if (log)
886 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +0000887
888 // We don't print an error message here because RewriteObjCConstString has done so for us.
889
Sean Callanan6ba533e2010-11-17 23:00:36 +0000890 return false;
891 }
Sean Callanan6ba533e2010-11-17 23:00:36 +0000892 }
893 }
894
895 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
896 vi != ve;
897 ++vi)
898 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000899 std::string value_name = vi->first().str();
900 const char *value_name_cstr = value_name.c_str();
901
902 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000903 {
904 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
905
906 if (!gv)
907 {
908 if (log)
909 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000910
911 if (m_error_stream)
912 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
913
Sean Callanan6ba533e2010-11-17 23:00:36 +0000914 return false;
915 }
916
917 gv->eraseFromParent();
918
919 break;
920 }
921 }
922
923 return true;
924}
925
Greg Clayton3c7feb42010-11-19 01:05:25 +0000926static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +0000927{
Greg Clayton3c7feb42010-11-19 01:05:25 +0000928 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +0000929
Greg Clayton3c7feb42010-11-19 01:05:25 +0000930 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +0000931 return false;
932
933 return true;
934}
935
Sean Callanan97c924e2011-01-27 01:07:04 +0000936// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +0000937bool
Sean Callananc0492742011-05-23 21:40:23 +0000938IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +0000939{
Greg Claytone005f2c2010-11-06 01:53:30 +0000940 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000941
942 LoadInst *load = dyn_cast<LoadInst>(selector_load);
943
944 if (!load)
945 return false;
946
947 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
948 //
949 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
950 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
951 //
952 // where %obj is the object pointer and %tmp is the selector.
953 //
Greg Clayton3c7feb42010-11-19 01:05:25 +0000954 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
955 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +0000956
957 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
958
959 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
960
961 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
962 return false;
963
964 Constant *osr_initializer = _objc_selector_references_->getInitializer();
965
966 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
967
968 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
969 return false;
970
971 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
972
973 if (!osr_initializer_base)
974 return false;
975
976 // Find the string's initializer (a ConstantArray) and get the string from it
977
978 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
979
980 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
981 return false;
982
983 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
984
985 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
986
987 if (!omvn_initializer_array->isString())
988 return false;
989
990 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
991
992 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000993 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000994
995 // Construct a call to sel_registerName
996
997 if (!m_sel_registerName)
998 {
Greg Claytonb5037af2010-11-15 01:47:11 +0000999 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001000
Greg Clayton8de27c72010-10-15 22:48:33 +00001001 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001002 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001003 return false;
1004
Sean Callananc2c6f772010-10-26 00:31:56 +00001005 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001006 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001007
Sean Callananf5857a02010-07-31 01:32:05 +00001008 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1009
1010 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001011 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001012 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001013 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001014
Sean Callanan9b6898f2011-07-30 02:42:06 +00001015 Type *type_array[1];
1016
1017 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1018
1019 ArrayRef<Type *> srN_arg_types(type_array, 1);
1020
Sean Callananf5857a02010-07-31 01:32:05 +00001021 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1022
1023 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001024 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1025 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001026 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001027 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001028 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1029 }
1030
Sean Callanan9b6898f2011-07-30 02:42:06 +00001031 Value *argument_array[1];
1032
Sean Callananc0492742011-05-23 21:40:23 +00001033 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001034
Sean Callanan9b6898f2011-07-30 02:42:06 +00001035 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001036
Sean Callanan9b6898f2011-07-30 02:42:06 +00001037 ArrayRef<Value *> srN_arguments(argument_array, 1);
1038
Sean Callananf5857a02010-07-31 01:32:05 +00001039 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001040 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001041 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001042 selector_load);
1043
1044 // Replace the load with the call in all users
1045
1046 selector_load->replaceAllUsesWith(srN_call);
1047
1048 selector_load->eraseFromParent();
1049
1050 return true;
1051}
1052
1053bool
Sean Callananc0492742011-05-23 21:40:23 +00001054IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001055{
Greg Claytone005f2c2010-11-06 01:53:30 +00001056 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001057
1058 BasicBlock::iterator ii;
1059
1060 typedef SmallVector <Instruction*, 2> InstrList;
1061 typedef InstrList::iterator InstrIterator;
1062
1063 InstrList selector_loads;
1064
Greg Clayton3c7feb42010-11-19 01:05:25 +00001065 for (ii = basic_block.begin();
1066 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001067 ++ii)
1068 {
1069 Instruction &inst = *ii;
1070
1071 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001072 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001073 selector_loads.push_back(&inst);
1074 }
1075
1076 InstrIterator iter;
1077
1078 for (iter = selector_loads.begin();
1079 iter != selector_loads.end();
1080 ++iter)
1081 {
Sean Callananc0492742011-05-23 21:40:23 +00001082 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001083 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001084 if (m_error_stream)
1085 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1086
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001087 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001088 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001089
Sean Callananf5857a02010-07-31 01:32:05 +00001090 return false;
1091 }
1092 }
1093
1094 return true;
1095}
1096
Sean Callanan97c924e2011-01-27 01:07:04 +00001097// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001098bool
Sean Callananc0492742011-05-23 21:40:23 +00001099IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001100{
Sean Callanan97678d12011-01-13 21:23:32 +00001101 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1102
Sean Callanana48fe162010-08-11 03:57:18 +00001103 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1104
1105 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1106
1107 if (!alloc_md || !alloc_md->getNumOperands())
1108 return false;
1109
1110 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1111
1112 if (!constant_int)
1113 return false;
1114
1115 // We attempt to register this as a new persistent variable with the DeclMap.
1116
1117 uintptr_t ptr = constant_int->getZExtValue();
1118
Sean Callanan82b74c82010-08-12 01:56:52 +00001119 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001120
Sean Callanan82b74c82010-08-12 01:56:52 +00001121 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1122 &decl->getASTContext());
1123
Greg Clayton8de27c72010-10-15 22:48:33 +00001124 StringRef decl_name (decl->getName());
1125 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001126 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001127 return false;
1128
Sean Callananc0492742011-05-23 21:40:23 +00001129 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001130 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001131 false, /* not constant */
1132 GlobalValue::ExternalLinkage,
1133 NULL, /* no initializer */
1134 alloc->getName().str().c_str());
1135
1136 // What we're going to do here is make believe this was a regular old external
1137 // variable. That means we need to make the metadata valid.
1138
Sean Callananc0492742011-05-23 21:40:23 +00001139 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001140
1141 llvm::Value* values[2];
1142 values[0] = persistent_global;
1143 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001144
1145 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001146
Sean Callananc0492742011-05-23 21:40:23 +00001147 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001148 named_metadata->addOperand(persistent_global_md);
1149
Sean Callanan97678d12011-01-13 21:23:32 +00001150 // Now, since the variable is a pointer variable, we will drop in a load of that
1151 // pointer variable.
1152
1153 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1154
1155 if (log)
1156 log->Printf("Replacing \"%s\" with \"%s\"",
1157 PrintValue(alloc).c_str(),
1158 PrintValue(persistent_load).c_str());
1159
1160 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001161 alloc->eraseFromParent();
1162
1163 return true;
1164}
1165
1166bool
Sean Callananc0492742011-05-23 21:40:23 +00001167IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001168{
Sean Callanane8a59a82010-09-13 21:34:21 +00001169 if (!m_resolve_vars)
1170 return true;
1171
Greg Claytone005f2c2010-11-06 01:53:30 +00001172 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001173
1174 BasicBlock::iterator ii;
1175
1176 typedef SmallVector <Instruction*, 2> InstrList;
1177 typedef InstrList::iterator InstrIterator;
1178
1179 InstrList pvar_allocs;
1180
Greg Clayton3c7feb42010-11-19 01:05:25 +00001181 for (ii = basic_block.begin();
1182 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001183 ++ii)
1184 {
1185 Instruction &inst = *ii;
1186
1187 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001188 {
1189 llvm::StringRef alloc_name = alloc->getName();
1190
1191 if (alloc_name.startswith("$") &&
1192 !alloc_name.startswith("$__lldb"))
1193 {
1194 if (alloc_name.find_first_of("0123456789") == 1)
1195 {
1196 if (log)
1197 log->Printf("Rejecting a numeric persistent variable.");
1198
Sean Callanan97c924e2011-01-27 01:07:04 +00001199 if (m_error_stream)
1200 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1201
Sean Callanan237e4742011-01-21 22:30:25 +00001202 return false;
1203 }
1204
Sean Callanana48fe162010-08-11 03:57:18 +00001205 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001206 }
1207 }
Sean Callanana48fe162010-08-11 03:57:18 +00001208 }
1209
1210 InstrIterator iter;
1211
1212 for (iter = pvar_allocs.begin();
1213 iter != pvar_allocs.end();
1214 ++iter)
1215 {
Sean Callananc0492742011-05-23 21:40:23 +00001216 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001217 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001218 if (m_error_stream)
1219 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1220
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001221 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001222 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001223
Sean Callanana48fe162010-08-11 03:57:18 +00001224 return false;
1225 }
1226 }
1227
1228 return true;
1229}
1230
Sean Callanan97c924e2011-01-27 01:07:04 +00001231// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001232bool
Sean Callananc0492742011-05-23 21:40:23 +00001233IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001234{
Greg Claytone005f2c2010-11-06 01:53:30 +00001235 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001236
1237 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001238 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001239
Greg Clayton8de27c72010-10-15 22:48:33 +00001240 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001241 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001242 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001243 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001244 default:
1245 break;
1246 case Instruction::GetElementPtr:
1247 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001248 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001249 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001250 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001251 }
1252 }
Sean Callananf921cf52010-12-03 19:51:05 +00001253 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001254 {
Sean Callananc0492742011-05-23 21:40:23 +00001255 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001256
Sean Callananf5857a02010-07-31 01:32:05 +00001257 if (!named_decl)
1258 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001259 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001260 return true;
1261
Sean Callanan7cd46742010-12-06 00:56:39 +00001262 if (!global_variable->hasExternalLinkage())
1263 return true;
1264
Sean Callananf5857a02010-07-31 01:32:05 +00001265 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001266 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001267
Sean Callananf5857a02010-07-31 01:32:05 +00001268 return false;
1269 }
1270
Greg Clayton8de27c72010-10-15 22:48:33 +00001271 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001272
Sean Callanan771131d2010-09-30 21:18:25 +00001273 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001274 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001275
1276 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001277 {
Sean Callanan771131d2010-09-30 21:18:25 +00001278 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001279 ast_context = &value_decl->getASTContext();
1280 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001281 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001282 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001283 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001284 }
Sean Callanan771131d2010-09-30 21:18:25 +00001285
Sean Callanan6a925532011-01-13 08:53:35 +00001286 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001287 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001288
Sean Callanan97678d12011-01-13 21:23:32 +00001289 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001290 {
1291 // The $__lldb_expr_result name indicates the the return value has allocated as
1292 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1293 // accesses to this static variable need to be redirected to the result of dereferencing
1294 // a pointer that is passed in as one of the arguments.
1295 //
1296 // Consequently, when reporting the size of the type, we report a pointer type pointing
1297 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001298 //
1299 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001300
Sean Callanan6a925532011-01-13 08:53:35 +00001301 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1302 value_type = PointerType::get(global_variable->getType(), 0);
1303 }
1304 else
1305 {
1306 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1307 value_type = global_variable->getType();
1308 }
Sean Callanan771131d2010-09-30 21:18:25 +00001309
1310 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1311 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001312
Sean Callanan771131d2010-09-30 21:18:25 +00001313 if (log)
Sean Callanan97678d12011-01-13 21:23:32 +00001314 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %d, align %d]",
Sean Callanan771131d2010-09-30 21:18:25 +00001315 name.c_str(),
1316 qual_type.getAsString().c_str(),
1317 PrintType(value_type).c_str(),
1318 value_size,
1319 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001320
Sean Callanan8bce6652010-07-13 21:41:46 +00001321
Sean Callanan8c127202010-08-23 23:09:38 +00001322 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001323 lldb_private::ConstString (name.c_str()),
1324 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001325 value_size,
1326 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001327 {
1328 if (!global_variable->hasExternalLinkage())
1329 return true;
1330 else
1331 return false;
1332 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001333 }
Sean Callananf3143b72010-12-03 03:02:31 +00001334 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001335 {
1336 if (log)
1337 log->Printf("Function pointers aren't handled right now");
1338
1339 return false;
1340 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001341
1342 return true;
1343}
1344
Sean Callanan97c924e2011-01-27 01:07:04 +00001345// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001346bool
Sean Callananc0492742011-05-23 21:40:23 +00001347IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001348{
Sean Callananc7674af2011-01-17 23:42:46 +00001349 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1350
1351 lldb_private::ConstString name(symbol->getName().str().c_str());
1352
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001353 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001354
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001355 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001356 {
1357 if (log)
1358 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1359
1360 return false;
1361 }
1362
1363 if (log)
1364 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1365
Sean Callanan9b6898f2011-07-30 02:42:06 +00001366 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001367
Sean Callanan9b6898f2011-07-30 02:42:06 +00001368 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1369 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001370
1371 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1372
1373 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1374
1375 if (log)
1376 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1377
1378 symbol->replaceAllUsesWith(symbol_addr_ptr);
1379
1380 return true;
1381}
1382
1383bool
Sean Callananc0492742011-05-23 21:40:23 +00001384IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001385{
Sean Callanan48443652010-12-02 19:47:57 +00001386 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1387
1388 if (log)
1389 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001390
Sean Callanan6ba533e2010-11-17 23:00:36 +00001391 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001392 op_index < num_ops;
1393 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001394 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001395 {
1396 if (m_error_stream)
1397 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1398
Sean Callanandc27aba2010-10-05 22:26:43 +00001399 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001400 }
1401
Sean Callanandc27aba2010-10-05 22:26:43 +00001402 return true;
1403}
1404
1405bool
Sean Callananc0492742011-05-23 21:40:23 +00001406IRForTarget::MaybeHandleCall (CallInst *llvm_call_inst)
Sean Callananba992c52010-07-27 02:07:53 +00001407{
Greg Claytone005f2c2010-11-06 01:53:30 +00001408 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananba992c52010-07-27 02:07:53 +00001409
Greg Clayton8de27c72010-10-15 22:48:33 +00001410 Function *fun = llvm_call_inst->getCalledFunction();
Sean Callanan9a877432011-08-01 17:41:38 +00001411
1412 // If the call is to something other than a plain llvm::Function, resolve which
1413 // Function is meant or give up.
Sean Callananba992c52010-07-27 02:07:53 +00001414
1415 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +00001416 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001417 Value *val = llvm_call_inst->getCalledValue();
Sean Callanan65af7342010-09-08 20:04:08 +00001418
1419 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
Sean Callanand5b3c352011-01-27 04:42:51 +00001420 LoadInst *load_inst = dyn_cast<LoadInst>(val);
Sean Callanan65af7342010-09-08 20:04:08 +00001421
1422 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
1423 {
1424 fun = dyn_cast<Function>(const_expr->getOperand(0));
1425
1426 if (!fun)
Sean Callanan97c924e2011-01-27 01:07:04 +00001427 {
1428 if (m_error_stream)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001429 m_error_stream->Printf("Internal error [IRForTaget]: Called entity is a cast of something not a function\n");
Sean Callanan97c924e2011-01-27 01:07:04 +00001430
Sean Callanan48443652010-12-02 19:47:57 +00001431 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001432 }
Sean Callanan65af7342010-09-08 20:04:08 +00001433 }
Sean Callananc4217a62010-12-06 23:53:20 +00001434 else if (const_expr && const_expr->getOpcode() == Instruction::IntToPtr)
1435 {
1436 return true; // already resolved
1437 }
Sean Callanand5b3c352011-01-27 04:42:51 +00001438 else if (load_inst)
1439 {
1440 return true; // virtual method call
1441 }
Sean Callanan65af7342010-09-08 20:04:08 +00001442 else
1443 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001444 if (m_error_stream)
1445 m_error_stream->Printf("Internal error [IRForTarget]: Called entity is not a function\n");
1446
Sean Callanan48443652010-12-02 19:47:57 +00001447 return false;
Sean Callanan65af7342010-09-08 20:04:08 +00001448 }
1449 }
Sean Callananba992c52010-07-27 02:07:53 +00001450
Sean Callanan9a877432011-08-01 17:41:38 +00001451 // Determine the name of the called function, which is needed to find the address.
1452 // Intrinsics are special-cased.
1453
Greg Clayton8de27c72010-10-15 22:48:33 +00001454 lldb_private::ConstString str;
Sean Callananc04743d2010-09-28 21:13:03 +00001455
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001456 if (fun->isIntrinsic())
Sean Callananc04743d2010-09-28 21:13:03 +00001457 {
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001458 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
Sean Callananc04743d2010-09-28 21:13:03 +00001459
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001460 switch (intrinsic_id)
1461 {
1462 default:
1463 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001464 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001465
1466 if (m_error_stream)
1467 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
1468
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001469 return false;
1470 case Intrinsic::memcpy:
Greg Clayton8de27c72010-10-15 22:48:33 +00001471 {
1472 static lldb_private::ConstString g_memcpy_str ("memcpy");
1473 str = g_memcpy_str;
1474 }
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001475 break;
1476 }
Sean Callananc04743d2010-09-28 21:13:03 +00001477
Greg Clayton8de27c72010-10-15 22:48:33 +00001478 if (log && str)
Greg Claytonb5037af2010-11-15 01:47:11 +00001479 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString());
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001480 }
1481 else
1482 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001483 str.SetCStringWithLength (fun->getName().data(), fun->getName().size());
Sean Callananc04743d2010-09-28 21:13:03 +00001484 }
1485
Sean Callanan9a877432011-08-01 17:41:38 +00001486 // Find the address of the function, and the type if possible.
1487
Sean Callananc0492742011-05-23 21:40:23 +00001488 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Greg Claytonb5037af2010-11-15 01:47:11 +00001489 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS;
Sean Callananf5857a02010-07-31 01:32:05 +00001490 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +00001491
Sean Callananf5857a02010-07-31 01:32:05 +00001492 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +00001493 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001494 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001495 {
Sean Callanan92aa6662010-09-07 21:49:41 +00001496 fun_value_ptr = NULL;
1497
Greg Clayton8de27c72010-10-15 22:48:33 +00001498 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +00001499 {
1500 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001501 log->Printf("Function \"%s\" had no address", str.GetCString());
Sean Callanan92aa6662010-09-07 21:49:41 +00001502
Sean Callanan97c924e2011-01-27 01:07:04 +00001503 if (m_error_stream)
1504 m_error_stream->Printf("Error [IRForTarget]: Call to a function '%s' that is not present in the target\n", str.GetCString());
1505
Sean Callanan92aa6662010-09-07 21:49:41 +00001506 return false;
1507 }
Sean Callananf5857a02010-07-31 01:32:05 +00001508 }
1509 }
1510 else
1511 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001512 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001513 {
1514 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001515 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString());
Sean Callanan97c924e2011-01-27 01:07:04 +00001516
1517 if (m_error_stream)
1518 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", str.GetCString());
1519
1520 return false;
Sean Callananf5857a02010-07-31 01:32:05 +00001521 }
Sean Callananba992c52010-07-27 02:07:53 +00001522 }
1523
1524 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001525 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +00001526
Sean Callanan9a877432011-08-01 17:41:38 +00001527 // Construct the typed pointer to the function.
1528
Sean Callanan58baaad2011-07-08 00:39:14 +00001529 Value *fun_addr_ptr = NULL;
Sean Callananf5857a02010-07-31 01:32:05 +00001530
1531 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +00001532 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001533 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1534 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1535 FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +00001536 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
1537 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001538 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
1539
1540 if (fun_value_ptr)
1541 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001542 }
Sean Callananf5857a02010-07-31 01:32:05 +00001543
1544 if (fun_value_ptr)
1545 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001546
Greg Clayton8de27c72010-10-15 22:48:33 +00001547 llvm_call_inst->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +00001548
Sean Callananc0492742011-05-23 21:40:23 +00001549 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(m_module->getContext(), str.GetCString());
Sean Callanane8a59a82010-09-13 21:34:21 +00001550
1551 Value *values[1];
1552 values[0] = func_name;
Sean Callanan0de254a2011-05-15 22:34:38 +00001553 ArrayRef<Value*> value_ref(values, 1);
1554
Sean Callananc0492742011-05-23 21:40:23 +00001555 MDNode *func_metadata = MDNode::get(m_module->getContext(), value_ref);
Sean Callanane8a59a82010-09-13 21:34:21 +00001556
Greg Clayton8de27c72010-10-15 22:48:33 +00001557 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata);
Sean Callanane8a59a82010-09-13 21:34:21 +00001558
1559 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001560 log->Printf("Set metadata for %p [%d, \"%s\"]", llvm_call_inst, func_name->isString(), func_name->getAsString().c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +00001561
Sean Callananba992c52010-07-27 02:07:53 +00001562 return true;
1563}
1564
1565bool
Sean Callananc0492742011-05-23 21:40:23 +00001566IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001567{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001568 /////////////////////////////////////////////////////////////////////////
1569 // Prepare the current basic block for execution in the remote process
1570 //
1571
Sean Callanan02fbafa2010-07-27 21:39:39 +00001572 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001573
Greg Clayton3c7feb42010-11-19 01:05:25 +00001574 for (ii = basic_block.begin();
1575 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001576 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001577 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001578 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001579
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001580 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001581
Sean Callanan97c924e2011-01-27 01:07:04 +00001582 // MaybeHandleCall handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001583 if (call && !MaybeHandleCall(call))
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001584 return false;
Sean Callanan48443652010-12-02 19:47:57 +00001585
Sean Callanan97c924e2011-01-27 01:07:04 +00001586 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001587 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001588 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001589 }
1590
1591 return true;
1592}
1593
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001594bool
Sean Callananc0492742011-05-23 21:40:23 +00001595IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001596{
Sean Callananae71e302010-11-18 22:21:58 +00001597 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1598
Sean Callananc0492742011-05-23 21:40:23 +00001599 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001600 global != end;
1601 ++global)
1602 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001603 if (log)
1604 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1605 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001606 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001607
Sean Callananc7674af2011-01-17 23:42:46 +00001608 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1609 {
Sean Callananc0492742011-05-23 21:40:23 +00001610 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001611 {
1612 if (m_error_stream)
1613 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1614
Sean Callananc7674af2011-01-17 23:42:46 +00001615 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001616 }
Sean Callananc7674af2011-01-17 23:42:46 +00001617 }
Sean Callananc0492742011-05-23 21:40:23 +00001618 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001619 {
Sean Callananc0492742011-05-23 21:40:23 +00001620 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001621 {
1622 if (m_error_stream)
1623 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1624
Sean Callananc7674af2011-01-17 23:42:46 +00001625 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001626 }
Sean Callananc7674af2011-01-17 23:42:46 +00001627 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001628 }
1629
1630 return true;
1631}
1632
Sean Callananc0492742011-05-23 21:40:23 +00001633bool
1634IRForTarget::ReplaceStrings ()
1635{
1636 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1637
1638 if (!m_data_allocator)
1639 return true; // hope for the best; some clients may not want static allocation!
1640
1641 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1642
1643 OffsetsTy offsets;
1644
1645 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1646 gi != ge;
1647 ++gi)
1648 {
1649 GlobalVariable *gv = gi;
1650
1651 if (!gv->hasInitializer())
1652 continue;
1653
1654 Constant *gc = gv->getInitializer();
1655
1656 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1657
1658 if (!gc_array)
1659 continue;
1660
1661 if (!gc_array->isCString())
1662 continue;
1663
1664 if (log)
1665 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1666
1667 std::string str = gc_array->getAsString();
1668
1669 offsets[gv] = m_data_allocator->GetStream().GetSize();
1670
1671 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1672 }
1673
Sean Callanan9b6898f2011-07-30 02:42:06 +00001674 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001675
1676 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1677 oi != oe;
1678 ++oi)
1679 {
1680 GlobalVariable *gv = oi->first;
1681 size_t offset = oi->second;
1682
1683 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1684
1685 if (log)
1686 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1687
1688 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1689 ui != ue;
1690 ++ui)
1691 {
1692 if (log)
1693 log->Printf("Found use %s", PrintValue(*ui).c_str());
1694
1695 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1696 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1697
1698 if (const_expr)
1699 {
1700 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1701 {
1702 if (log)
1703 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1704
1705 return false;
1706 }
1707
1708 const_expr->replaceAllUsesWith(new_initializer);
1709 }
1710 else if (store_inst)
1711 {
1712 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1713
1714 store_inst->setOperand(0, bit_cast);
1715 }
1716 else
1717 {
1718 if (log)
1719 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1720
1721 return false;
1722 }
1723 }
1724
1725 gv->eraseFromParent();
1726 }
1727
1728 return true;
1729}
1730
1731bool
1732IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1733{
1734 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1735
1736 if (!m_data_allocator)
1737 return true;
1738
1739 typedef SmallVector <Value*, 2> ConstantList;
1740 typedef SmallVector <llvm::Instruction*, 2> UserList;
1741 typedef ConstantList::iterator ConstantIterator;
1742 typedef UserList::iterator UserIterator;
1743
1744 ConstantList static_constants;
1745 UserList static_users;
1746
1747 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1748 ii != ie;
1749 ++ii)
1750 {
1751 llvm::Instruction &inst = *ii;
1752
1753 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1754 oi != oe;
1755 ++oi)
1756 {
1757 Value *operand_val = oi->get();
1758
1759 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1760
1761 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1762 {
1763 static_constants.push_back(operand_val);
1764 static_users.push_back(ii);
1765 }
1766 }
1767 }
1768
1769 ConstantIterator constant_iter;
1770 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00001771
Sean Callananc0492742011-05-23 21:40:23 +00001772 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1773 constant_iter != static_constants.end();
1774 ++constant_iter, ++user_iter)
1775 {
1776 Value *operand_val = *constant_iter;
1777 llvm::Instruction *inst = *user_iter;
1778
1779 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1780
1781 if (operand_constant_fp)
1782 {
1783 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1784 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1785
1786 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1787 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1788
1789 if (log)
1790 {
1791 std::string s;
1792 raw_string_ostream ss(s);
1793 for (size_t index = 0;
1794 index < operand_data_size;
1795 ++index)
1796 {
1797 ss << (uint32_t)operand_raw_data[index];
1798 ss << " ";
1799 }
1800 ss.flush();
1801
1802 log->Printf("Found ConstantFP with size %d and raw data %s", operand_data_size, s.c_str());
1803 }
1804
1805 lldb_private::DataBufferHeap data(operand_data_size, 0);
1806
1807 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
1808 {
1809 uint8_t *data_bytes = data.GetBytes();
1810
1811 for (size_t index = 0;
1812 index < operand_data_size;
1813 ++index)
1814 {
1815 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1816 }
1817 }
1818 else
1819 {
1820 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
1821 }
1822
1823 uint64_t offset = m_data_allocator->GetStream().GetSize();
1824
1825 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
1826
Sean Callanan9b6898f2011-07-30 02:42:06 +00001827 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00001828
1829 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
1830
1831 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
1832
1833 operand_constant_fp->replaceAllUsesWith(fp_load);
1834 }
1835 }
1836
1837 return true;
1838}
1839
Sean Callanan02fbafa2010-07-27 21:39:39 +00001840static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001841{
Sean Callanan58baaad2011-07-08 00:39:14 +00001842 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00001843
Sean Callanan6ba533e2010-11-17 23:00:36 +00001844 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001845 return false;
1846
Sean Callanan58baaad2011-07-08 00:39:14 +00001847 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001848
1849 if ((CE = dyn_cast<ConstantExpr>(V)))
1850 {
1851 if (CE->getOpcode() != Instruction::BitCast)
1852 return false;
1853
Sean Callanan6ba533e2010-11-17 23:00:36 +00001854 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001855 }
1856
Sean Callanan6ba533e2010-11-17 23:00:36 +00001857 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001858
1859 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1860 return false;
1861
1862 return true;
1863}
1864
Sean Callananc0492742011-05-23 21:40:23 +00001865void
1866IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00001867{
Sean Callananc0492742011-05-23 21:40:23 +00001868 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00001869
1870 Value::use_iterator ui;
1871
1872 for (ui = guard_load->use_begin();
1873 ui != guard_load->use_end();
1874 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001875 {
Greg Clayton6e713402010-07-30 20:30:44 +00001876 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001877 {
1878 // do nothing for the moment
1879 }
1880 else
1881 {
1882 ui->replaceUsesOfWith(guard_load, zero);
1883 }
1884 }
Sean Callanan45839272010-07-24 01:37:44 +00001885
1886 guard_load->eraseFromParent();
1887}
1888
1889static void ExciseGuardStore(Instruction* guard_store)
1890{
1891 guard_store->eraseFromParent();
1892}
1893
1894bool
Sean Callananc0492742011-05-23 21:40:23 +00001895IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00001896{
1897 ///////////////////////////////////////////////////////
1898 // Eliminate any reference to guard variables found.
1899 //
1900
Sean Callanan02fbafa2010-07-27 21:39:39 +00001901 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001902
Sean Callanan02fbafa2010-07-27 21:39:39 +00001903 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001904 typedef InstrList::iterator InstrIterator;
1905
1906 InstrList guard_loads;
1907 InstrList guard_stores;
1908
Greg Clayton3c7feb42010-11-19 01:05:25 +00001909 for (ii = basic_block.begin();
1910 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00001911 ++ii)
1912 {
1913 Instruction &inst = *ii;
1914
1915 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1916 if (isGuardVariableRef(load->getPointerOperand()))
1917 guard_loads.push_back(&inst);
1918
1919 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1920 if (isGuardVariableRef(store->getPointerOperand()))
1921 guard_stores.push_back(&inst);
1922 }
1923
1924 InstrIterator iter;
1925
1926 for (iter = guard_loads.begin();
1927 iter != guard_loads.end();
1928 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00001929 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00001930
1931 for (iter = guard_stores.begin();
1932 iter != guard_stores.end();
1933 ++iter)
1934 ExciseGuardStore(*iter);
1935
1936 return true;
1937}
1938
Sean Callanan97c924e2011-01-27 01:07:04 +00001939// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001940bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001941IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00001942{
Greg Claytone005f2c2010-11-06 01:53:30 +00001943 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001944
1945 Value::use_iterator ui;
1946
Sean Callanana48fe162010-08-11 03:57:18 +00001947 SmallVector<User*, 16> users;
1948
1949 // We do this because the use list might change, invalidating our iterator.
1950 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00001951 for (ui = old_constant->use_begin();
1952 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001953 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001954 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001955
Johnny Chen2bc9eb32011-07-19 19:48:13 +00001956 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00001957 i < users.size();
1958 ++i)
1959 {
1960 User *user = users[i];
1961
Sean Callananbafd6852010-07-14 23:40:29 +00001962 if (Constant *constant = dyn_cast<Constant>(user))
1963 {
1964 // synthesize a new non-constant equivalent of the constant
1965
1966 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1967 {
1968 switch (constant_expr->getOpcode())
1969 {
1970 default:
1971 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001972 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001973 return false;
1974 case Instruction::BitCast:
1975 {
1976 // UnaryExpr
1977 // OperandList[0] is value
1978
1979 Value *s = constant_expr->getOperand(0);
1980
Greg Clayton3c7feb42010-11-19 01:05:25 +00001981 if (s == old_constant)
1982 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00001983
Sean Callananc0492742011-05-23 21:40:23 +00001984 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00001985
Greg Clayton3c7feb42010-11-19 01:05:25 +00001986 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00001987 }
1988 break;
1989 case Instruction::GetElementPtr:
1990 {
1991 // GetElementPtrConstantExpr
1992 // OperandList[0] is base
1993 // OperandList[1]... are indices
1994
1995 Value *ptr = constant_expr->getOperand(0);
1996
Greg Clayton3c7feb42010-11-19 01:05:25 +00001997 if (ptr == old_constant)
1998 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00001999
2000 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002001
2002 unsigned operand_index;
2003 unsigned num_operands = constant_expr->getNumOperands();
2004
2005 for (operand_index = 1;
2006 operand_index < num_operands;
2007 ++operand_index)
2008 {
2009 Value *operand = constant_expr->getOperand(operand_index);
2010
Greg Clayton3c7feb42010-11-19 01:05:25 +00002011 if (operand == old_constant)
2012 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002013
Sean Callanan9b6898f2011-07-30 02:42:06 +00002014 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002015 }
2016
Sean Callanan9b6898f2011-07-30 02:42:06 +00002017 ArrayRef <Value*> indices(index_vector);
2018
2019 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002020
Greg Clayton3c7feb42010-11-19 01:05:25 +00002021 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002022 }
2023 break;
2024 }
2025 }
2026 else
2027 {
2028 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002029 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002030 return false;
2031 }
2032 }
2033 else
2034 {
2035 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002036 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002037 }
2038 }
2039
2040 return true;
2041}
2042
Sean Callanan8bce6652010-07-13 21:41:46 +00002043bool
Sean Callananc0492742011-05-23 21:40:23 +00002044IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002045{
Sean Callanane8a59a82010-09-13 21:34:21 +00002046 if (!m_resolve_vars)
2047 return true;
2048
Greg Claytone005f2c2010-11-06 01:53:30 +00002049 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002050
2051 m_decl_map->DoStructLayout();
2052
2053 if (log)
2054 log->Printf("Element arrangement:");
2055
2056 uint32_t num_elements;
2057 uint32_t element_index;
2058
2059 size_t size;
2060 off_t alignment;
2061
2062 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2063 return false;
2064
Greg Clayton3c7feb42010-11-19 01:05:25 +00002065 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002066
Greg Clayton3c7feb42010-11-19 01:05:25 +00002067 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002068 {
2069 if (m_error_stream)
2070 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2071
Sean Callanan8bce6652010-07-13 21:41:46 +00002072 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002073 }
2074
Sean Callanan02fbafa2010-07-27 21:39:39 +00002075 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002076
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002077 if (argument->getName().equals("this"))
2078 {
2079 ++iter;
2080
Greg Clayton3c7feb42010-11-19 01:05:25 +00002081 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002082 {
2083 if (m_error_stream)
2084 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2085
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002086 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002087 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002088
2089 argument = iter;
2090 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002091 else if (argument->getName().equals("self"))
2092 {
2093 ++iter;
2094
2095 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002096 {
2097 if (m_error_stream)
2098 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2099
Sean Callanan3aa7da52010-12-13 22:46:15 +00002100 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002101 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002102
2103 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002104 {
2105 if (m_error_stream)
2106 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2107
Sean Callanan3aa7da52010-12-13 22:46:15 +00002108 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002109 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002110
2111 ++iter;
2112
2113 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002114 {
2115 if (m_error_stream)
2116 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2117
Sean Callanan3aa7da52010-12-13 22:46:15 +00002118 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002119 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002120
2121 argument = iter;
2122 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002123
Greg Clayton8de27c72010-10-15 22:48:33 +00002124 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002125 {
2126 if (m_error_stream)
2127 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2128
Sean Callanan8bce6652010-07-13 21:41:46 +00002129 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002130 }
2131
Sean Callanan8bce6652010-07-13 21:41:46 +00002132 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002133 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002134
Greg Clayton3c7feb42010-11-19 01:05:25 +00002135 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002136 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002137
Sean Callanan6ba533e2010-11-17 23:00:36 +00002138 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002139 {
2140 if (m_error_stream)
2141 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2142
Sean Callanan8bce6652010-07-13 21:41:46 +00002143 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002144 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002145
Sean Callananc0492742011-05-23 21:40:23 +00002146 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002147 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002148
2149 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002150 {
2151 if (m_error_stream)
2152 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2153
Sean Callanan8bce6652010-07-13 21:41:46 +00002154 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002155 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002156
2157 for (element_index = 0; element_index < num_elements; ++element_index)
2158 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002159 const clang::NamedDecl *decl = NULL;
2160 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002161 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002162 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002163
Sean Callanan45690fe2010-08-30 22:17:16 +00002164 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002165 {
2166 if (m_error_stream)
2167 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2168
Sean Callanan8bce6652010-07-13 21:41:46 +00002169 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002170 }
2171
Sean Callanan8bce6652010-07-13 21:41:46 +00002172 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002173 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00002174 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00002175 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002176 PrintValue(value, true).c_str(),
2177 offset);
2178
Sean Callanan9b6898f2011-07-30 02:42:06 +00002179 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002180 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002181
Sean Callanan58baaad2011-07-08 00:39:14 +00002182 Value *replacement = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002183
Sean Callanan6a925532011-01-13 08:53:35 +00002184 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2185 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2186 // entry in order to produce the static variable that the AST thinks it is accessing.
2187 if (name == m_result_name && !m_result_is_pointer)
2188 {
2189 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2190
2191 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2192
2193 replacement = load;
2194 }
Sean Callananbafd6852010-07-14 23:40:29 +00002195 else
Sean Callanan6a925532011-01-13 08:53:35 +00002196 {
2197 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2198
2199 replacement = bit_cast;
2200 }
2201
2202 if (Constant *constant = dyn_cast<Constant>(value))
2203 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2204 else
2205 value->replaceAllUsesWith(replacement);
Sean Callananb51ee982010-11-02 23:51:17 +00002206
2207 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2208 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00002209 }
2210
2211 if (log)
2212 log->Printf("Total structure [align %d, size %d]", alignment, size);
2213
2214 return true;
2215}
2216
Sean Callananc0492742011-05-23 21:40:23 +00002217llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002218IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002219 uint64_t offset)
2220{
2221 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2222
Sean Callanan9b6898f2011-07-30 02:42:06 +00002223 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2224 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002225
2226 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002227
2228 llvm::Constant *offset_array[1];
2229
2230 offset_array[0] = offset_int;
2231
2232 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2233
2234 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002235 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2236
2237 return reloc_getbitcast;
2238}
2239
2240bool
2241IRForTarget::CompleteDataAllocation ()
2242{
2243 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2244
2245 if (!m_data_allocator->GetStream().GetSize())
2246 return true;
2247
2248 lldb::addr_t allocation = m_data_allocator->Allocate();
2249
2250 if (log)
2251 {
2252 if (allocation)
2253 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2254 else
2255 log->Printf("Failed to allocate static data");
2256 }
2257
2258 if (!allocation)
2259 return false;
2260
Sean Callanan9b6898f2011-07-30 02:42:06 +00002261 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2262 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002263
2264 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2265 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2266
2267 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2268
2269 m_reloc_placeholder->eraseFromParent();
2270
2271 return true;
2272}
2273
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002274bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002275IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002276{
Greg Claytone005f2c2010-11-06 01:53:30 +00002277 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002278
Sean Callananc0492742011-05-23 21:40:23 +00002279 m_module = &llvm_module;
2280
2281 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002282
2283 if (!function)
2284 {
2285 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002286 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002287
2288 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002289 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002290
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002291 return false;
2292 }
Sean Callananc0492742011-05-23 21:40:23 +00002293
2294 if (!FixFunctionLinkage (*function))
2295 {
2296 if (log)
2297 log->Printf("Couldn't fix the linkage for the function");
2298
2299 return false;
2300 }
2301
Sean Callanan9b6898f2011-07-30 02:42:06 +00002302 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002303
2304 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2305 intptr_ty,
2306 false /* isConstant */,
2307 GlobalVariable::InternalLinkage,
2308 Constant::getNullValue(intptr_ty),
2309 "reloc_placeholder",
2310 NULL /* InsertBefore */,
2311 false /* ThreadLocal */,
2312 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002313
Sean Callanan02fbafa2010-07-27 21:39:39 +00002314 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002315
Sean Callananc0492742011-05-23 21:40:23 +00002316 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002317
Sean Callanan82b74c82010-08-12 01:56:52 +00002318 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002319 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002320 //
2321
Sean Callananc0492742011-05-23 21:40:23 +00002322 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002323 {
2324 if (log)
2325 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002326
2327 // CreateResultVariable() reports its own errors, so we don't do so here
2328
Sean Callanan82b74c82010-08-12 01:56:52 +00002329 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002330 }
Sean Callanan82b74c82010-08-12 01:56:52 +00002331
Sean Callanan696cf5f2011-05-07 01:06:41 +00002332 if (m_const_result)
2333 return true;
2334
Sean Callananc0492742011-05-23 21:40:23 +00002335 if (log)
2336 {
2337 std::string s;
2338 raw_string_ostream oss(s);
2339
2340 m_module->print(oss, NULL);
2341
2342 oss.flush();
2343
2344 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2345 }
2346
Sean Callanan6ba533e2010-11-17 23:00:36 +00002347 ///////////////////////////////////////////////////////////////////////////////
2348 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2349 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002350
Sean Callananc0492742011-05-23 21:40:23 +00002351 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002352 {
2353 if (log)
2354 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002355
2356 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2357
Sean Callanan6ba533e2010-11-17 23:00:36 +00002358 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002359 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002360
Sean Callananf5857a02010-07-31 01:32:05 +00002361 //////////////////////////////////
2362 // Run basic-block level passes
2363 //
2364
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002365 for (bbi = function->begin();
2366 bbi != function->end();
2367 ++bbi)
2368 {
Sean Callananc0492742011-05-23 21:40:23 +00002369 if (!RemoveGuards(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002370 {
2371 if (log)
2372 log->Printf("RemoveGuards() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002373
2374 // RemoveGuards() reports its own errors, so we don't do so here
2375
Sean Callanan8c127202010-08-23 23:09:38 +00002376 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002377 }
Sean Callanan8c127202010-08-23 23:09:38 +00002378
Sean Callananc0492742011-05-23 21:40:23 +00002379 if (!RewritePersistentAllocs(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002380 {
2381 if (log)
2382 log->Printf("RewritePersistentAllocs() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002383
2384 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2385
Sean Callananf5857a02010-07-31 01:32:05 +00002386 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002387 }
Sean Callananf5857a02010-07-31 01:32:05 +00002388
Sean Callananc0492742011-05-23 21:40:23 +00002389 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002390 {
2391 if (log)
2392 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002393
2394 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2395
Sean Callanana48fe162010-08-11 03:57:18 +00002396 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002397 }
Sean Callanana48fe162010-08-11 03:57:18 +00002398
Sean Callananc0492742011-05-23 21:40:23 +00002399 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002400 {
2401 if (log)
2402 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002403
2404 // ResolveCalls() reports its own errors, so we don't do so here
2405
Sean Callanan8bce6652010-07-13 21:41:46 +00002406 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002407 }
Sean Callananc0492742011-05-23 21:40:23 +00002408
2409 if (!ReplaceStaticLiterals(*bbi))
2410 {
2411 if (log)
2412 log->Printf("ReplaceStaticLiterals() failed");
2413
2414 return false;
2415 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002416 }
2417
Sean Callanan771131d2010-09-30 21:18:25 +00002418 ///////////////////////////////
2419 // Run function-level passes
2420 //
2421
Sean Callananc0492742011-05-23 21:40:23 +00002422 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002423 {
2424 if (log)
2425 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002426
2427 // ResolveExternals() reports its own errors, so we don't do so here
2428
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002429 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002430 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002431
Sean Callananc0492742011-05-23 21:40:23 +00002432 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002433 {
2434 if (log)
2435 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002436
2437 // ReplaceVariables() reports its own errors, so we don't do so here
2438
Sean Callanan771131d2010-09-30 21:18:25 +00002439 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002440 }
Sean Callanan771131d2010-09-30 21:18:25 +00002441
Sean Callananc0492742011-05-23 21:40:23 +00002442 if (!ReplaceStrings())
2443 {
2444 if (log)
2445 log->Printf("ReplaceStrings() failed");
2446
2447 return false;
2448 }
2449
2450 if (!CompleteDataAllocation())
2451 {
2452 if (log)
2453 log->Printf("CompleteDataAllocation() failed");
2454
2455 return false;
2456 }
2457
Sean Callanan8bce6652010-07-13 21:41:46 +00002458 if (log)
2459 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002460 std::string s;
2461 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002462
Sean Callananc0492742011-05-23 21:40:23 +00002463 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002464
2465 oss.flush();
2466
Greg Claytonb5037af2010-11-15 01:47:11 +00002467 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002468 }
2469
2470 return true;
2471}
2472
2473void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002474IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002475{
2476}
2477
2478PassManagerType
2479IRForTarget::getPotentialPassManagerType() const
2480{
2481 return PMT_ModulePassManager;
2482}