blob: af919a15f21f0f7337b3b7eac7230293f9c24f90 [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 Callanan57fb37e2011-08-01 20:53:53 +00001411
1412 bool is_bitcast = false;
Sean Callanan9a877432011-08-01 17:41:38 +00001413
1414 // If the call is to something other than a plain llvm::Function, resolve which
1415 // Function is meant or give up.
Sean Callananba992c52010-07-27 02:07:53 +00001416
1417 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +00001418 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001419 Value *val = llvm_call_inst->getCalledValue();
Sean Callanan65af7342010-09-08 20:04:08 +00001420
1421 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
Sean Callanand5b3c352011-01-27 04:42:51 +00001422 LoadInst *load_inst = dyn_cast<LoadInst>(val);
Sean Callanan65af7342010-09-08 20:04:08 +00001423
1424 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
1425 {
1426 fun = dyn_cast<Function>(const_expr->getOperand(0));
1427
1428 if (!fun)
Sean Callanan97c924e2011-01-27 01:07:04 +00001429 {
1430 if (m_error_stream)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001431 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 +00001432
Sean Callanan48443652010-12-02 19:47:57 +00001433 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001434 }
Sean Callanan57fb37e2011-08-01 20:53:53 +00001435
1436 is_bitcast = true;
Sean Callanan65af7342010-09-08 20:04:08 +00001437 }
Sean Callananc4217a62010-12-06 23:53:20 +00001438 else if (const_expr && const_expr->getOpcode() == Instruction::IntToPtr)
1439 {
1440 return true; // already resolved
1441 }
Sean Callanand5b3c352011-01-27 04:42:51 +00001442 else if (load_inst)
1443 {
1444 return true; // virtual method call
1445 }
Sean Callanan65af7342010-09-08 20:04:08 +00001446 else
1447 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001448 if (m_error_stream)
1449 m_error_stream->Printf("Internal error [IRForTarget]: Called entity is not a function\n");
1450
Sean Callanan48443652010-12-02 19:47:57 +00001451 return false;
Sean Callanan65af7342010-09-08 20:04:08 +00001452 }
1453 }
Sean Callananba992c52010-07-27 02:07:53 +00001454
Sean Callanan9a877432011-08-01 17:41:38 +00001455 // Determine the name of the called function, which is needed to find the address.
1456 // Intrinsics are special-cased.
1457
Greg Clayton8de27c72010-10-15 22:48:33 +00001458 lldb_private::ConstString str;
Sean Callananc04743d2010-09-28 21:13:03 +00001459
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001460 if (fun->isIntrinsic())
Sean Callananc04743d2010-09-28 21:13:03 +00001461 {
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001462 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
Sean Callananc04743d2010-09-28 21:13:03 +00001463
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001464 switch (intrinsic_id)
1465 {
1466 default:
1467 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001468 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001469
1470 if (m_error_stream)
1471 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
1472
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001473 return false;
1474 case Intrinsic::memcpy:
Greg Clayton8de27c72010-10-15 22:48:33 +00001475 {
1476 static lldb_private::ConstString g_memcpy_str ("memcpy");
1477 str = g_memcpy_str;
1478 }
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001479 break;
1480 }
Sean Callananc04743d2010-09-28 21:13:03 +00001481
Greg Clayton8de27c72010-10-15 22:48:33 +00001482 if (log && str)
Greg Claytonb5037af2010-11-15 01:47:11 +00001483 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString());
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001484 }
1485 else
1486 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001487 str.SetCStringWithLength (fun->getName().data(), fun->getName().size());
Sean Callananc04743d2010-09-28 21:13:03 +00001488 }
1489
Sean Callanan9a877432011-08-01 17:41:38 +00001490 // Find the address of the function, and the type if possible.
1491
Sean Callananc0492742011-05-23 21:40:23 +00001492 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Greg Claytonb5037af2010-11-15 01:47:11 +00001493 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS;
Sean Callananf5857a02010-07-31 01:32:05 +00001494 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +00001495
Sean Callananf5857a02010-07-31 01:32:05 +00001496 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +00001497 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001498 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001499 {
Sean Callanan92aa6662010-09-07 21:49:41 +00001500 fun_value_ptr = NULL;
1501
Greg Clayton8de27c72010-10-15 22:48:33 +00001502 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +00001503 {
1504 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001505 log->Printf("Function \"%s\" had no address", str.GetCString());
Sean Callanan92aa6662010-09-07 21:49:41 +00001506
Sean Callanan97c924e2011-01-27 01:07:04 +00001507 if (m_error_stream)
1508 m_error_stream->Printf("Error [IRForTarget]: Call to a function '%s' that is not present in the target\n", str.GetCString());
1509
Sean Callanan92aa6662010-09-07 21:49:41 +00001510 return false;
1511 }
Sean Callananf5857a02010-07-31 01:32:05 +00001512 }
1513 }
1514 else
1515 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001516 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001517 {
1518 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001519 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString());
Sean Callanan97c924e2011-01-27 01:07:04 +00001520
1521 if (m_error_stream)
1522 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", str.GetCString());
1523
1524 return false;
Sean Callananf5857a02010-07-31 01:32:05 +00001525 }
Sean Callananba992c52010-07-27 02:07:53 +00001526 }
1527
1528 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001529 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +00001530
Sean Callanan9a877432011-08-01 17:41:38 +00001531 // Construct the typed pointer to the function.
1532
Sean Callanan58baaad2011-07-08 00:39:14 +00001533 Value *fun_addr_ptr = NULL;
Sean Callananf5857a02010-07-31 01:32:05 +00001534
1535 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +00001536 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001537 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1538 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1539 FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +00001540 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
1541 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001542 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
1543
1544 if (fun_value_ptr)
1545 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001546 }
Sean Callananf5857a02010-07-31 01:32:05 +00001547
1548 if (fun_value_ptr)
1549 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001550
Sean Callanan57fb37e2011-08-01 20:53:53 +00001551 if (is_bitcast)
1552 {
1553 Value *val = llvm_call_inst->getCalledValue();
1554
1555 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
1556
1557 Constant *fun_addr_ptr_cst = dyn_cast<Constant>(fun_addr_ptr);
1558
1559 if (!fun_addr_ptr_cst)
1560 {
1561 if (m_error_stream)
1562 m_error_stream->Printf("Error [IRForTarget]: Non-constant source function '%s' has a constant BitCast\n", str.GetCString());
1563
1564 return false;
1565 }
1566
1567 Constant *new_bit_cast = ConstantExpr::getBitCast(fun_addr_ptr_cst, const_expr->getType());
1568
1569 llvm_call_inst->setCalledFunction(new_bit_cast);
1570 }
1571 else
1572 {
1573 llvm_call_inst->setCalledFunction(fun_addr_ptr);
1574 }
Sean Callanan02fbafa2010-07-27 21:39:39 +00001575
Sean Callananc0492742011-05-23 21:40:23 +00001576 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(m_module->getContext(), str.GetCString());
Sean Callanane8a59a82010-09-13 21:34:21 +00001577
1578 Value *values[1];
1579 values[0] = func_name;
Sean Callanan0de254a2011-05-15 22:34:38 +00001580 ArrayRef<Value*> value_ref(values, 1);
1581
Sean Callananc0492742011-05-23 21:40:23 +00001582 MDNode *func_metadata = MDNode::get(m_module->getContext(), value_ref);
Sean Callanane8a59a82010-09-13 21:34:21 +00001583
Greg Clayton8de27c72010-10-15 22:48:33 +00001584 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata);
Sean Callanane8a59a82010-09-13 21:34:21 +00001585
1586 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001587 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 +00001588
Sean Callananba992c52010-07-27 02:07:53 +00001589 return true;
1590}
1591
1592bool
Sean Callananc0492742011-05-23 21:40:23 +00001593IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001594{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001595 /////////////////////////////////////////////////////////////////////////
1596 // Prepare the current basic block for execution in the remote process
1597 //
1598
Sean Callanan02fbafa2010-07-27 21:39:39 +00001599 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001600
Greg Clayton3c7feb42010-11-19 01:05:25 +00001601 for (ii = basic_block.begin();
1602 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001603 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001604 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001605 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001606
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001607 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001608
Sean Callanan97c924e2011-01-27 01:07:04 +00001609 // MaybeHandleCall handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001610 if (call && !MaybeHandleCall(call))
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001611 return false;
Sean Callanan48443652010-12-02 19:47:57 +00001612
Sean Callanan97c924e2011-01-27 01:07:04 +00001613 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001614 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001615 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001616 }
1617
1618 return true;
1619}
1620
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001621bool
Sean Callananc0492742011-05-23 21:40:23 +00001622IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001623{
Sean Callananae71e302010-11-18 22:21:58 +00001624 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1625
Sean Callananc0492742011-05-23 21:40:23 +00001626 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001627 global != end;
1628 ++global)
1629 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001630 if (log)
1631 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1632 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001633 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001634
Sean Callananc7674af2011-01-17 23:42:46 +00001635 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1636 {
Sean Callananc0492742011-05-23 21:40:23 +00001637 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001638 {
1639 if (m_error_stream)
1640 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1641
Sean Callananc7674af2011-01-17 23:42:46 +00001642 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001643 }
Sean Callananc7674af2011-01-17 23:42:46 +00001644 }
Sean Callananc0492742011-05-23 21:40:23 +00001645 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001646 {
Sean Callananc0492742011-05-23 21:40:23 +00001647 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001648 {
1649 if (m_error_stream)
1650 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1651
Sean Callananc7674af2011-01-17 23:42:46 +00001652 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001653 }
Sean Callananc7674af2011-01-17 23:42:46 +00001654 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001655 }
1656
1657 return true;
1658}
1659
Sean Callananc0492742011-05-23 21:40:23 +00001660bool
1661IRForTarget::ReplaceStrings ()
1662{
1663 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1664
1665 if (!m_data_allocator)
1666 return true; // hope for the best; some clients may not want static allocation!
1667
1668 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1669
1670 OffsetsTy offsets;
1671
1672 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1673 gi != ge;
1674 ++gi)
1675 {
1676 GlobalVariable *gv = gi;
1677
1678 if (!gv->hasInitializer())
1679 continue;
1680
1681 Constant *gc = gv->getInitializer();
1682
1683 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1684
1685 if (!gc_array)
1686 continue;
1687
1688 if (!gc_array->isCString())
1689 continue;
1690
1691 if (log)
1692 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1693
1694 std::string str = gc_array->getAsString();
1695
1696 offsets[gv] = m_data_allocator->GetStream().GetSize();
1697
1698 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1699 }
1700
Sean Callanan9b6898f2011-07-30 02:42:06 +00001701 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001702
1703 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1704 oi != oe;
1705 ++oi)
1706 {
1707 GlobalVariable *gv = oi->first;
1708 size_t offset = oi->second;
1709
1710 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1711
1712 if (log)
1713 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1714
1715 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1716 ui != ue;
1717 ++ui)
1718 {
1719 if (log)
1720 log->Printf("Found use %s", PrintValue(*ui).c_str());
1721
1722 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1723 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1724
1725 if (const_expr)
1726 {
1727 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1728 {
1729 if (log)
1730 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1731
1732 return false;
1733 }
1734
1735 const_expr->replaceAllUsesWith(new_initializer);
1736 }
1737 else if (store_inst)
1738 {
1739 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1740
1741 store_inst->setOperand(0, bit_cast);
1742 }
1743 else
1744 {
1745 if (log)
1746 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1747
1748 return false;
1749 }
1750 }
1751
1752 gv->eraseFromParent();
1753 }
1754
1755 return true;
1756}
1757
1758bool
1759IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1760{
1761 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1762
1763 if (!m_data_allocator)
1764 return true;
1765
1766 typedef SmallVector <Value*, 2> ConstantList;
1767 typedef SmallVector <llvm::Instruction*, 2> UserList;
1768 typedef ConstantList::iterator ConstantIterator;
1769 typedef UserList::iterator UserIterator;
1770
1771 ConstantList static_constants;
1772 UserList static_users;
1773
1774 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1775 ii != ie;
1776 ++ii)
1777 {
1778 llvm::Instruction &inst = *ii;
1779
1780 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1781 oi != oe;
1782 ++oi)
1783 {
1784 Value *operand_val = oi->get();
1785
1786 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1787
1788 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1789 {
1790 static_constants.push_back(operand_val);
1791 static_users.push_back(ii);
1792 }
1793 }
1794 }
1795
1796 ConstantIterator constant_iter;
1797 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00001798
Sean Callananc0492742011-05-23 21:40:23 +00001799 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1800 constant_iter != static_constants.end();
1801 ++constant_iter, ++user_iter)
1802 {
1803 Value *operand_val = *constant_iter;
1804 llvm::Instruction *inst = *user_iter;
1805
1806 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1807
1808 if (operand_constant_fp)
1809 {
1810 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1811 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1812
1813 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1814 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1815
1816 if (log)
1817 {
1818 std::string s;
1819 raw_string_ostream ss(s);
1820 for (size_t index = 0;
1821 index < operand_data_size;
1822 ++index)
1823 {
1824 ss << (uint32_t)operand_raw_data[index];
1825 ss << " ";
1826 }
1827 ss.flush();
1828
1829 log->Printf("Found ConstantFP with size %d and raw data %s", operand_data_size, s.c_str());
1830 }
1831
1832 lldb_private::DataBufferHeap data(operand_data_size, 0);
1833
1834 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
1835 {
1836 uint8_t *data_bytes = data.GetBytes();
1837
1838 for (size_t index = 0;
1839 index < operand_data_size;
1840 ++index)
1841 {
1842 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1843 }
1844 }
1845 else
1846 {
1847 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
1848 }
1849
1850 uint64_t offset = m_data_allocator->GetStream().GetSize();
1851
1852 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
1853
Sean Callanan9b6898f2011-07-30 02:42:06 +00001854 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00001855
1856 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
1857
1858 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
1859
1860 operand_constant_fp->replaceAllUsesWith(fp_load);
1861 }
1862 }
1863
1864 return true;
1865}
1866
Sean Callanan02fbafa2010-07-27 21:39:39 +00001867static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001868{
Sean Callanan58baaad2011-07-08 00:39:14 +00001869 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00001870
Sean Callanan6ba533e2010-11-17 23:00:36 +00001871 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001872 return false;
1873
Sean Callanan58baaad2011-07-08 00:39:14 +00001874 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001875
1876 if ((CE = dyn_cast<ConstantExpr>(V)))
1877 {
1878 if (CE->getOpcode() != Instruction::BitCast)
1879 return false;
1880
Sean Callanan6ba533e2010-11-17 23:00:36 +00001881 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001882 }
1883
Sean Callanan6ba533e2010-11-17 23:00:36 +00001884 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001885
1886 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1887 return false;
1888
1889 return true;
1890}
1891
Sean Callananc0492742011-05-23 21:40:23 +00001892void
1893IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00001894{
Sean Callananc0492742011-05-23 21:40:23 +00001895 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00001896
1897 Value::use_iterator ui;
1898
1899 for (ui = guard_load->use_begin();
1900 ui != guard_load->use_end();
1901 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001902 {
Greg Clayton6e713402010-07-30 20:30:44 +00001903 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001904 {
1905 // do nothing for the moment
1906 }
1907 else
1908 {
1909 ui->replaceUsesOfWith(guard_load, zero);
1910 }
1911 }
Sean Callanan45839272010-07-24 01:37:44 +00001912
1913 guard_load->eraseFromParent();
1914}
1915
1916static void ExciseGuardStore(Instruction* guard_store)
1917{
1918 guard_store->eraseFromParent();
1919}
1920
1921bool
Sean Callananc0492742011-05-23 21:40:23 +00001922IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00001923{
1924 ///////////////////////////////////////////////////////
1925 // Eliminate any reference to guard variables found.
1926 //
1927
Sean Callanan02fbafa2010-07-27 21:39:39 +00001928 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001929
Sean Callanan02fbafa2010-07-27 21:39:39 +00001930 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001931 typedef InstrList::iterator InstrIterator;
1932
1933 InstrList guard_loads;
1934 InstrList guard_stores;
1935
Greg Clayton3c7feb42010-11-19 01:05:25 +00001936 for (ii = basic_block.begin();
1937 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00001938 ++ii)
1939 {
1940 Instruction &inst = *ii;
1941
1942 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1943 if (isGuardVariableRef(load->getPointerOperand()))
1944 guard_loads.push_back(&inst);
1945
1946 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1947 if (isGuardVariableRef(store->getPointerOperand()))
1948 guard_stores.push_back(&inst);
1949 }
1950
1951 InstrIterator iter;
1952
1953 for (iter = guard_loads.begin();
1954 iter != guard_loads.end();
1955 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00001956 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00001957
1958 for (iter = guard_stores.begin();
1959 iter != guard_stores.end();
1960 ++iter)
1961 ExciseGuardStore(*iter);
1962
1963 return true;
1964}
1965
Sean Callanan97c924e2011-01-27 01:07:04 +00001966// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001967bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001968IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00001969{
Greg Claytone005f2c2010-11-06 01:53:30 +00001970 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001971
1972 Value::use_iterator ui;
1973
Sean Callanana48fe162010-08-11 03:57:18 +00001974 SmallVector<User*, 16> users;
1975
1976 // We do this because the use list might change, invalidating our iterator.
1977 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00001978 for (ui = old_constant->use_begin();
1979 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001980 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001981 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001982
Johnny Chen2bc9eb32011-07-19 19:48:13 +00001983 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00001984 i < users.size();
1985 ++i)
1986 {
1987 User *user = users[i];
1988
Sean Callananbafd6852010-07-14 23:40:29 +00001989 if (Constant *constant = dyn_cast<Constant>(user))
1990 {
1991 // synthesize a new non-constant equivalent of the constant
1992
1993 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1994 {
1995 switch (constant_expr->getOpcode())
1996 {
1997 default:
1998 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001999 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002000 return false;
2001 case Instruction::BitCast:
2002 {
2003 // UnaryExpr
2004 // OperandList[0] is value
2005
2006 Value *s = constant_expr->getOperand(0);
2007
Greg Clayton3c7feb42010-11-19 01:05:25 +00002008 if (s == old_constant)
2009 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002010
Sean Callananc0492742011-05-23 21:40:23 +00002011 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002012
Greg Clayton3c7feb42010-11-19 01:05:25 +00002013 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002014 }
2015 break;
2016 case Instruction::GetElementPtr:
2017 {
2018 // GetElementPtrConstantExpr
2019 // OperandList[0] is base
2020 // OperandList[1]... are indices
2021
2022 Value *ptr = constant_expr->getOperand(0);
2023
Greg Clayton3c7feb42010-11-19 01:05:25 +00002024 if (ptr == old_constant)
2025 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002026
2027 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002028
2029 unsigned operand_index;
2030 unsigned num_operands = constant_expr->getNumOperands();
2031
2032 for (operand_index = 1;
2033 operand_index < num_operands;
2034 ++operand_index)
2035 {
2036 Value *operand = constant_expr->getOperand(operand_index);
2037
Greg Clayton3c7feb42010-11-19 01:05:25 +00002038 if (operand == old_constant)
2039 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002040
Sean Callanan9b6898f2011-07-30 02:42:06 +00002041 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002042 }
2043
Sean Callanan9b6898f2011-07-30 02:42:06 +00002044 ArrayRef <Value*> indices(index_vector);
2045
2046 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002047
Greg Clayton3c7feb42010-11-19 01:05:25 +00002048 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002049 }
2050 break;
2051 }
2052 }
2053 else
2054 {
2055 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002056 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002057 return false;
2058 }
2059 }
2060 else
2061 {
2062 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002063 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002064 }
2065 }
2066
2067 return true;
2068}
2069
Sean Callanan8bce6652010-07-13 21:41:46 +00002070bool
Sean Callananc0492742011-05-23 21:40:23 +00002071IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002072{
Sean Callanane8a59a82010-09-13 21:34:21 +00002073 if (!m_resolve_vars)
2074 return true;
2075
Greg Claytone005f2c2010-11-06 01:53:30 +00002076 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002077
2078 m_decl_map->DoStructLayout();
2079
2080 if (log)
2081 log->Printf("Element arrangement:");
2082
2083 uint32_t num_elements;
2084 uint32_t element_index;
2085
2086 size_t size;
2087 off_t alignment;
2088
2089 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2090 return false;
2091
Greg Clayton3c7feb42010-11-19 01:05:25 +00002092 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002093
Greg Clayton3c7feb42010-11-19 01:05:25 +00002094 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002095 {
2096 if (m_error_stream)
2097 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2098
Sean Callanan8bce6652010-07-13 21:41:46 +00002099 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002100 }
2101
Sean Callanan02fbafa2010-07-27 21:39:39 +00002102 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002103
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002104 if (argument->getName().equals("this"))
2105 {
2106 ++iter;
2107
Greg Clayton3c7feb42010-11-19 01:05:25 +00002108 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002109 {
2110 if (m_error_stream)
2111 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2112
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002113 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002114 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002115
2116 argument = iter;
2117 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002118 else if (argument->getName().equals("self"))
2119 {
2120 ++iter;
2121
2122 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002123 {
2124 if (m_error_stream)
2125 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2126
Sean Callanan3aa7da52010-12-13 22:46:15 +00002127 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002128 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002129
2130 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002131 {
2132 if (m_error_stream)
2133 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2134
Sean Callanan3aa7da52010-12-13 22:46:15 +00002135 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002136 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002137
2138 ++iter;
2139
2140 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002141 {
2142 if (m_error_stream)
2143 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2144
Sean Callanan3aa7da52010-12-13 22:46:15 +00002145 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002146 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002147
2148 argument = iter;
2149 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002150
Greg Clayton8de27c72010-10-15 22:48:33 +00002151 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002152 {
2153 if (m_error_stream)
2154 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2155
Sean Callanan8bce6652010-07-13 21:41:46 +00002156 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002157 }
2158
Sean Callanan8bce6652010-07-13 21:41:46 +00002159 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002160 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002161
Greg Clayton3c7feb42010-11-19 01:05:25 +00002162 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002163 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002164
Sean Callanan6ba533e2010-11-17 23:00:36 +00002165 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002166 {
2167 if (m_error_stream)
2168 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2169
Sean Callanan8bce6652010-07-13 21:41:46 +00002170 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002171 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002172
Sean Callananc0492742011-05-23 21:40:23 +00002173 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002174 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002175
2176 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002177 {
2178 if (m_error_stream)
2179 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2180
Sean Callanan8bce6652010-07-13 21:41:46 +00002181 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002182 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002183
2184 for (element_index = 0; element_index < num_elements; ++element_index)
2185 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002186 const clang::NamedDecl *decl = NULL;
2187 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002188 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002189 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002190
Sean Callanan45690fe2010-08-30 22:17:16 +00002191 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002192 {
2193 if (m_error_stream)
2194 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2195
Sean Callanan8bce6652010-07-13 21:41:46 +00002196 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002197 }
2198
Sean Callanan8bce6652010-07-13 21:41:46 +00002199 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002200 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00002201 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00002202 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002203 PrintValue(value, true).c_str(),
2204 offset);
2205
Sean Callanan9b6898f2011-07-30 02:42:06 +00002206 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002207 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002208
Sean Callanan58baaad2011-07-08 00:39:14 +00002209 Value *replacement = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002210
Sean Callanan6a925532011-01-13 08:53:35 +00002211 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2212 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2213 // entry in order to produce the static variable that the AST thinks it is accessing.
2214 if (name == m_result_name && !m_result_is_pointer)
2215 {
2216 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2217
2218 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2219
2220 replacement = load;
2221 }
Sean Callananbafd6852010-07-14 23:40:29 +00002222 else
Sean Callanan6a925532011-01-13 08:53:35 +00002223 {
2224 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2225
2226 replacement = bit_cast;
2227 }
2228
2229 if (Constant *constant = dyn_cast<Constant>(value))
2230 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2231 else
2232 value->replaceAllUsesWith(replacement);
Sean Callananb51ee982010-11-02 23:51:17 +00002233
2234 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2235 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00002236 }
2237
2238 if (log)
2239 log->Printf("Total structure [align %d, size %d]", alignment, size);
2240
2241 return true;
2242}
2243
Sean Callananc0492742011-05-23 21:40:23 +00002244llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002245IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002246 uint64_t offset)
2247{
2248 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2249
Sean Callanan9b6898f2011-07-30 02:42:06 +00002250 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2251 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002252
2253 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002254
2255 llvm::Constant *offset_array[1];
2256
2257 offset_array[0] = offset_int;
2258
2259 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2260
2261 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002262 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2263
2264 return reloc_getbitcast;
2265}
2266
2267bool
2268IRForTarget::CompleteDataAllocation ()
2269{
2270 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2271
2272 if (!m_data_allocator->GetStream().GetSize())
2273 return true;
2274
2275 lldb::addr_t allocation = m_data_allocator->Allocate();
2276
2277 if (log)
2278 {
2279 if (allocation)
2280 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2281 else
2282 log->Printf("Failed to allocate static data");
2283 }
2284
2285 if (!allocation)
2286 return false;
2287
Sean Callanan9b6898f2011-07-30 02:42:06 +00002288 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2289 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002290
2291 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2292 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2293
2294 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2295
2296 m_reloc_placeholder->eraseFromParent();
2297
2298 return true;
2299}
2300
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002301bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002302IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002303{
Greg Claytone005f2c2010-11-06 01:53:30 +00002304 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002305
Sean Callananc0492742011-05-23 21:40:23 +00002306 m_module = &llvm_module;
2307
2308 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002309
2310 if (!function)
2311 {
2312 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002313 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002314
2315 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002316 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 +00002317
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002318 return false;
2319 }
Sean Callananc0492742011-05-23 21:40:23 +00002320
2321 if (!FixFunctionLinkage (*function))
2322 {
2323 if (log)
2324 log->Printf("Couldn't fix the linkage for the function");
2325
2326 return false;
2327 }
2328
Sean Callanan9b6898f2011-07-30 02:42:06 +00002329 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002330
2331 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2332 intptr_ty,
2333 false /* isConstant */,
2334 GlobalVariable::InternalLinkage,
2335 Constant::getNullValue(intptr_ty),
2336 "reloc_placeholder",
2337 NULL /* InsertBefore */,
2338 false /* ThreadLocal */,
2339 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002340
Sean Callanan02fbafa2010-07-27 21:39:39 +00002341 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002342
Sean Callananc0492742011-05-23 21:40:23 +00002343 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002344
Sean Callanan82b74c82010-08-12 01:56:52 +00002345 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002346 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002347 //
2348
Sean Callananc0492742011-05-23 21:40:23 +00002349 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002350 {
2351 if (log)
2352 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002353
2354 // CreateResultVariable() reports its own errors, so we don't do so here
2355
Sean Callanan82b74c82010-08-12 01:56:52 +00002356 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002357 }
Sean Callanan82b74c82010-08-12 01:56:52 +00002358
Sean Callanan696cf5f2011-05-07 01:06:41 +00002359 if (m_const_result)
2360 return true;
2361
Sean Callananc0492742011-05-23 21:40:23 +00002362 if (log)
2363 {
2364 std::string s;
2365 raw_string_ostream oss(s);
2366
2367 m_module->print(oss, NULL);
2368
2369 oss.flush();
2370
2371 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2372 }
2373
Sean Callanan6ba533e2010-11-17 23:00:36 +00002374 ///////////////////////////////////////////////////////////////////////////////
2375 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2376 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002377
Sean Callananc0492742011-05-23 21:40:23 +00002378 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002379 {
2380 if (log)
2381 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002382
2383 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2384
Sean Callanan6ba533e2010-11-17 23:00:36 +00002385 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002386 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002387
Sean Callananf5857a02010-07-31 01:32:05 +00002388 //////////////////////////////////
2389 // Run basic-block level passes
2390 //
2391
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002392 for (bbi = function->begin();
2393 bbi != function->end();
2394 ++bbi)
2395 {
Sean Callananc0492742011-05-23 21:40:23 +00002396 if (!RemoveGuards(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002397 {
2398 if (log)
2399 log->Printf("RemoveGuards() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002400
2401 // RemoveGuards() reports its own errors, so we don't do so here
2402
Sean Callanan8c127202010-08-23 23:09:38 +00002403 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002404 }
Sean Callanan8c127202010-08-23 23:09:38 +00002405
Sean Callananc0492742011-05-23 21:40:23 +00002406 if (!RewritePersistentAllocs(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002407 {
2408 if (log)
2409 log->Printf("RewritePersistentAllocs() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002410
2411 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2412
Sean Callananf5857a02010-07-31 01:32:05 +00002413 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002414 }
Sean Callananf5857a02010-07-31 01:32:05 +00002415
Sean Callananc0492742011-05-23 21:40:23 +00002416 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002417 {
2418 if (log)
2419 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002420
2421 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2422
Sean Callanana48fe162010-08-11 03:57:18 +00002423 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002424 }
Sean Callanana48fe162010-08-11 03:57:18 +00002425
Sean Callananc0492742011-05-23 21:40:23 +00002426 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002427 {
2428 if (log)
2429 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002430
2431 // ResolveCalls() reports its own errors, so we don't do so here
2432
Sean Callanan8bce6652010-07-13 21:41:46 +00002433 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002434 }
Sean Callananc0492742011-05-23 21:40:23 +00002435
2436 if (!ReplaceStaticLiterals(*bbi))
2437 {
2438 if (log)
2439 log->Printf("ReplaceStaticLiterals() failed");
2440
2441 return false;
2442 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002443 }
2444
Sean Callanan771131d2010-09-30 21:18:25 +00002445 ///////////////////////////////
2446 // Run function-level passes
2447 //
2448
Sean Callananc0492742011-05-23 21:40:23 +00002449 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002450 {
2451 if (log)
2452 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002453
2454 // ResolveExternals() reports its own errors, so we don't do so here
2455
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002456 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002457 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002458
Sean Callananc0492742011-05-23 21:40:23 +00002459 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002460 {
2461 if (log)
2462 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002463
2464 // ReplaceVariables() reports its own errors, so we don't do so here
2465
Sean Callanan771131d2010-09-30 21:18:25 +00002466 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002467 }
Sean Callanan771131d2010-09-30 21:18:25 +00002468
Sean Callananc0492742011-05-23 21:40:23 +00002469 if (!ReplaceStrings())
2470 {
2471 if (log)
2472 log->Printf("ReplaceStrings() failed");
2473
2474 return false;
2475 }
2476
2477 if (!CompleteDataAllocation())
2478 {
2479 if (log)
2480 log->Printf("CompleteDataAllocation() failed");
2481
2482 return false;
2483 }
2484
Sean Callanan8bce6652010-07-13 21:41:46 +00002485 if (log)
2486 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002487 std::string s;
2488 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002489
Sean Callananc0492742011-05-23 21:40:23 +00002490 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002491
2492 oss.flush();
2493
Greg Claytonb5037af2010-11-15 01:47:11 +00002494 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002495 }
2496
2497 return true;
2498}
2499
2500void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002501IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002502{
2503}
2504
2505PassManagerType
2506IRForTarget::getPotentialPassManagerType() const
2507{
2508 return PMT_ModulePassManager;
2509}