blob: 3722f34bd5d6172ea41be0ff0dda61669269367c [file] [log] [blame]
Sean Callanan47dc4572011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
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 Callanan47dc4572011-09-15 02:13:07 +000029#include "lldb/Expression/IRInterpreter.h"
Sean Callananc0492742011-05-23 21:40:23 +000030#include "lldb/Host/Endian.h"
Sean Callanan696cf5f2011-05-07 01:06:41 +000031#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000032
33#include <map>
34
35using namespace llvm;
36
Sean Callanan3351dac2010-08-18 18:50:51 +000037static char ID;
38
Sean Callananc0492742011-05-23 21:40:23 +000039IRForTarget::StaticDataAllocator::StaticDataAllocator()
40{
41}
42
43IRForTarget::StaticDataAllocator::~StaticDataAllocator()
44{
45}
46
Greg Clayton3c7feb42010-11-19 01:05:25 +000047IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
48 bool resolve_vars,
Sean Callanan47dc4572011-09-15 02:13:07 +000049 lldb_private::ExecutionPolicy execution_policy,
Sean Callanan696cf5f2011-05-07 01:06:41 +000050 lldb::ClangExpressionVariableSP &const_result,
Sean Callananc0492742011-05-23 21:40:23 +000051 StaticDataAllocator *data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +000052 lldb_private::Stream *error_stream,
Greg Clayton3c7feb42010-11-19 01:05:25 +000053 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000054 ModulePass(ID),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000055 m_resolve_vars(resolve_vars),
Sean Callanan47dc4572011-09-15 02:13:07 +000056 m_execution_policy(execution_policy),
57 m_interpret_success(false),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000058 m_func_name(func_name),
Sean Callananc0492742011-05-23 21:40:23 +000059 m_module(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000060 m_decl_map(decl_map),
61 m_data_allocator(data_allocator),
Sean Callanan6ba533e2010-11-17 23:00:36 +000062 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000063 m_sel_registerName(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000064 m_const_result(const_result),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000065 m_error_stream(error_stream),
Sean Callanan6a925532011-01-13 08:53:35 +000066 m_has_side_effects(false),
Sean Callanan696cf5f2011-05-07 01:06:41 +000067 m_result_store(NULL),
68 m_result_is_pointer(false),
Sean Callananc0492742011-05-23 21:40:23 +000069 m_reloc_placeholder(NULL)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000070{
71}
72
Sean Callanan771131d2010-09-30 21:18:25 +000073/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000074
75static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000076PrintValue(const Value *value, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000077{
78 std::string s;
79 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000080 value->print(rso);
Sean Callanana48fe162010-08-11 03:57:18 +000081 rso.flush();
82 if (truncate)
83 s.resize(s.length() - 1);
84 return s;
85}
86
Sean Callanan771131d2010-09-30 21:18:25 +000087static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000088PrintType(const Type *type, bool truncate = false)
Sean Callanan771131d2010-09-30 21:18:25 +000089{
90 std::string s;
91 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000092 type->print(rso);
Sean Callanan771131d2010-09-30 21:18:25 +000093 rso.flush();
94 if (truncate)
95 s.resize(s.length() - 1);
96 return s;
97}
98
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000099IRForTarget::~IRForTarget()
100{
101}
102
Sean Callananc0492742011-05-23 21:40:23 +0000103bool
104IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
105{
106 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
107
108 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
109
Sean Callananfecc09c2011-11-19 02:54:21 +0000110 std::string name = llvm_function.getName().str();
Sean Callananc0492742011-05-23 21:40:23 +0000111
112 return true;
113}
114
Sean Callanan82b74c82010-08-12 01:56:52 +0000115bool
Sean Callananc0492742011-05-23 21:40:23 +0000116IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000117{
118 llvm::Function::iterator bbi;
119 BasicBlock::iterator ii;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000120
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000121 for (bbi = llvm_function.begin();
122 bbi != llvm_function.end();
123 ++bbi)
124 {
125 BasicBlock &basic_block = *bbi;
126
127 for (ii = basic_block.begin();
128 ii != basic_block.end();
129 ++ii)
130 {
131 switch (ii->getOpcode())
132 {
133 default:
134 return true;
135 case Instruction::Store:
136 {
137 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
138
139 Value *store_ptr = store_inst->getPointerOperand();
140
Sean Callanan696cf5f2011-05-07 01:06:41 +0000141 std::string ptr_name;
142
143 if (store_ptr->hasName())
Sean Callananfecc09c2011-11-19 02:54:21 +0000144 ptr_name = store_ptr->getName().str();
Sean Callanan696cf5f2011-05-07 01:06:41 +0000145
146 if (isa <AllocaInst> (store_ptr))
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000147 break;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000148
149 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
150 {
151 if (ptr_name.find("GV") == std::string::npos)
152 m_result_store = store_inst;
153 }
154 else
155 {
156 return true;
157 }
158
159 break;
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000160 }
161 case Instruction::Load:
162 case Instruction::Alloca:
163 case Instruction::GetElementPtr:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000164 case Instruction::BitCast:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000165 case Instruction::Ret:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000166 case Instruction::ICmp:
167 case Instruction::Br:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000168 break;
169 }
170 }
171 }
172
173 return false;
174}
175
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000176bool
177IRForTarget::GetFunctionAddress (llvm::Function *fun,
178 uint64_t &fun_addr,
179 lldb_private::ConstString &name,
180 Constant **&value_ptr)
181{
182 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
183
184 fun_addr = LLDB_INVALID_ADDRESS;
185 name.Clear();
186 value_ptr = NULL;
187
188 if (fun->isIntrinsic())
189 {
190 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
191
192 switch (intrinsic_id)
193 {
194 default:
195 if (log)
196 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
197
198 if (m_error_stream)
199 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
200
201 return false;
202 case Intrinsic::memcpy:
203 {
204 static lldb_private::ConstString g_memcpy_str ("memcpy");
205 name = g_memcpy_str;
206 }
207 break;
Sean Callanan7befa302011-11-16 00:20:50 +0000208 case Intrinsic::memset:
209 {
210 static lldb_private::ConstString g_memset_str ("memset");
211 name = g_memset_str;
212 }
213 break;
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000214 }
215
216 if (log && name)
217 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
218 }
219 else
220 {
221 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
222 }
223
224 // Find the address of the function.
225
226 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000227
228 if (fun_decl)
229 {
Sean Callananc7ca4662011-10-25 18:36:40 +0000230 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000231 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000232 lldb_private::ConstString alternate_mangling_const_str;
233 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
234 if (!found_it)
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000235 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000236 // Check for an alternate mangling for "std::basic_string<char>"
237 // that is part of the itanium C++ name mangling scheme
238 const char *name_cstr = name.GetCString();
239 if (strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
240 {
241 std::string alternate_mangling("_ZNKSs");
242 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
243 alternate_mangling_const_str.SetCString(alternate_mangling.c_str());
244 found_it = m_decl_map->GetFunctionAddress (alternate_mangling_const_str, fun_addr);
245 }
246 }
247
248 if (!found_it)
249 {
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000250 if (log)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000251 {
252 if (alternate_mangling_const_str)
253 log->Printf("Function \"%s\" (alternate name \"%s\") has no address", name.GetCString(), alternate_mangling_const_str.GetCString());
254 else
255 log->Printf("Function \"%s\" had no address", name.GetCString());
256 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000257
258 if (m_error_stream)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000259 {
260 if (alternate_mangling_const_str)
261 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n", name.GetCString(), alternate_mangling_const_str.GetCString());
262 else
263 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n", name.GetCString());
264 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000265 return false;
266 }
267 }
268 }
269 else
270 {
271 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
272 {
273 if (log)
274 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
275
276 if (m_error_stream)
277 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
278
279 return false;
280 }
281 }
282
283 if (log)
284 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), fun_addr);
285
286 return true;
287}
288
289llvm::Constant *
290IRForTarget::BuildFunctionPointer (llvm::Type *type,
291 uint64_t ptr)
292{
293 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
294 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
295 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
296 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
297 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
298}
299
Sean Callanan715f6b02011-10-31 22:11:40 +0000300void
301IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
302 llvm::Value *function_ptr,
303 const char *name)
304{
305 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
306
307 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
308 i != e;
309 ++i)
310 {
311 Value *user = *i;
312
313 if (Instruction *user_inst = dyn_cast<Instruction>(user))
314 {
315 Constant *name_array = ConstantArray::get(context, StringRef(name));
316
317 ArrayRef<Value *> md_values(name_array);
318
319 MDNode *metadata = MDNode::get(context, md_values);
320
321 user_inst->setMetadata("lldb.call.realName", metadata);
322 }
323 else
324 {
325 RegisterFunctionMetadata (context, user, name);
326 }
327 }
328}
329
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000330bool
331IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
332 llvm::Function &llvm_function)
333{
334 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
335
336 for (llvm::Module::iterator fi = llvm_module.begin();
337 fi != llvm_module.end();
338 ++fi)
339 {
340 Function *fun = fi;
341
342 bool is_decl = fun->isDeclaration();
343
344 if (log)
Sean Callananfecc09c2011-11-19 02:54:21 +0000345 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000346
347 if (!is_decl)
348 continue;
349
350 if (fun->hasNUses(0))
351 continue; // ignore
352
353 uint64_t addr = LLDB_INVALID_ADDRESS;
354 lldb_private::ConstString name;
355 Constant **value_ptr = NULL;
356
357 if (!GetFunctionAddress(fun,
358 addr,
359 name,
360 value_ptr))
361 return false; // GetFunctionAddress reports its own errors
362
363 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
364
Sean Callanan715f6b02011-10-31 22:11:40 +0000365 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
366
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000367 if (value_ptr)
368 *value_ptr = value;
369
370 fun->replaceAllUsesWith(value);
371 }
372
373 return true;
374}
375
Sean Callanan47dc4572011-09-15 02:13:07 +0000376
Sean Callanan696cf5f2011-05-07 01:06:41 +0000377clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000378IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000379{
380 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
381
Sean Callanan47dc4572011-09-15 02:13:07 +0000382 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000383
384 if (!named_metadata)
385 return NULL;
386
387 unsigned num_nodes = named_metadata->getNumOperands();
388 unsigned node_index;
389
390 for (node_index = 0;
391 node_index < num_nodes;
392 ++node_index)
393 {
394 MDNode *metadata_node = named_metadata->getOperand(node_index);
395
396 if (!metadata_node)
397 return NULL;
398
399 if (metadata_node->getNumOperands() != 2)
400 continue;
401
402 if (metadata_node->getOperand(0) != global_val)
403 continue;
404
405 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
406
407 if (!constant_int)
408 return NULL;
409
410 uintptr_t ptr = constant_int->getZExtValue();
411
412 return reinterpret_cast<clang::NamedDecl *>(ptr);
413 }
414
415 return NULL;
416}
417
Sean Callanan47dc4572011-09-15 02:13:07 +0000418clang::NamedDecl *
419IRForTarget::DeclForGlobal (GlobalValue *global_val)
420{
421 return DeclForGlobal(global_val, m_module);
422}
423
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000424void
425IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
426 const lldb_private::ConstString &name,
427 lldb_private::TypeFromParser type)
428{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000429 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
430 {
431 switch (init_expr->getOpcode())
432 {
433 default:
434 return;
435 case Instruction::IntToPtr:
436 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
437 return;
438 }
439 }
440 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
441 {
442 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
443 }
444}
445
446void
Sean Callananc0492742011-05-23 21:40:23 +0000447IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000448{
449 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
450
451 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000452 return;
453
Sean Callanan696cf5f2011-05-07 01:06:41 +0000454 LoadInst *original_load = NULL;
455
456 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
457 current_value != NULL;
458 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000459 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000460 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
461 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
462
463 if (cast_inst)
464 {
465 next_value = cast_inst->getOperand(0);
466 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000467 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000468 {
469 if (isa<LoadInst>(load_inst->getPointerOperand()))
470 {
471 next_value = load_inst->getPointerOperand();
472 }
473 else
474 {
475 original_load = load_inst;
476 break;
477 }
478 }
479 else
480 {
481 return;
482 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000483 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000484
485 Value *loaded_value = original_load->getPointerOperand();
486 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
487
488 if (!loaded_global)
489 return;
490
Sean Callananc0492742011-05-23 21:40:23 +0000491 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000492
493 if (!loaded_decl)
494 return;
495
496 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
497
498 if (!loaded_var)
499 return;
500
501 if (log)
502 {
503 lldb_private::StreamString type_desc_stream;
504 type.DumpTypeDescription(&type_desc_stream);
505
506 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
507 }
508
509 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000510}
511
512bool
Sean Callananc0492742011-05-23 21:40:23 +0000513IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000514{
Greg Claytone005f2c2010-11-06 01:53:30 +0000515 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000516
Sean Callanane8a59a82010-09-13 21:34:21 +0000517 if (!m_resolve_vars)
518 return true;
519
520 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000521
Sean Callananc0492742011-05-23 21:40:23 +0000522 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000523
Sean Callanan9b6898f2011-07-30 02:42:06 +0000524 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000525 const char *result_name = NULL;
526
527 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
528 vi != ve;
529 ++vi)
530 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000531 result_name_str = vi->first().str();
532 const char *value_name = result_name_str.c_str();
533
534 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
535 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000536 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000537 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000538 m_result_is_pointer = true;
539 break;
540 }
541
Sean Callanan9b6898f2011-07-30 02:42:06 +0000542 if (strstr(value_name, "$__lldb_expr_result") &&
543 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000544 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000545 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000546 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000547 break;
548 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000549 }
550
551 if (!result_name)
552 {
553 if (log)
554 log->PutCString("Couldn't find result variable");
555
556 return true;
557 }
558
Sean Callananc04743d2010-09-28 21:13:03 +0000559 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000560 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000561
Sean Callananc0492742011-05-23 21:40:23 +0000562 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000563
564 if (!result_value)
565 {
566 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000567 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000568
Sean Callanan97c924e2011-01-27 01:07:04 +0000569 if (m_error_stream)
570 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
571
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000572 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000573 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000574
Sean Callanan82b74c82010-08-12 01:56:52 +0000575 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000576 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000577
578 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
579
580 if (!result_global)
581 {
582 if (log)
583 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000584
585 if (m_error_stream)
586 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
587
Sean Callanan82b74c82010-08-12 01:56:52 +0000588 return false;
589 }
590
Sean Callananc0492742011-05-23 21:40:23 +0000591 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000592 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000593 {
594 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000595 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000596
Sean Callanan97c924e2011-01-27 01:07:04 +0000597 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000598 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 +0000599
Sean Callanan82b74c82010-08-12 01:56:52 +0000600 return false;
601 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000602
Sean Callanan696cf5f2011-05-07 01:06:41 +0000603 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000604 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000605 std::string decl_desc_str;
606 raw_string_ostream decl_desc_stream(decl_desc_str);
607 result_decl->print(decl_desc_stream);
608 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000609
Sean Callanan696cf5f2011-05-07 01:06:41 +0000610 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000611 }
612
Sean Callanan696cf5f2011-05-07 01:06:41 +0000613 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
614 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000615 {
616 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000617 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000618
619 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000620 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 +0000621
Sean Callanan82b74c82010-08-12 01:56:52 +0000622 return false;
623 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000624
Sean Callanan82b74c82010-08-12 01:56:52 +0000625 // Get the next available result name from m_decl_map and create the persistent
626 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000627
Sean Callanan696cf5f2011-05-07 01:06:41 +0000628 // If the result is an Lvalue, it is emitted as a pointer; see
629 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000630 if (m_result_is_pointer)
631 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000632 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000633 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan6a925532011-01-13 08:53:35 +0000634
Sean Callanan4fdf7952011-12-08 19:04:34 +0000635 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
636 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = dyn_cast<clang::ObjCObjectPointerType>(pointer_type);
637
638 if (pointer_pointertype)
639 {
640 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
641
642 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
643 &result_decl->getASTContext());
644 }
645 else if (pointer_objcobjpointertype)
646 {
647 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
648
649 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
650 &result_decl->getASTContext());
651 }
652 else
Sean Callanan6a925532011-01-13 08:53:35 +0000653 {
654 if (log)
655 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000656
657 if (m_error_stream)
658 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
659
Sean Callanan6a925532011-01-13 08:53:35 +0000660 return false;
661 }
Sean Callanan6a925532011-01-13 08:53:35 +0000662 }
663 else
664 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000665 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000666 &result_decl->getASTContext());
667 }
668
669 if (m_result_type.GetClangTypeBitWidth() == 0)
670 {
671 lldb_private::StreamString type_desc_stream;
672 m_result_type.DumpTypeDescription(&type_desc_stream);
673
674 if (log)
675 log->Printf("Result type has size 0");
676
677 if (m_error_stream)
678 m_error_stream->Printf("Internal error [IRForTarget]: Result type '%s' has invalid size\n",
679 type_desc_stream.GetData());
Sean Callanan6a925532011-01-13 08:53:35 +0000680 }
681
Sean Callanan696cf5f2011-05-07 01:06:41 +0000682 if (log)
683 {
684 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000685 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000686
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000687 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan696cf5f2011-05-07 01:06:41 +0000688 }
689
Sean Callanan6a925532011-01-13 08:53:35 +0000690 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000691
692 if (log)
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000693 log->Printf("Creating a new result global: \"%s\" with size 0x%x",
694 m_result_name.GetCString(),
695 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanan82b74c82010-08-12 01:56:52 +0000696
697 // Construct a new result global and set up its metadata
698
Sean Callananc0492742011-05-23 21:40:23 +0000699 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000700 result_global->getType()->getElementType(),
701 false, /* not constant */
702 GlobalValue::ExternalLinkage,
703 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000704 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000705
706 // It's too late in compilation to create a new VarDecl for this, but we don't
707 // need to. We point the metadata at the old VarDecl. This creates an odd
708 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000709 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000710 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
711 // fixed up.
712
Sean Callananc0492742011-05-23 21:40:23 +0000713 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000714 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000715 false);
716
717 llvm::Value* values[2];
718 values[0] = new_result_global;
719 values[1] = new_constant_int;
720
Sean Callanan0de254a2011-05-15 22:34:38 +0000721 ArrayRef<Value*> value_ref(values, 2);
722
Sean Callananc0492742011-05-23 21:40:23 +0000723 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
724 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000725 named_metadata->addOperand(persistent_global_md);
726
727 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000728 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000729 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000730 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000731
732 if (result_global->hasNUses(0))
733 {
734 // We need to synthesize a store for this variable, because otherwise
735 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000736
Greg Clayton8de27c72010-10-15 22:48:33 +0000737 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000738 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
739
740 if (!first_entry_instruction)
741 return false;
742
743 if (!result_global->hasInitializer())
744 {
745 if (log)
746 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000747
748 if (m_error_stream)
749 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
750
Sean Callanan2e2db532010-09-07 22:43:19 +0000751 return false;
752 }
753
754 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000755
756 // Here we write the initializer into a result variable assuming it
757 // can be computed statically.
758
759 if (!m_has_side_effects)
760 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000761 //MaybeSetConstantResult (initializer,
762 // m_result_name,
763 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000764 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000765
Greg Clayton2c344ca2011-02-05 02:28:58 +0000766 StoreInst *synthesized_store = new StoreInst(initializer,
767 new_result_global,
768 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000769
770 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000771 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000772 }
773 else
774 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000775 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000776 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000777 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000778 }
779
Sean Callanan2e2db532010-09-07 22:43:19 +0000780 result_global->replaceAllUsesWith(new_result_global);
781 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000782
783 if (!m_const_result)
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000784 if (!m_decl_map->AddPersistentVariable(result_decl,
785 m_result_name,
786 m_result_type,
787 true,
788 m_result_is_pointer))
789 return false;
Sean Callanan2e2db532010-09-07 22:43:19 +0000790
Sean Callanan82b74c82010-08-12 01:56:52 +0000791 result_global->eraseFromParent();
792
793 return true;
794}
795
Johnny Chen58021cc2011-08-09 23:10:20 +0000796#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000797static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000798{
799 if (!depth)
800 return;
801
802 depth--;
803
Johnny Chen58021cc2011-08-09 23:10:20 +0000804 if (log)
805 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000806
Greg Clayton3c7feb42010-11-19 01:05:25 +0000807 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000808 ui != ue;
809 ++ui)
810 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000811 if (log)
812 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000813 DebugUsers(log, *ui, depth);
814 }
815
Johnny Chen58021cc2011-08-09 23:10:20 +0000816 if (log)
817 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000818}
Johnny Chen58021cc2011-08-09 23:10:20 +0000819#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000820
821bool
Sean Callananc0492742011-05-23 21:40:23 +0000822IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000823 llvm::GlobalVariable *cstr,
824 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000825{
826 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
827
Sean Callanan9b6898f2011-07-30 02:42:06 +0000828 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000829
Sean Callanan9b6898f2011-07-30 02:42:06 +0000830 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
831 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000832 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000833 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
834 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000835
836 if (!m_CFStringCreateWithBytes)
837 {
838 lldb::addr_t CFStringCreateWithBytes_addr;
839
840 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
841
842 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
843 {
844 if (log)
845 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
846
Sean Callanan97c924e2011-01-27 01:07:04 +0000847 if (m_error_stream)
848 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
849
Sean Callanan6ba533e2010-11-17 23:00:36 +0000850 return false;
851 }
852
853 if (log)
854 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
855
856 // Build the function type:
857 //
858 // CFStringRef CFStringCreateWithBytes (
859 // CFAllocatorRef alloc,
860 // const UInt8 *bytes,
861 // CFIndex numBytes,
862 // CFStringEncoding encoding,
863 // Boolean isExternalRepresentation
864 // );
865 //
866 // We make the following substitutions:
867 //
868 // CFStringRef -> i8*
869 // CFAllocatorRef -> i8*
870 // UInt8 * -> i8*
871 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
872 // CFStringEncoding -> i32
873 // Boolean -> i8
874
Sean Callanan9b6898f2011-07-30 02:42:06 +0000875 Type *arg_type_array[5];
876
877 arg_type_array[0] = i8_ptr_ty;
878 arg_type_array[1] = i8_ptr_ty;
879 arg_type_array[2] = intptr_ty;
880 arg_type_array[3] = i32_ty;
881 arg_type_array[4] = i8_ty;
882
883 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
884
Sean Callananc0492742011-05-23 21:40:23 +0000885 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000886
887 // Build the constant containing the pointer to the function
888 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
889 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
890 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
891 }
892
Sean Callanan58baaad2011-07-08 00:39:14 +0000893 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000894
895 if (cstr)
896 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000897
Sean Callanan6ba533e2010-11-17 23:00:36 +0000898 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000899 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
900 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000901 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
902 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
903
Sean Callanan9b6898f2011-07-30 02:42:06 +0000904 Value *argument_array[5];
905
906 argument_array[0] = alloc_arg;
907 argument_array[1] = bytes_arg;
908 argument_array[2] = numBytes_arg;
909 argument_array[3] = encoding_arg;
910 argument_array[4] = isExternal_arg;
911
912 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000913
914 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000915 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000916 "CFStringCreateWithBytes",
917 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000918
Greg Clayton3c7feb42010-11-19 01:05:25 +0000919 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000920 {
921 if (log)
922 log->PutCString("Couldn't replace the NSString with the result of the call");
923
Sean Callanan97c924e2011-01-27 01:07:04 +0000924 if (m_error_stream)
925 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
926
Sean Callanan6ba533e2010-11-17 23:00:36 +0000927 return false;
928 }
929
Greg Clayton3c7feb42010-11-19 01:05:25 +0000930 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000931
932 return true;
933}
934
935bool
Sean Callananc0492742011-05-23 21:40:23 +0000936IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000937{
938 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
939
Sean Callananc0492742011-05-23 21:40:23 +0000940 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000941
Greg Clayton3c7feb42010-11-19 01:05:25 +0000942 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000943 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
944
945 if (!FirstEntryInstruction)
946 {
947 if (log)
948 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
949
Sean Callanan97c924e2011-01-27 01:07:04 +0000950 if (m_error_stream)
951 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
952
Sean Callanan6ba533e2010-11-17 23:00:36 +0000953 return false;
954 }
955
956 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
957 vi != ve;
958 ++vi)
959 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000960 std::string value_name = vi->first().str();
961 const char *value_name_cstr = value_name.c_str();
962
963 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000964 {
965 Value *nsstring_value = vi->second;
966
967 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
968
969 if (!nsstring_global)
970 {
971 if (log)
972 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000973
974 if (m_error_stream)
975 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
976
Sean Callanan6ba533e2010-11-17 23:00:36 +0000977 return false;
978 }
979
980 if (!nsstring_global->hasInitializer())
981 {
982 if (log)
983 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000984
985 if (m_error_stream)
986 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
987
Sean Callanan6ba533e2010-11-17 23:00:36 +0000988 return false;
989 }
990
991 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
992
993 if (!nsstring_struct)
994 {
995 if (log)
996 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000997
998 if (m_error_stream)
999 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
1000
Sean Callanan6ba533e2010-11-17 23:00:36 +00001001 return false;
1002 }
1003
1004 // We expect the following structure:
1005 //
1006 // struct {
1007 // int *isa;
1008 // int flags;
1009 // char *str;
1010 // long length;
1011 // };
1012
1013 if (nsstring_struct->getNumOperands() != 4)
1014 {
1015 if (log)
1016 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 +00001017
1018 if (m_error_stream)
1019 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
1020
Sean Callanan6ba533e2010-11-17 23:00:36 +00001021 return false;
1022 }
1023
1024 Constant *nsstring_member = nsstring_struct->getOperand(2);
1025
1026 if (!nsstring_member)
1027 {
1028 if (log)
1029 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +00001030
1031 if (m_error_stream)
1032 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1033
Sean Callanan6ba533e2010-11-17 23:00:36 +00001034 return false;
1035 }
1036
1037 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1038
1039 if (!nsstring_expr)
1040 {
1041 if (log)
1042 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +00001043
1044 if (m_error_stream)
1045 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1046
Sean Callanan6ba533e2010-11-17 23:00:36 +00001047 return false;
1048 }
1049
1050 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1051 {
1052 if (log)
1053 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 +00001054
1055 if (m_error_stream)
1056 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1057
Sean Callanan6ba533e2010-11-17 23:00:36 +00001058 return false;
1059 }
1060
1061 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1062
1063 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1064
1065 if (!cstr_global)
1066 {
1067 if (log)
1068 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001069
1070 if (m_error_stream)
1071 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 +00001072
Sean Callanan6ba533e2010-11-17 23:00:36 +00001073 return false;
1074 }
1075
1076 if (!cstr_global->hasInitializer())
1077 {
1078 if (log)
1079 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +00001080
1081 if (m_error_stream)
1082 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1083
Sean Callanan6ba533e2010-11-17 23:00:36 +00001084 return false;
1085 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001086
1087 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001088 if (!cstr_array)
1089 {
1090 if (log)
1091 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001092
1093 if (m_error_stream)
1094 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1095
Sean Callanan6ba533e2010-11-17 23:00:36 +00001096 return false;
1097 }
1098
1099 if (!cstr_array->isCString())
1100 {
1101 if (log)
1102 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +00001103
1104 if (m_error_stream)
1105 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1106
Sean Callanan6ba533e2010-11-17 23:00:36 +00001107 return false;
1108 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001109 */
1110
1111 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001112
1113 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001114 {
1115 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001116 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001117 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001118 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001119 }
1120
1121 if (!cstr_array)
1122 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001123
Sean Callananc0492742011-05-23 21:40:23 +00001124 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001125 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001126 if (log)
1127 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001128
1129 // We don't print an error message here because RewriteObjCConstString has done so for us.
1130
Sean Callanan6ba533e2010-11-17 23:00:36 +00001131 return false;
1132 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001133 }
1134 }
1135
1136 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1137 vi != ve;
1138 ++vi)
1139 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001140 std::string value_name = vi->first().str();
1141 const char *value_name_cstr = value_name.c_str();
1142
1143 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001144 {
1145 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1146
1147 if (!gv)
1148 {
1149 if (log)
1150 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001151
1152 if (m_error_stream)
1153 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1154
Sean Callanan6ba533e2010-11-17 23:00:36 +00001155 return false;
1156 }
1157
1158 gv->eraseFromParent();
1159
1160 break;
1161 }
1162 }
1163
1164 return true;
1165}
1166
Greg Clayton3c7feb42010-11-19 01:05:25 +00001167static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001168{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001169 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001170
Greg Clayton3c7feb42010-11-19 01:05:25 +00001171 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001172 return false;
1173
1174 return true;
1175}
1176
Sean Callanan97c924e2011-01-27 01:07:04 +00001177// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001178bool
Sean Callananc0492742011-05-23 21:40:23 +00001179IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001180{
Greg Claytone005f2c2010-11-06 01:53:30 +00001181 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001182
1183 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1184
1185 if (!load)
1186 return false;
1187
1188 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1189 //
1190 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1191 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1192 //
1193 // where %obj is the object pointer and %tmp is the selector.
1194 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001195 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1196 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001197
1198 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1199
1200 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1201
1202 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1203 return false;
1204
1205 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1206
1207 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1208
1209 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1210 return false;
1211
1212 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1213
1214 if (!osr_initializer_base)
1215 return false;
1216
1217 // Find the string's initializer (a ConstantArray) and get the string from it
1218
1219 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1220
1221 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1222 return false;
1223
1224 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1225
1226 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1227
1228 if (!omvn_initializer_array->isString())
1229 return false;
1230
1231 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1232
1233 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001234 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001235
1236 // Construct a call to sel_registerName
1237
1238 if (!m_sel_registerName)
1239 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001240 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001241
Greg Clayton8de27c72010-10-15 22:48:33 +00001242 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001243 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001244 return false;
1245
Sean Callananc2c6f772010-10-26 00:31:56 +00001246 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001247 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001248
Sean Callananf5857a02010-07-31 01:32:05 +00001249 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1250
1251 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001252 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001253 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001254 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001255
Sean Callanan9b6898f2011-07-30 02:42:06 +00001256 Type *type_array[1];
1257
1258 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1259
1260 ArrayRef<Type *> srN_arg_types(type_array, 1);
1261
Sean Callananf5857a02010-07-31 01:32:05 +00001262 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1263
1264 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001265 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1266 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001267 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001268 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001269 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1270 }
1271
Sean Callanan9b6898f2011-07-30 02:42:06 +00001272 Value *argument_array[1];
1273
Sean Callananc0492742011-05-23 21:40:23 +00001274 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001275
Sean Callanan9b6898f2011-07-30 02:42:06 +00001276 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001277
Sean Callanan9b6898f2011-07-30 02:42:06 +00001278 ArrayRef<Value *> srN_arguments(argument_array, 1);
1279
Sean Callananf5857a02010-07-31 01:32:05 +00001280 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001281 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001282 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001283 selector_load);
1284
1285 // Replace the load with the call in all users
1286
1287 selector_load->replaceAllUsesWith(srN_call);
1288
1289 selector_load->eraseFromParent();
1290
1291 return true;
1292}
1293
1294bool
Sean Callananc0492742011-05-23 21:40:23 +00001295IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001296{
Greg Claytone005f2c2010-11-06 01:53:30 +00001297 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001298
1299 BasicBlock::iterator ii;
1300
1301 typedef SmallVector <Instruction*, 2> InstrList;
1302 typedef InstrList::iterator InstrIterator;
1303
1304 InstrList selector_loads;
1305
Greg Clayton3c7feb42010-11-19 01:05:25 +00001306 for (ii = basic_block.begin();
1307 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001308 ++ii)
1309 {
1310 Instruction &inst = *ii;
1311
1312 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001313 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001314 selector_loads.push_back(&inst);
1315 }
1316
1317 InstrIterator iter;
1318
1319 for (iter = selector_loads.begin();
1320 iter != selector_loads.end();
1321 ++iter)
1322 {
Sean Callananc0492742011-05-23 21:40:23 +00001323 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001324 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001325 if (m_error_stream)
1326 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1327
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001328 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001329 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001330
Sean Callananf5857a02010-07-31 01:32:05 +00001331 return false;
1332 }
1333 }
1334
1335 return true;
1336}
1337
Sean Callanan97c924e2011-01-27 01:07:04 +00001338// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001339bool
Sean Callananc0492742011-05-23 21:40:23 +00001340IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001341{
Sean Callanan97678d12011-01-13 21:23:32 +00001342 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1343
Sean Callanana48fe162010-08-11 03:57:18 +00001344 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1345
1346 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1347
1348 if (!alloc_md || !alloc_md->getNumOperands())
1349 return false;
1350
1351 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1352
1353 if (!constant_int)
1354 return false;
1355
1356 // We attempt to register this as a new persistent variable with the DeclMap.
1357
1358 uintptr_t ptr = constant_int->getZExtValue();
1359
Sean Callanan82b74c82010-08-12 01:56:52 +00001360 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001361
Sean Callanan82b74c82010-08-12 01:56:52 +00001362 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1363 &decl->getASTContext());
1364
Greg Clayton8de27c72010-10-15 22:48:33 +00001365 StringRef decl_name (decl->getName());
1366 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001367 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001368 return false;
1369
Sean Callananc0492742011-05-23 21:40:23 +00001370 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001371 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001372 false, /* not constant */
1373 GlobalValue::ExternalLinkage,
1374 NULL, /* no initializer */
1375 alloc->getName().str().c_str());
1376
1377 // What we're going to do here is make believe this was a regular old external
1378 // variable. That means we need to make the metadata valid.
1379
Sean Callananc0492742011-05-23 21:40:23 +00001380 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001381
1382 llvm::Value* values[2];
1383 values[0] = persistent_global;
1384 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001385
1386 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001387
Sean Callananc0492742011-05-23 21:40:23 +00001388 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001389 named_metadata->addOperand(persistent_global_md);
1390
Sean Callanan97678d12011-01-13 21:23:32 +00001391 // Now, since the variable is a pointer variable, we will drop in a load of that
1392 // pointer variable.
1393
1394 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1395
1396 if (log)
1397 log->Printf("Replacing \"%s\" with \"%s\"",
1398 PrintValue(alloc).c_str(),
1399 PrintValue(persistent_load).c_str());
1400
1401 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001402 alloc->eraseFromParent();
1403
1404 return true;
1405}
1406
1407bool
Sean Callananc0492742011-05-23 21:40:23 +00001408IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001409{
Sean Callanane8a59a82010-09-13 21:34:21 +00001410 if (!m_resolve_vars)
1411 return true;
1412
Greg Claytone005f2c2010-11-06 01:53:30 +00001413 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001414
1415 BasicBlock::iterator ii;
1416
1417 typedef SmallVector <Instruction*, 2> InstrList;
1418 typedef InstrList::iterator InstrIterator;
1419
1420 InstrList pvar_allocs;
1421
Greg Clayton3c7feb42010-11-19 01:05:25 +00001422 for (ii = basic_block.begin();
1423 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001424 ++ii)
1425 {
1426 Instruction &inst = *ii;
1427
1428 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001429 {
1430 llvm::StringRef alloc_name = alloc->getName();
1431
1432 if (alloc_name.startswith("$") &&
1433 !alloc_name.startswith("$__lldb"))
1434 {
1435 if (alloc_name.find_first_of("0123456789") == 1)
1436 {
1437 if (log)
1438 log->Printf("Rejecting a numeric persistent variable.");
1439
Sean Callanan97c924e2011-01-27 01:07:04 +00001440 if (m_error_stream)
1441 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1442
Sean Callanan237e4742011-01-21 22:30:25 +00001443 return false;
1444 }
1445
Sean Callanana48fe162010-08-11 03:57:18 +00001446 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001447 }
1448 }
Sean Callanana48fe162010-08-11 03:57:18 +00001449 }
1450
1451 InstrIterator iter;
1452
1453 for (iter = pvar_allocs.begin();
1454 iter != pvar_allocs.end();
1455 ++iter)
1456 {
Sean Callananc0492742011-05-23 21:40:23 +00001457 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001458 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001459 if (m_error_stream)
1460 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1461
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001462 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001463 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001464
Sean Callanana48fe162010-08-11 03:57:18 +00001465 return false;
1466 }
1467 }
1468
1469 return true;
1470}
1471
Sean Callananc7ca4662011-10-25 18:36:40 +00001472bool
1473IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1474{
1475 if (!initializer)
1476 return true;
1477
1478 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1479
1480 if (log && log->GetVerbose())
1481 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1482
1483 Type *initializer_type = initializer->getType();
1484
1485 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1486 {
1487 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1488 return true;
1489 }
1490 else if (ConstantArray *array_initializer = dyn_cast<ConstantArray>(initializer))
1491 {
1492 if (array_initializer->isString())
1493 {
1494 std::string array_initializer_string = array_initializer->getAsString();
1495 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1496 }
1497 else
1498 {
1499 ArrayType *array_initializer_type = array_initializer->getType();
1500 Type *array_element_type = array_initializer_type->getElementType();
1501
1502 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1503
1504 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1505 {
1506 if (!MaterializeInitializer(data + (i * element_size), array_initializer->getOperand(i)))
1507 return false;
1508 }
1509 }
1510 return true;
1511 }
1512 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1513 {
1514 StructType *struct_initializer_type = struct_initializer->getType();
1515 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1516
1517 for (int i = 0;
1518 i < struct_initializer->getNumOperands();
1519 ++i)
1520 {
1521 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1522 return false;
1523 }
1524 return true;
1525 }
1526 return false;
1527}
1528
1529bool
1530IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1531{
1532 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1533 return false;
1534
Sean Callananc41606f2011-11-15 19:13:54 +00001535 if (global_variable == m_reloc_placeholder)
1536 return true;
1537
Sean Callananc7ca4662011-10-25 18:36:40 +00001538 uint64_t offset = m_data_allocator->GetStream().GetSize();
1539
1540 llvm::Type *variable_type = global_variable->getType();
1541
1542 Constant *initializer = global_variable->getInitializer();
1543
1544 llvm::Type *initializer_type = initializer->getType();
1545
1546 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1547
1548 lldb_private::DataBufferHeap data(size, '\0');
1549
1550 if (initializer)
1551 if (!MaterializeInitializer(data.GetBytes(), initializer))
1552 return false;
1553
1554 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1555
1556 Constant *new_pointer = BuildRelocation(variable_type, offset);
1557
1558 global_variable->replaceAllUsesWith(new_pointer);
1559
1560 global_variable->eraseFromParent();
1561
1562 return true;
1563}
1564
Sean Callanan97c924e2011-01-27 01:07:04 +00001565// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001566bool
Sean Callananc0492742011-05-23 21:40:23 +00001567IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001568{
Greg Claytone005f2c2010-11-06 01:53:30 +00001569 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001570
1571 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001572 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001573
Greg Clayton8de27c72010-10-15 22:48:33 +00001574 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001575 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001576 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001577 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001578 default:
1579 break;
1580 case Instruction::GetElementPtr:
1581 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001582 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001583 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001584 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001585 }
1586 }
Sean Callananf921cf52010-12-03 19:51:05 +00001587 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001588 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001589 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1590 return MaterializeInternalVariable(global_variable);
1591
Sean Callananc0492742011-05-23 21:40:23 +00001592 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001593
Sean Callananf5857a02010-07-31 01:32:05 +00001594 if (!named_decl)
1595 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001596 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001597 return true;
1598
Sean Callanan7cd46742010-12-06 00:56:39 +00001599 if (!global_variable->hasExternalLinkage())
1600 return true;
1601
Sean Callananf5857a02010-07-31 01:32:05 +00001602 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001603 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001604
Sean Callananf5857a02010-07-31 01:32:05 +00001605 return false;
1606 }
1607
Greg Clayton8de27c72010-10-15 22:48:33 +00001608 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001609
Sean Callanan771131d2010-09-30 21:18:25 +00001610 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001611 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001612
1613 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001614 {
Sean Callanan771131d2010-09-30 21:18:25 +00001615 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001616 ast_context = &value_decl->getASTContext();
1617 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001618 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001619 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001620 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001621 }
Sean Callanan771131d2010-09-30 21:18:25 +00001622
Sean Callanan6a925532011-01-13 08:53:35 +00001623 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001624 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001625
Sean Callanan97678d12011-01-13 21:23:32 +00001626 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001627 {
1628 // The $__lldb_expr_result name indicates the the return value has allocated as
1629 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1630 // accesses to this static variable need to be redirected to the result of dereferencing
1631 // a pointer that is passed in as one of the arguments.
1632 //
1633 // Consequently, when reporting the size of the type, we report a pointer type pointing
1634 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001635 //
1636 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001637
Sean Callanan6a925532011-01-13 08:53:35 +00001638 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1639 value_type = PointerType::get(global_variable->getType(), 0);
1640 }
1641 else
1642 {
1643 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1644 value_type = global_variable->getType();
1645 }
Sean Callanan771131d2010-09-30 21:18:25 +00001646
1647 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1648 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001649
Sean Callanan771131d2010-09-30 21:18:25 +00001650 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001651 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001652 name.c_str(),
1653 qual_type.getAsString().c_str(),
1654 PrintType(value_type).c_str(),
1655 value_size,
1656 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001657
Sean Callanan8bce6652010-07-13 21:41:46 +00001658
Sean Callanan8c127202010-08-23 23:09:38 +00001659 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001660 lldb_private::ConstString (name.c_str()),
1661 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001662 value_size,
1663 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001664 {
1665 if (!global_variable->hasExternalLinkage())
1666 return true;
1667 else
1668 return false;
1669 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001670 }
Sean Callananf3143b72010-12-03 03:02:31 +00001671 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001672 {
1673 if (log)
1674 log->Printf("Function pointers aren't handled right now");
1675
1676 return false;
1677 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001678
1679 return true;
1680}
1681
Sean Callanan97c924e2011-01-27 01:07:04 +00001682// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001683bool
Sean Callananc0492742011-05-23 21:40:23 +00001684IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001685{
Sean Callananc7674af2011-01-17 23:42:46 +00001686 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1687
1688 lldb_private::ConstString name(symbol->getName().str().c_str());
1689
Sean Callanan21ef5bb2011-12-01 02:04:16 +00001690 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc7674af2011-01-17 23:42:46 +00001691
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001692 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001693 {
1694 if (log)
1695 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1696
1697 return false;
1698 }
1699
1700 if (log)
1701 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1702
Sean Callanan9b6898f2011-07-30 02:42:06 +00001703 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001704
Sean Callanan9b6898f2011-07-30 02:42:06 +00001705 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1706 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001707
1708 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1709
1710 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1711
1712 if (log)
1713 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1714
1715 symbol->replaceAllUsesWith(symbol_addr_ptr);
1716
1717 return true;
1718}
1719
1720bool
Sean Callananc0492742011-05-23 21:40:23 +00001721IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001722{
Sean Callanan48443652010-12-02 19:47:57 +00001723 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1724
1725 if (log)
1726 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001727
Sean Callanan6ba533e2010-11-17 23:00:36 +00001728 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001729 op_index < num_ops;
1730 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001731 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001732 {
1733 if (m_error_stream)
1734 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1735
Sean Callanandc27aba2010-10-05 22:26:43 +00001736 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001737 }
1738
Sean Callanandc27aba2010-10-05 22:26:43 +00001739 return true;
1740}
1741
1742bool
Sean Callanan9911d2f2011-11-01 23:38:03 +00001743IRForTarget::HandleObjCClass(Value *classlist_reference)
1744{
1745 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1746
1747 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1748
1749 if (!global_variable)
1750 return false;
1751
1752 Constant *initializer = global_variable->getInitializer();
1753
1754 if (!initializer)
1755 return false;
1756
1757 if (!initializer->hasName())
1758 return false;
1759
1760 StringRef name(initializer->getName());
1761 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton16d21872011-12-03 20:02:42 +00001762 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callanan9911d2f2011-11-01 23:38:03 +00001763
1764 if (log)
1765 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1766
1767 if (class_ptr == LLDB_INVALID_ADDRESS)
1768 return false;
1769
1770 if (global_variable->use_begin() == global_variable->use_end())
1771 return false;
1772
1773 LoadInst *load_instruction = NULL;
1774
1775 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1776 i != e;
1777 ++i)
1778 {
1779 if ((load_instruction = dyn_cast<LoadInst>(*i)))
1780 break;
1781 }
1782
1783 if (!load_instruction)
1784 return false;
1785
1786 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1787 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1788
1789 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1790 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1791
1792 load_instruction->replaceAllUsesWith(class_bitcast);
1793
1794 load_instruction->eraseFromParent();
1795
1796 return true;
1797}
1798
1799bool
Sean Callananc0492742011-05-23 21:40:23 +00001800IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001801{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001802 /////////////////////////////////////////////////////////////////////////
1803 // Prepare the current basic block for execution in the remote process
1804 //
1805
Sean Callanan02fbafa2010-07-27 21:39:39 +00001806 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001807
Greg Clayton3c7feb42010-11-19 01:05:25 +00001808 for (ii = basic_block.begin();
1809 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001810 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001811 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001812 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001813
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001814 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001815
Sean Callanan97c924e2011-01-27 01:07:04 +00001816 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001817 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001818 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001819 }
1820
1821 return true;
1822}
1823
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001824bool
Sean Callananc0492742011-05-23 21:40:23 +00001825IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001826{
Sean Callananae71e302010-11-18 22:21:58 +00001827 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1828
Sean Callananc0492742011-05-23 21:40:23 +00001829 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001830 global != end;
1831 ++global)
1832 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001833 if (log)
1834 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1835 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001836 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001837
Sean Callanan9911d2f2011-11-01 23:38:03 +00001838 std::string global_name = (*global).getName().str();
1839
1840 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc7674af2011-01-17 23:42:46 +00001841 {
Sean Callananc0492742011-05-23 21:40:23 +00001842 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001843 {
1844 if (m_error_stream)
1845 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1846
Sean Callananc7674af2011-01-17 23:42:46 +00001847 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001848 }
Sean Callananc7674af2011-01-17 23:42:46 +00001849 }
Sean Callanan9911d2f2011-11-01 23:38:03 +00001850 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1851 {
1852 if (!HandleObjCClass(global))
1853 {
1854 if (m_error_stream)
1855 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1856
1857 return false;
1858 }
1859 }
Sean Callananc0492742011-05-23 21:40:23 +00001860 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001861 {
Sean Callananc0492742011-05-23 21:40:23 +00001862 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001863 {
1864 if (m_error_stream)
1865 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1866
Sean Callananc7674af2011-01-17 23:42:46 +00001867 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001868 }
Sean Callananc7674af2011-01-17 23:42:46 +00001869 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001870 }
1871
1872 return true;
1873}
1874
Sean Callananc0492742011-05-23 21:40:23 +00001875bool
1876IRForTarget::ReplaceStrings ()
1877{
1878 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1879
1880 if (!m_data_allocator)
1881 return true; // hope for the best; some clients may not want static allocation!
1882
1883 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1884
1885 OffsetsTy offsets;
1886
1887 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1888 gi != ge;
1889 ++gi)
1890 {
1891 GlobalVariable *gv = gi;
1892
1893 if (!gv->hasInitializer())
1894 continue;
1895
1896 Constant *gc = gv->getInitializer();
1897
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001898 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001899
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001900 if (gc->isNullValue())
1901 {
1902 Type *gc_type = gc->getType();
1903
1904 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1905
1906 if (!gc_array_type)
1907 continue;
1908
1909 Type *gc_element_type = gc_array_type->getElementType();
1910
1911 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1912
1913 if (gc_integer_type->getBitWidth() != 8)
1914 continue;
1915
1916 str = "";
1917 }
1918 else
1919 {
1920 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1921
1922 if (!gc_array)
1923 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001924
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001925 if (!gc_array->isCString())
1926 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001927
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001928 if (log)
1929 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001930
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001931 str = gc_array->getAsString();
1932 }
1933
Sean Callananc0492742011-05-23 21:40:23 +00001934 offsets[gv] = m_data_allocator->GetStream().GetSize();
1935
1936 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1937 }
1938
Sean Callanan9b6898f2011-07-30 02:42:06 +00001939 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001940
1941 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1942 oi != oe;
1943 ++oi)
1944 {
1945 GlobalVariable *gv = oi->first;
1946 size_t offset = oi->second;
1947
1948 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1949
1950 if (log)
1951 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1952
1953 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1954 ui != ue;
1955 ++ui)
1956 {
1957 if (log)
1958 log->Printf("Found use %s", PrintValue(*ui).c_str());
1959
1960 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1961 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1962
1963 if (const_expr)
1964 {
1965 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1966 {
1967 if (log)
1968 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1969
1970 return false;
1971 }
1972
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001973 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1974 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1975
1976 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001977 }
1978 else if (store_inst)
1979 {
1980 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1981
1982 store_inst->setOperand(0, bit_cast);
1983 }
1984 else
1985 {
1986 if (log)
1987 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1988
1989 return false;
1990 }
1991 }
1992
1993 gv->eraseFromParent();
1994 }
1995
1996 return true;
1997}
1998
1999bool
2000IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
2001{
2002 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2003
2004 if (!m_data_allocator)
2005 return true;
2006
2007 typedef SmallVector <Value*, 2> ConstantList;
2008 typedef SmallVector <llvm::Instruction*, 2> UserList;
2009 typedef ConstantList::iterator ConstantIterator;
2010 typedef UserList::iterator UserIterator;
2011
2012 ConstantList static_constants;
2013 UserList static_users;
2014
2015 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2016 ii != ie;
2017 ++ii)
2018 {
2019 llvm::Instruction &inst = *ii;
2020
2021 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2022 oi != oe;
2023 ++oi)
2024 {
2025 Value *operand_val = oi->get();
2026
2027 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2028
2029 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
2030 {
2031 static_constants.push_back(operand_val);
2032 static_users.push_back(ii);
2033 }
2034 }
2035 }
2036
2037 ConstantIterator constant_iter;
2038 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00002039
Sean Callananc0492742011-05-23 21:40:23 +00002040 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2041 constant_iter != static_constants.end();
2042 ++constant_iter, ++user_iter)
2043 {
2044 Value *operand_val = *constant_iter;
2045 llvm::Instruction *inst = *user_iter;
2046
2047 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2048
2049 if (operand_constant_fp)
2050 {
2051 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2052 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2053
2054 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2055 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2056
2057 if (log)
2058 {
2059 std::string s;
2060 raw_string_ostream ss(s);
2061 for (size_t index = 0;
2062 index < operand_data_size;
2063 ++index)
2064 {
2065 ss << (uint32_t)operand_raw_data[index];
2066 ss << " ";
2067 }
2068 ss.flush();
2069
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002070 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00002071 }
2072
2073 lldb_private::DataBufferHeap data(operand_data_size, 0);
2074
2075 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
2076 {
2077 uint8_t *data_bytes = data.GetBytes();
2078
2079 for (size_t index = 0;
2080 index < operand_data_size;
2081 ++index)
2082 {
2083 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2084 }
2085 }
2086 else
2087 {
2088 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2089 }
2090
2091 uint64_t offset = m_data_allocator->GetStream().GetSize();
2092
2093 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
2094
Sean Callanan9b6898f2011-07-30 02:42:06 +00002095 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00002096
2097 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2098
2099 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2100
2101 operand_constant_fp->replaceAllUsesWith(fp_load);
2102 }
2103 }
2104
2105 return true;
2106}
2107
Sean Callanan02fbafa2010-07-27 21:39:39 +00002108static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00002109{
Sean Callanan58baaad2011-07-08 00:39:14 +00002110 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00002111
Sean Callanan6ba533e2010-11-17 23:00:36 +00002112 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00002113 return false;
2114
Sean Callanan58baaad2011-07-08 00:39:14 +00002115 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002116
2117 if ((CE = dyn_cast<ConstantExpr>(V)))
2118 {
2119 if (CE->getOpcode() != Instruction::BitCast)
2120 return false;
2121
Sean Callanan6ba533e2010-11-17 23:00:36 +00002122 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002123 }
2124
Sean Callanan6ba533e2010-11-17 23:00:36 +00002125 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00002126
2127 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2128 return false;
2129
2130 return true;
2131}
2132
Sean Callananc0492742011-05-23 21:40:23 +00002133void
2134IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00002135{
Sean Callananc0492742011-05-23 21:40:23 +00002136 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002137
2138 Value::use_iterator ui;
2139
2140 for (ui = guard_load->use_begin();
2141 ui != guard_load->use_end();
2142 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002143 {
Greg Clayton6e713402010-07-30 20:30:44 +00002144 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002145 {
2146 // do nothing for the moment
2147 }
2148 else
2149 {
2150 ui->replaceUsesOfWith(guard_load, zero);
2151 }
2152 }
Sean Callanan45839272010-07-24 01:37:44 +00002153
2154 guard_load->eraseFromParent();
2155}
2156
2157static void ExciseGuardStore(Instruction* guard_store)
2158{
2159 guard_store->eraseFromParent();
2160}
2161
2162bool
Sean Callananc0492742011-05-23 21:40:23 +00002163IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002164{
2165 ///////////////////////////////////////////////////////
2166 // Eliminate any reference to guard variables found.
2167 //
2168
Sean Callanan02fbafa2010-07-27 21:39:39 +00002169 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002170
Sean Callanan02fbafa2010-07-27 21:39:39 +00002171 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002172 typedef InstrList::iterator InstrIterator;
2173
2174 InstrList guard_loads;
2175 InstrList guard_stores;
2176
Greg Clayton3c7feb42010-11-19 01:05:25 +00002177 for (ii = basic_block.begin();
2178 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002179 ++ii)
2180 {
2181 Instruction &inst = *ii;
2182
2183 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2184 if (isGuardVariableRef(load->getPointerOperand()))
2185 guard_loads.push_back(&inst);
2186
2187 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2188 if (isGuardVariableRef(store->getPointerOperand()))
2189 guard_stores.push_back(&inst);
2190 }
2191
2192 InstrIterator iter;
2193
2194 for (iter = guard_loads.begin();
2195 iter != guard_loads.end();
2196 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002197 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002198
2199 for (iter = guard_stores.begin();
2200 iter != guard_stores.end();
2201 ++iter)
2202 ExciseGuardStore(*iter);
2203
2204 return true;
2205}
2206
Sean Callanan97c924e2011-01-27 01:07:04 +00002207// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002208bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002209IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002210{
Greg Claytone005f2c2010-11-06 01:53:30 +00002211 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002212
2213 Value::use_iterator ui;
2214
Sean Callanana48fe162010-08-11 03:57:18 +00002215 SmallVector<User*, 16> users;
2216
2217 // We do this because the use list might change, invalidating our iterator.
2218 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002219 for (ui = old_constant->use_begin();
2220 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002221 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002222 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002223
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002224 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002225 i < users.size();
2226 ++i)
2227 {
2228 User *user = users[i];
2229
Sean Callananbafd6852010-07-14 23:40:29 +00002230 if (Constant *constant = dyn_cast<Constant>(user))
2231 {
2232 // synthesize a new non-constant equivalent of the constant
2233
2234 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2235 {
2236 switch (constant_expr->getOpcode())
2237 {
2238 default:
2239 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002240 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002241 return false;
2242 case Instruction::BitCast:
2243 {
2244 // UnaryExpr
2245 // OperandList[0] is value
2246
2247 Value *s = constant_expr->getOperand(0);
2248
Greg Clayton3c7feb42010-11-19 01:05:25 +00002249 if (s == old_constant)
2250 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002251
Sean Callananc0492742011-05-23 21:40:23 +00002252 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002253
Greg Clayton3c7feb42010-11-19 01:05:25 +00002254 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002255 }
2256 break;
2257 case Instruction::GetElementPtr:
2258 {
2259 // GetElementPtrConstantExpr
2260 // OperandList[0] is base
2261 // OperandList[1]... are indices
2262
2263 Value *ptr = constant_expr->getOperand(0);
2264
Greg Clayton3c7feb42010-11-19 01:05:25 +00002265 if (ptr == old_constant)
2266 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002267
2268 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002269
2270 unsigned operand_index;
2271 unsigned num_operands = constant_expr->getNumOperands();
2272
2273 for (operand_index = 1;
2274 operand_index < num_operands;
2275 ++operand_index)
2276 {
2277 Value *operand = constant_expr->getOperand(operand_index);
2278
Greg Clayton3c7feb42010-11-19 01:05:25 +00002279 if (operand == old_constant)
2280 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002281
Sean Callanan9b6898f2011-07-30 02:42:06 +00002282 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002283 }
2284
Sean Callanan9b6898f2011-07-30 02:42:06 +00002285 ArrayRef <Value*> indices(index_vector);
2286
2287 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002288
Greg Clayton3c7feb42010-11-19 01:05:25 +00002289 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002290 }
2291 break;
2292 }
2293 }
2294 else
2295 {
2296 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002297 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002298 return false;
2299 }
2300 }
2301 else
2302 {
2303 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002304 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002305 }
2306 }
2307
2308 return true;
2309}
2310
Sean Callanan8bce6652010-07-13 21:41:46 +00002311bool
Sean Callananc0492742011-05-23 21:40:23 +00002312IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002313{
Sean Callanane8a59a82010-09-13 21:34:21 +00002314 if (!m_resolve_vars)
2315 return true;
2316
Greg Claytone005f2c2010-11-06 01:53:30 +00002317 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002318
2319 m_decl_map->DoStructLayout();
2320
2321 if (log)
2322 log->Printf("Element arrangement:");
2323
2324 uint32_t num_elements;
2325 uint32_t element_index;
2326
2327 size_t size;
2328 off_t alignment;
2329
2330 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2331 return false;
2332
Greg Clayton3c7feb42010-11-19 01:05:25 +00002333 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002334
Greg Clayton3c7feb42010-11-19 01:05:25 +00002335 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002336 {
2337 if (m_error_stream)
2338 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2339
Sean Callanan8bce6652010-07-13 21:41:46 +00002340 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002341 }
2342
Sean Callanan02fbafa2010-07-27 21:39:39 +00002343 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002344
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002345 if (argument->getName().equals("this"))
2346 {
2347 ++iter;
2348
Greg Clayton3c7feb42010-11-19 01:05:25 +00002349 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002350 {
2351 if (m_error_stream)
2352 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2353
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002354 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002355 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002356
2357 argument = iter;
2358 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002359 else if (argument->getName().equals("self"))
2360 {
2361 ++iter;
2362
2363 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002364 {
2365 if (m_error_stream)
2366 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2367
Sean Callanan3aa7da52010-12-13 22:46:15 +00002368 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002369 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002370
2371 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002372 {
2373 if (m_error_stream)
2374 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2375
Sean Callanan3aa7da52010-12-13 22:46:15 +00002376 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002377 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002378
2379 ++iter;
2380
2381 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002382 {
2383 if (m_error_stream)
2384 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2385
Sean Callanan3aa7da52010-12-13 22:46:15 +00002386 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002387 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002388
2389 argument = iter;
2390 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002391
Greg Clayton8de27c72010-10-15 22:48:33 +00002392 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002393 {
2394 if (m_error_stream)
2395 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2396
Sean Callanan8bce6652010-07-13 21:41:46 +00002397 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002398 }
2399
Sean Callanan8bce6652010-07-13 21:41:46 +00002400 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002401 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002402
Greg Clayton3c7feb42010-11-19 01:05:25 +00002403 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002404 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002405
Sean Callanan6ba533e2010-11-17 23:00:36 +00002406 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002407 {
2408 if (m_error_stream)
2409 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2410
Sean Callanan8bce6652010-07-13 21:41:46 +00002411 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002412 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002413
Sean Callananc0492742011-05-23 21:40:23 +00002414 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002415 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002416
2417 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002418 {
2419 if (m_error_stream)
2420 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2421
Sean Callanan8bce6652010-07-13 21:41:46 +00002422 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002423 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002424
2425 for (element_index = 0; element_index < num_elements; ++element_index)
2426 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002427 const clang::NamedDecl *decl = NULL;
2428 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002429 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002430 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002431
Sean Callanan45690fe2010-08-30 22:17:16 +00002432 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002433 {
2434 if (m_error_stream)
2435 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2436
Sean Callanan8bce6652010-07-13 21:41:46 +00002437 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002438 }
2439
Sean Callanan8bce6652010-07-13 21:41:46 +00002440 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002441 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002442 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002443 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002444 offset);
2445
Sean Callanan9b6898f2011-07-30 02:42:06 +00002446 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002447 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002448
Sean Callananc7ca4662011-10-25 18:36:40 +00002449 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002450 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002451 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002452
Sean Callananc7ca4662011-10-25 18:36:40 +00002453 if (log)
2454 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002455
Sean Callananc7ca4662011-10-25 18:36:40 +00002456 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2457 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2458 // entry in order to produce the static variable that the AST thinks it is accessing.
2459 if (name == m_result_name && !m_result_is_pointer)
2460 {
2461 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2462
2463 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2464
2465 replacement = load;
2466 }
2467 else
2468 {
2469 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2470
2471 replacement = bit_cast;
2472 }
2473
2474 if (Constant *constant = dyn_cast<Constant>(value))
2475 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2476 else
2477 value->replaceAllUsesWith(replacement);
2478
2479 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2480 var->eraseFromParent();
2481 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002482 }
2483
2484 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002485 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002486
2487 return true;
2488}
2489
Sean Callananc0492742011-05-23 21:40:23 +00002490llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002491IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002492 uint64_t offset)
2493{
2494 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2495
Sean Callanan9b6898f2011-07-30 02:42:06 +00002496 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2497 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002498
2499 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002500
2501 llvm::Constant *offset_array[1];
2502
2503 offset_array[0] = offset_int;
2504
2505 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2506
2507 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002508 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2509
2510 return reloc_getbitcast;
2511}
2512
2513bool
2514IRForTarget::CompleteDataAllocation ()
2515{
Sean Callanan47dc4572011-09-15 02:13:07 +00002516 if (!m_data_allocator)
2517 return true;
2518
Sean Callananc0492742011-05-23 21:40:23 +00002519 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2520
2521 if (!m_data_allocator->GetStream().GetSize())
2522 return true;
2523
2524 lldb::addr_t allocation = m_data_allocator->Allocate();
2525
2526 if (log)
2527 {
2528 if (allocation)
2529 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2530 else
2531 log->Printf("Failed to allocate static data");
2532 }
2533
2534 if (!allocation)
2535 return false;
2536
Sean Callanan9b6898f2011-07-30 02:42:06 +00002537 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2538 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002539
2540 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2541 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2542
2543 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2544
2545 m_reloc_placeholder->eraseFromParent();
2546
2547 return true;
2548}
2549
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002550bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002551IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002552{
Greg Claytone005f2c2010-11-06 01:53:30 +00002553 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002554
Sean Callananc0492742011-05-23 21:40:23 +00002555 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002556 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002557
2558 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002559
2560 if (!function)
2561 {
2562 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002563 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002564
2565 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002566 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 +00002567
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002568 return false;
2569 }
Sean Callananc0492742011-05-23 21:40:23 +00002570
2571 if (!FixFunctionLinkage (*function))
2572 {
2573 if (log)
2574 log->Printf("Couldn't fix the linkage for the function");
2575
2576 return false;
2577 }
2578
Sean Callananc7ca4662011-10-25 18:36:40 +00002579 if (log)
2580 {
2581 std::string s;
2582 raw_string_ostream oss(s);
2583
2584 m_module->print(oss, NULL);
2585
2586 oss.flush();
2587
2588 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2589 }
2590
Sean Callanan9b6898f2011-07-30 02:42:06 +00002591 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002592
2593 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2594 intptr_ty,
2595 false /* isConstant */,
2596 GlobalVariable::InternalLinkage,
2597 Constant::getNullValue(intptr_ty),
2598 "reloc_placeholder",
2599 NULL /* InsertBefore */,
2600 false /* ThreadLocal */,
2601 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002602
Sean Callanan02fbafa2010-07-27 21:39:39 +00002603 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002604
Sean Callananc0492742011-05-23 21:40:23 +00002605 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002606
Sean Callanan82b74c82010-08-12 01:56:52 +00002607 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002608 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002609 //
2610
Sean Callananc0492742011-05-23 21:40:23 +00002611 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002612 {
2613 if (log)
2614 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002615
2616 // CreateResultVariable() reports its own errors, so we don't do so here
2617
Sean Callanan82b74c82010-08-12 01:56:52 +00002618 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002619 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002620
2621 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2622 {
2623 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002624 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002625 }
2626
2627 for (bbi = function->begin();
2628 bbi != function->end();
2629 ++bbi)
2630 {
2631 if (!RemoveGuards(*bbi))
2632 {
2633 if (log)
2634 log->Printf("RemoveGuards() failed");
2635
2636 // RemoveGuards() reports its own errors, so we don't do so here
2637
2638 return false;
2639 }
2640
2641 if (!RewritePersistentAllocs(*bbi))
2642 {
2643 if (log)
2644 log->Printf("RewritePersistentAllocs() failed");
2645
2646 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2647
2648 return false;
2649 }
2650 }
2651
2652 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2653 {
2654 IRInterpreter interpreter (*m_decl_map,
2655 m_error_stream);
2656
2657 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2658 {
2659 m_interpret_success = true;
2660 return true;
2661 }
2662 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002663
Sean Callanan7b8eb762011-11-01 17:33:54 +00002664 if (log && log->GetVerbose())
Sean Callananc0492742011-05-23 21:40:23 +00002665 {
2666 std::string s;
2667 raw_string_ostream oss(s);
2668
2669 m_module->print(oss, NULL);
2670
2671 oss.flush();
2672
2673 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2674 }
2675
Sean Callanan6ba533e2010-11-17 23:00:36 +00002676 ///////////////////////////////////////////////////////////////////////////////
2677 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2678 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002679
Sean Callananc0492742011-05-23 21:40:23 +00002680 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002681 {
2682 if (log)
2683 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002684
2685 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2686
Sean Callanan6ba533e2010-11-17 23:00:36 +00002687 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002688 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002689
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002690 ///////////////////////////////
2691 // Resolve function pointers
2692 //
2693
2694 if (!ResolveFunctionPointers(llvm_module, *function))
2695 {
2696 if (log)
2697 log->Printf("ResolveFunctionPointers() failed");
2698
2699 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2700
2701 return false;
2702 }
2703
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002704 for (bbi = function->begin();
2705 bbi != function->end();
2706 ++bbi)
2707 {
Sean Callananc0492742011-05-23 21:40:23 +00002708 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002709 {
2710 if (log)
2711 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002712
2713 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2714
Sean Callanana48fe162010-08-11 03:57:18 +00002715 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002716 }
Sean Callanana48fe162010-08-11 03:57:18 +00002717
Sean Callananc0492742011-05-23 21:40:23 +00002718 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002719 {
2720 if (log)
2721 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002722
2723 // ResolveCalls() reports its own errors, so we don't do so here
2724
Sean Callanan8bce6652010-07-13 21:41:46 +00002725 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002726 }
Sean Callananc0492742011-05-23 21:40:23 +00002727
2728 if (!ReplaceStaticLiterals(*bbi))
2729 {
2730 if (log)
2731 log->Printf("ReplaceStaticLiterals() failed");
2732
2733 return false;
2734 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002735 }
2736
Sean Callanan771131d2010-09-30 21:18:25 +00002737 ///////////////////////////////
2738 // Run function-level passes
2739 //
2740
Sean Callananc0492742011-05-23 21:40:23 +00002741 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002742 {
2743 if (log)
2744 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002745
2746 // ResolveExternals() reports its own errors, so we don't do so here
2747
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002748 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002749 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002750
Sean Callananc0492742011-05-23 21:40:23 +00002751 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002752 {
2753 if (log)
2754 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002755
2756 // ReplaceVariables() reports its own errors, so we don't do so here
2757
Sean Callanan771131d2010-09-30 21:18:25 +00002758 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002759 }
Sean Callanan771131d2010-09-30 21:18:25 +00002760
Sean Callananc0492742011-05-23 21:40:23 +00002761 if (!ReplaceStrings())
2762 {
2763 if (log)
2764 log->Printf("ReplaceStrings() failed");
2765
2766 return false;
2767 }
2768
2769 if (!CompleteDataAllocation())
2770 {
2771 if (log)
2772 log->Printf("CompleteDataAllocation() failed");
2773
2774 return false;
2775 }
2776
Sean Callanan7b8eb762011-11-01 17:33:54 +00002777 if (log && log->GetVerbose())
Sean Callanan8bce6652010-07-13 21:41:46 +00002778 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002779 std::string s;
2780 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002781
Sean Callananc0492742011-05-23 21:40:23 +00002782 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002783
2784 oss.flush();
2785
Greg Claytonb5037af2010-11-15 01:47:11 +00002786 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002787 }
2788
2789 return true;
2790}
2791
2792void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002793IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002794{
2795}
2796
2797PassManagerType
2798IRForTarget::getPotentialPassManagerType() const
2799{
2800 return PMT_ModulePassManager;
2801}