blob: 4cf8d792f7228186aab9b0d1f96d7d5be0ccd905 [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();
634 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000635
636 if (!pointer_pointertype)
637 {
638 if (log)
639 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000640
641 if (m_error_stream)
642 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
643
Sean Callanan6a925532011-01-13 08:53:35 +0000644 return false;
645 }
646
647 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
648
Sean Callanan47dc4572011-09-15 02:13:07 +0000649 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000650 &result_decl->getASTContext());
Sean Callanan6a925532011-01-13 08:53:35 +0000651 }
652 else
653 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000654 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000655 &result_decl->getASTContext());
656 }
657
658 if (m_result_type.GetClangTypeBitWidth() == 0)
659 {
660 lldb_private::StreamString type_desc_stream;
661 m_result_type.DumpTypeDescription(&type_desc_stream);
662
663 if (log)
664 log->Printf("Result type has size 0");
665
666 if (m_error_stream)
667 m_error_stream->Printf("Internal error [IRForTarget]: Result type '%s' has invalid size\n",
668 type_desc_stream.GetData());
Sean Callanan6a925532011-01-13 08:53:35 +0000669 }
670
Sean Callanan696cf5f2011-05-07 01:06:41 +0000671 if (log)
672 {
673 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000674 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000675
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000676 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan696cf5f2011-05-07 01:06:41 +0000677 }
678
Sean Callanan6a925532011-01-13 08:53:35 +0000679 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000680
681 if (log)
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000682 log->Printf("Creating a new result global: \"%s\" with size 0x%x",
683 m_result_name.GetCString(),
684 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanan82b74c82010-08-12 01:56:52 +0000685
686 // Construct a new result global and set up its metadata
687
Sean Callananc0492742011-05-23 21:40:23 +0000688 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000689 result_global->getType()->getElementType(),
690 false, /* not constant */
691 GlobalValue::ExternalLinkage,
692 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000693 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000694
695 // It's too late in compilation to create a new VarDecl for this, but we don't
696 // need to. We point the metadata at the old VarDecl. This creates an odd
697 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000698 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000699 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
700 // fixed up.
701
Sean Callananc0492742011-05-23 21:40:23 +0000702 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000703 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000704 false);
705
706 llvm::Value* values[2];
707 values[0] = new_result_global;
708 values[1] = new_constant_int;
709
Sean Callanan0de254a2011-05-15 22:34:38 +0000710 ArrayRef<Value*> value_ref(values, 2);
711
Sean Callananc0492742011-05-23 21:40:23 +0000712 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
713 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000714 named_metadata->addOperand(persistent_global_md);
715
716 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000717 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000718 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000719 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000720
721 if (result_global->hasNUses(0))
722 {
723 // We need to synthesize a store for this variable, because otherwise
724 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000725
Greg Clayton8de27c72010-10-15 22:48:33 +0000726 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000727 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
728
729 if (!first_entry_instruction)
730 return false;
731
732 if (!result_global->hasInitializer())
733 {
734 if (log)
735 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000736
737 if (m_error_stream)
738 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
739
Sean Callanan2e2db532010-09-07 22:43:19 +0000740 return false;
741 }
742
743 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000744
745 // Here we write the initializer into a result variable assuming it
746 // can be computed statically.
747
748 if (!m_has_side_effects)
749 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000750 //MaybeSetConstantResult (initializer,
751 // m_result_name,
752 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000753 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000754
Greg Clayton2c344ca2011-02-05 02:28:58 +0000755 StoreInst *synthesized_store = new StoreInst(initializer,
756 new_result_global,
757 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000758
759 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000760 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000761 }
762 else
763 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000764 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000765 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000766 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000767 }
768
Sean Callanan2e2db532010-09-07 22:43:19 +0000769 result_global->replaceAllUsesWith(new_result_global);
770 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000771
772 if (!m_const_result)
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000773 if (!m_decl_map->AddPersistentVariable(result_decl,
774 m_result_name,
775 m_result_type,
776 true,
777 m_result_is_pointer))
778 return false;
Sean Callanan2e2db532010-09-07 22:43:19 +0000779
Sean Callanan82b74c82010-08-12 01:56:52 +0000780 result_global->eraseFromParent();
781
782 return true;
783}
784
Johnny Chen58021cc2011-08-09 23:10:20 +0000785#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000786static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000787{
788 if (!depth)
789 return;
790
791 depth--;
792
Johnny Chen58021cc2011-08-09 23:10:20 +0000793 if (log)
794 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000795
Greg Clayton3c7feb42010-11-19 01:05:25 +0000796 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000797 ui != ue;
798 ++ui)
799 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000800 if (log)
801 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000802 DebugUsers(log, *ui, depth);
803 }
804
Johnny Chen58021cc2011-08-09 23:10:20 +0000805 if (log)
806 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000807}
Johnny Chen58021cc2011-08-09 23:10:20 +0000808#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000809
810bool
Sean Callananc0492742011-05-23 21:40:23 +0000811IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000812 llvm::GlobalVariable *cstr,
813 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000814{
815 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
816
Sean Callanan9b6898f2011-07-30 02:42:06 +0000817 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000818
Sean Callanan9b6898f2011-07-30 02:42:06 +0000819 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
820 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000821 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000822 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
823 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000824
825 if (!m_CFStringCreateWithBytes)
826 {
827 lldb::addr_t CFStringCreateWithBytes_addr;
828
829 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
830
831 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
832 {
833 if (log)
834 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
835
Sean Callanan97c924e2011-01-27 01:07:04 +0000836 if (m_error_stream)
837 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
838
Sean Callanan6ba533e2010-11-17 23:00:36 +0000839 return false;
840 }
841
842 if (log)
843 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
844
845 // Build the function type:
846 //
847 // CFStringRef CFStringCreateWithBytes (
848 // CFAllocatorRef alloc,
849 // const UInt8 *bytes,
850 // CFIndex numBytes,
851 // CFStringEncoding encoding,
852 // Boolean isExternalRepresentation
853 // );
854 //
855 // We make the following substitutions:
856 //
857 // CFStringRef -> i8*
858 // CFAllocatorRef -> i8*
859 // UInt8 * -> i8*
860 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
861 // CFStringEncoding -> i32
862 // Boolean -> i8
863
Sean Callanan9b6898f2011-07-30 02:42:06 +0000864 Type *arg_type_array[5];
865
866 arg_type_array[0] = i8_ptr_ty;
867 arg_type_array[1] = i8_ptr_ty;
868 arg_type_array[2] = intptr_ty;
869 arg_type_array[3] = i32_ty;
870 arg_type_array[4] = i8_ty;
871
872 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
873
Sean Callananc0492742011-05-23 21:40:23 +0000874 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000875
876 // Build the constant containing the pointer to the function
877 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
878 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
879 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
880 }
881
Sean Callanan58baaad2011-07-08 00:39:14 +0000882 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000883
884 if (cstr)
885 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000886
Sean Callanan6ba533e2010-11-17 23:00:36 +0000887 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000888 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
889 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000890 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
891 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
892
Sean Callanan9b6898f2011-07-30 02:42:06 +0000893 Value *argument_array[5];
894
895 argument_array[0] = alloc_arg;
896 argument_array[1] = bytes_arg;
897 argument_array[2] = numBytes_arg;
898 argument_array[3] = encoding_arg;
899 argument_array[4] = isExternal_arg;
900
901 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000902
903 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000904 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000905 "CFStringCreateWithBytes",
906 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000907
Greg Clayton3c7feb42010-11-19 01:05:25 +0000908 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000909 {
910 if (log)
911 log->PutCString("Couldn't replace the NSString with the result of the call");
912
Sean Callanan97c924e2011-01-27 01:07:04 +0000913 if (m_error_stream)
914 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
915
Sean Callanan6ba533e2010-11-17 23:00:36 +0000916 return false;
917 }
918
Greg Clayton3c7feb42010-11-19 01:05:25 +0000919 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000920
921 return true;
922}
923
924bool
Sean Callananc0492742011-05-23 21:40:23 +0000925IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000926{
927 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
928
Sean Callananc0492742011-05-23 21:40:23 +0000929 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000930
Greg Clayton3c7feb42010-11-19 01:05:25 +0000931 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000932 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
933
934 if (!FirstEntryInstruction)
935 {
936 if (log)
937 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
938
Sean Callanan97c924e2011-01-27 01:07:04 +0000939 if (m_error_stream)
940 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
941
Sean Callanan6ba533e2010-11-17 23:00:36 +0000942 return false;
943 }
944
945 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
946 vi != ve;
947 ++vi)
948 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000949 std::string value_name = vi->first().str();
950 const char *value_name_cstr = value_name.c_str();
951
952 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000953 {
954 Value *nsstring_value = vi->second;
955
956 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
957
958 if (!nsstring_global)
959 {
960 if (log)
961 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000962
963 if (m_error_stream)
964 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
965
Sean Callanan6ba533e2010-11-17 23:00:36 +0000966 return false;
967 }
968
969 if (!nsstring_global->hasInitializer())
970 {
971 if (log)
972 log->PutCString("NSString variable does not have an initializer");
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 does not have an initializer\n");
976
Sean Callanan6ba533e2010-11-17 23:00:36 +0000977 return false;
978 }
979
980 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
981
982 if (!nsstring_struct)
983 {
984 if (log)
985 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000986
987 if (m_error_stream)
988 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
989
Sean Callanan6ba533e2010-11-17 23:00:36 +0000990 return false;
991 }
992
993 // We expect the following structure:
994 //
995 // struct {
996 // int *isa;
997 // int flags;
998 // char *str;
999 // long length;
1000 // };
1001
1002 if (nsstring_struct->getNumOperands() != 4)
1003 {
1004 if (log)
1005 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 +00001006
1007 if (m_error_stream)
1008 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
1009
Sean Callanan6ba533e2010-11-17 23:00:36 +00001010 return false;
1011 }
1012
1013 Constant *nsstring_member = nsstring_struct->getOperand(2);
1014
1015 if (!nsstring_member)
1016 {
1017 if (log)
1018 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +00001019
1020 if (m_error_stream)
1021 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1022
Sean Callanan6ba533e2010-11-17 23:00:36 +00001023 return false;
1024 }
1025
1026 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1027
1028 if (!nsstring_expr)
1029 {
1030 if (log)
1031 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +00001032
1033 if (m_error_stream)
1034 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1035
Sean Callanan6ba533e2010-11-17 23:00:36 +00001036 return false;
1037 }
1038
1039 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1040 {
1041 if (log)
1042 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 +00001043
1044 if (m_error_stream)
1045 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1046
Sean Callanan6ba533e2010-11-17 23:00:36 +00001047 return false;
1048 }
1049
1050 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1051
1052 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1053
1054 if (!cstr_global)
1055 {
1056 if (log)
1057 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001058
1059 if (m_error_stream)
1060 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 +00001061
Sean Callanan6ba533e2010-11-17 23:00:36 +00001062 return false;
1063 }
1064
1065 if (!cstr_global->hasInitializer())
1066 {
1067 if (log)
1068 log->PutCString("NSString initializer's str element does not have an initializer");
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 initialized data\n");
1072
Sean Callanan6ba533e2010-11-17 23:00:36 +00001073 return false;
1074 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001075
1076 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001077 if (!cstr_array)
1078 {
1079 if (log)
1080 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001081
1082 if (m_error_stream)
1083 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1084
Sean Callanan6ba533e2010-11-17 23:00:36 +00001085 return false;
1086 }
1087
1088 if (!cstr_array->isCString())
1089 {
1090 if (log)
1091 log->PutCString("NSString initializer's str element is not a C string array");
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 a C string\n");
1095
Sean Callanan6ba533e2010-11-17 23:00:36 +00001096 return false;
1097 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001098 */
1099
1100 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001101
1102 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001103 {
1104 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001105 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001106 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001107 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001108 }
1109
1110 if (!cstr_array)
1111 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001112
Sean Callananc0492742011-05-23 21:40:23 +00001113 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001114 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001115 if (log)
1116 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001117
1118 // We don't print an error message here because RewriteObjCConstString has done so for us.
1119
Sean Callanan6ba533e2010-11-17 23:00:36 +00001120 return false;
1121 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001122 }
1123 }
1124
1125 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1126 vi != ve;
1127 ++vi)
1128 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001129 std::string value_name = vi->first().str();
1130 const char *value_name_cstr = value_name.c_str();
1131
1132 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001133 {
1134 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1135
1136 if (!gv)
1137 {
1138 if (log)
1139 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001140
1141 if (m_error_stream)
1142 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1143
Sean Callanan6ba533e2010-11-17 23:00:36 +00001144 return false;
1145 }
1146
1147 gv->eraseFromParent();
1148
1149 break;
1150 }
1151 }
1152
1153 return true;
1154}
1155
Greg Clayton3c7feb42010-11-19 01:05:25 +00001156static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001157{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001158 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001159
Greg Clayton3c7feb42010-11-19 01:05:25 +00001160 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001161 return false;
1162
1163 return true;
1164}
1165
Sean Callanan97c924e2011-01-27 01:07:04 +00001166// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001167bool
Sean Callananc0492742011-05-23 21:40:23 +00001168IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001169{
Greg Claytone005f2c2010-11-06 01:53:30 +00001170 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001171
1172 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1173
1174 if (!load)
1175 return false;
1176
1177 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1178 //
1179 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1180 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1181 //
1182 // where %obj is the object pointer and %tmp is the selector.
1183 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001184 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1185 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001186
1187 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1188
1189 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1190
1191 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1192 return false;
1193
1194 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1195
1196 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1197
1198 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1199 return false;
1200
1201 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1202
1203 if (!osr_initializer_base)
1204 return false;
1205
1206 // Find the string's initializer (a ConstantArray) and get the string from it
1207
1208 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1209
1210 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1211 return false;
1212
1213 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1214
1215 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1216
1217 if (!omvn_initializer_array->isString())
1218 return false;
1219
1220 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1221
1222 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001223 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001224
1225 // Construct a call to sel_registerName
1226
1227 if (!m_sel_registerName)
1228 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001229 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001230
Greg Clayton8de27c72010-10-15 22:48:33 +00001231 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001232 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001233 return false;
1234
Sean Callananc2c6f772010-10-26 00:31:56 +00001235 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001236 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001237
Sean Callananf5857a02010-07-31 01:32:05 +00001238 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1239
1240 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001241 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001242 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001243 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001244
Sean Callanan9b6898f2011-07-30 02:42:06 +00001245 Type *type_array[1];
1246
1247 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1248
1249 ArrayRef<Type *> srN_arg_types(type_array, 1);
1250
Sean Callananf5857a02010-07-31 01:32:05 +00001251 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1252
1253 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001254 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1255 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001256 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001257 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001258 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1259 }
1260
Sean Callanan9b6898f2011-07-30 02:42:06 +00001261 Value *argument_array[1];
1262
Sean Callananc0492742011-05-23 21:40:23 +00001263 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001264
Sean Callanan9b6898f2011-07-30 02:42:06 +00001265 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001266
Sean Callanan9b6898f2011-07-30 02:42:06 +00001267 ArrayRef<Value *> srN_arguments(argument_array, 1);
1268
Sean Callananf5857a02010-07-31 01:32:05 +00001269 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001270 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001271 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001272 selector_load);
1273
1274 // Replace the load with the call in all users
1275
1276 selector_load->replaceAllUsesWith(srN_call);
1277
1278 selector_load->eraseFromParent();
1279
1280 return true;
1281}
1282
1283bool
Sean Callananc0492742011-05-23 21:40:23 +00001284IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001285{
Greg Claytone005f2c2010-11-06 01:53:30 +00001286 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001287
1288 BasicBlock::iterator ii;
1289
1290 typedef SmallVector <Instruction*, 2> InstrList;
1291 typedef InstrList::iterator InstrIterator;
1292
1293 InstrList selector_loads;
1294
Greg Clayton3c7feb42010-11-19 01:05:25 +00001295 for (ii = basic_block.begin();
1296 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001297 ++ii)
1298 {
1299 Instruction &inst = *ii;
1300
1301 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001302 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001303 selector_loads.push_back(&inst);
1304 }
1305
1306 InstrIterator iter;
1307
1308 for (iter = selector_loads.begin();
1309 iter != selector_loads.end();
1310 ++iter)
1311 {
Sean Callananc0492742011-05-23 21:40:23 +00001312 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001313 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001314 if (m_error_stream)
1315 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1316
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001317 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001318 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001319
Sean Callananf5857a02010-07-31 01:32:05 +00001320 return false;
1321 }
1322 }
1323
1324 return true;
1325}
1326
Sean Callanan97c924e2011-01-27 01:07:04 +00001327// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001328bool
Sean Callananc0492742011-05-23 21:40:23 +00001329IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001330{
Sean Callanan97678d12011-01-13 21:23:32 +00001331 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1332
Sean Callanana48fe162010-08-11 03:57:18 +00001333 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1334
1335 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1336
1337 if (!alloc_md || !alloc_md->getNumOperands())
1338 return false;
1339
1340 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1341
1342 if (!constant_int)
1343 return false;
1344
1345 // We attempt to register this as a new persistent variable with the DeclMap.
1346
1347 uintptr_t ptr = constant_int->getZExtValue();
1348
Sean Callanan82b74c82010-08-12 01:56:52 +00001349 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001350
Sean Callanan82b74c82010-08-12 01:56:52 +00001351 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1352 &decl->getASTContext());
1353
Greg Clayton8de27c72010-10-15 22:48:33 +00001354 StringRef decl_name (decl->getName());
1355 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001356 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001357 return false;
1358
Sean Callananc0492742011-05-23 21:40:23 +00001359 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001360 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001361 false, /* not constant */
1362 GlobalValue::ExternalLinkage,
1363 NULL, /* no initializer */
1364 alloc->getName().str().c_str());
1365
1366 // What we're going to do here is make believe this was a regular old external
1367 // variable. That means we need to make the metadata valid.
1368
Sean Callananc0492742011-05-23 21:40:23 +00001369 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001370
1371 llvm::Value* values[2];
1372 values[0] = persistent_global;
1373 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001374
1375 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001376
Sean Callananc0492742011-05-23 21:40:23 +00001377 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001378 named_metadata->addOperand(persistent_global_md);
1379
Sean Callanan97678d12011-01-13 21:23:32 +00001380 // Now, since the variable is a pointer variable, we will drop in a load of that
1381 // pointer variable.
1382
1383 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1384
1385 if (log)
1386 log->Printf("Replacing \"%s\" with \"%s\"",
1387 PrintValue(alloc).c_str(),
1388 PrintValue(persistent_load).c_str());
1389
1390 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001391 alloc->eraseFromParent();
1392
1393 return true;
1394}
1395
1396bool
Sean Callananc0492742011-05-23 21:40:23 +00001397IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001398{
Sean Callanane8a59a82010-09-13 21:34:21 +00001399 if (!m_resolve_vars)
1400 return true;
1401
Greg Claytone005f2c2010-11-06 01:53:30 +00001402 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001403
1404 BasicBlock::iterator ii;
1405
1406 typedef SmallVector <Instruction*, 2> InstrList;
1407 typedef InstrList::iterator InstrIterator;
1408
1409 InstrList pvar_allocs;
1410
Greg Clayton3c7feb42010-11-19 01:05:25 +00001411 for (ii = basic_block.begin();
1412 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001413 ++ii)
1414 {
1415 Instruction &inst = *ii;
1416
1417 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001418 {
1419 llvm::StringRef alloc_name = alloc->getName();
1420
1421 if (alloc_name.startswith("$") &&
1422 !alloc_name.startswith("$__lldb"))
1423 {
1424 if (alloc_name.find_first_of("0123456789") == 1)
1425 {
1426 if (log)
1427 log->Printf("Rejecting a numeric persistent variable.");
1428
Sean Callanan97c924e2011-01-27 01:07:04 +00001429 if (m_error_stream)
1430 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1431
Sean Callanan237e4742011-01-21 22:30:25 +00001432 return false;
1433 }
1434
Sean Callanana48fe162010-08-11 03:57:18 +00001435 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001436 }
1437 }
Sean Callanana48fe162010-08-11 03:57:18 +00001438 }
1439
1440 InstrIterator iter;
1441
1442 for (iter = pvar_allocs.begin();
1443 iter != pvar_allocs.end();
1444 ++iter)
1445 {
Sean Callananc0492742011-05-23 21:40:23 +00001446 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001447 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001448 if (m_error_stream)
1449 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1450
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001451 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001452 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001453
Sean Callanana48fe162010-08-11 03:57:18 +00001454 return false;
1455 }
1456 }
1457
1458 return true;
1459}
1460
Sean Callananc7ca4662011-10-25 18:36:40 +00001461bool
1462IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1463{
1464 if (!initializer)
1465 return true;
1466
1467 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1468
1469 if (log && log->GetVerbose())
1470 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1471
1472 Type *initializer_type = initializer->getType();
1473
1474 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1475 {
1476 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1477 return true;
1478 }
1479 else if (ConstantArray *array_initializer = dyn_cast<ConstantArray>(initializer))
1480 {
1481 if (array_initializer->isString())
1482 {
1483 std::string array_initializer_string = array_initializer->getAsString();
1484 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1485 }
1486 else
1487 {
1488 ArrayType *array_initializer_type = array_initializer->getType();
1489 Type *array_element_type = array_initializer_type->getElementType();
1490
1491 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1492
1493 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1494 {
1495 if (!MaterializeInitializer(data + (i * element_size), array_initializer->getOperand(i)))
1496 return false;
1497 }
1498 }
1499 return true;
1500 }
1501 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1502 {
1503 StructType *struct_initializer_type = struct_initializer->getType();
1504 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1505
1506 for (int i = 0;
1507 i < struct_initializer->getNumOperands();
1508 ++i)
1509 {
1510 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1511 return false;
1512 }
1513 return true;
1514 }
1515 return false;
1516}
1517
1518bool
1519IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1520{
1521 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1522 return false;
1523
Sean Callananc41606f2011-11-15 19:13:54 +00001524 if (global_variable == m_reloc_placeholder)
1525 return true;
1526
Sean Callananc7ca4662011-10-25 18:36:40 +00001527 uint64_t offset = m_data_allocator->GetStream().GetSize();
1528
1529 llvm::Type *variable_type = global_variable->getType();
1530
1531 Constant *initializer = global_variable->getInitializer();
1532
1533 llvm::Type *initializer_type = initializer->getType();
1534
1535 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1536
1537 lldb_private::DataBufferHeap data(size, '\0');
1538
1539 if (initializer)
1540 if (!MaterializeInitializer(data.GetBytes(), initializer))
1541 return false;
1542
1543 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1544
1545 Constant *new_pointer = BuildRelocation(variable_type, offset);
1546
1547 global_variable->replaceAllUsesWith(new_pointer);
1548
1549 global_variable->eraseFromParent();
1550
1551 return true;
1552}
1553
Sean Callanan97c924e2011-01-27 01:07:04 +00001554// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001555bool
Sean Callananc0492742011-05-23 21:40:23 +00001556IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001557{
Greg Claytone005f2c2010-11-06 01:53:30 +00001558 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001559
1560 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001561 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001562
Greg Clayton8de27c72010-10-15 22:48:33 +00001563 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001564 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001565 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001566 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001567 default:
1568 break;
1569 case Instruction::GetElementPtr:
1570 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001571 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001572 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001573 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001574 }
1575 }
Sean Callananf921cf52010-12-03 19:51:05 +00001576 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001577 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001578 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1579 return MaterializeInternalVariable(global_variable);
1580
Sean Callananc0492742011-05-23 21:40:23 +00001581 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001582
Sean Callananf5857a02010-07-31 01:32:05 +00001583 if (!named_decl)
1584 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001585 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001586 return true;
1587
Sean Callanan7cd46742010-12-06 00:56:39 +00001588 if (!global_variable->hasExternalLinkage())
1589 return true;
1590
Sean Callananf5857a02010-07-31 01:32:05 +00001591 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001592 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001593
Sean Callananf5857a02010-07-31 01:32:05 +00001594 return false;
1595 }
1596
Greg Clayton8de27c72010-10-15 22:48:33 +00001597 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001598
Sean Callanan771131d2010-09-30 21:18:25 +00001599 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001600 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001601
1602 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001603 {
Sean Callanan771131d2010-09-30 21:18:25 +00001604 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001605 ast_context = &value_decl->getASTContext();
1606 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001607 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001608 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001609 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001610 }
Sean Callanan771131d2010-09-30 21:18:25 +00001611
Sean Callanan6a925532011-01-13 08:53:35 +00001612 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001613 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001614
Sean Callanan97678d12011-01-13 21:23:32 +00001615 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001616 {
1617 // The $__lldb_expr_result name indicates the the return value has allocated as
1618 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1619 // accesses to this static variable need to be redirected to the result of dereferencing
1620 // a pointer that is passed in as one of the arguments.
1621 //
1622 // Consequently, when reporting the size of the type, we report a pointer type pointing
1623 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001624 //
1625 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001626
Sean Callanan6a925532011-01-13 08:53:35 +00001627 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1628 value_type = PointerType::get(global_variable->getType(), 0);
1629 }
1630 else
1631 {
1632 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1633 value_type = global_variable->getType();
1634 }
Sean Callanan771131d2010-09-30 21:18:25 +00001635
1636 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1637 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001638
Sean Callanan771131d2010-09-30 21:18:25 +00001639 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001640 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001641 name.c_str(),
1642 qual_type.getAsString().c_str(),
1643 PrintType(value_type).c_str(),
1644 value_size,
1645 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001646
Sean Callanan8bce6652010-07-13 21:41:46 +00001647
Sean Callanan8c127202010-08-23 23:09:38 +00001648 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001649 lldb_private::ConstString (name.c_str()),
1650 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001651 value_size,
1652 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001653 {
1654 if (!global_variable->hasExternalLinkage())
1655 return true;
1656 else
1657 return false;
1658 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001659 }
Sean Callananf3143b72010-12-03 03:02:31 +00001660 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001661 {
1662 if (log)
1663 log->Printf("Function pointers aren't handled right now");
1664
1665 return false;
1666 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001667
1668 return true;
1669}
1670
Sean Callanan97c924e2011-01-27 01:07:04 +00001671// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001672bool
Sean Callananc0492742011-05-23 21:40:23 +00001673IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001674{
Sean Callananc7674af2011-01-17 23:42:46 +00001675 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1676
1677 lldb_private::ConstString name(symbol->getName().str().c_str());
1678
Sean Callanan21ef5bb2011-12-01 02:04:16 +00001679 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc7674af2011-01-17 23:42:46 +00001680
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001681 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001682 {
1683 if (log)
1684 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1685
1686 return false;
1687 }
1688
1689 if (log)
1690 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1691
Sean Callanan9b6898f2011-07-30 02:42:06 +00001692 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001693
Sean Callanan9b6898f2011-07-30 02:42:06 +00001694 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1695 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001696
1697 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1698
1699 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1700
1701 if (log)
1702 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1703
1704 symbol->replaceAllUsesWith(symbol_addr_ptr);
1705
1706 return true;
1707}
1708
1709bool
Sean Callananc0492742011-05-23 21:40:23 +00001710IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001711{
Sean Callanan48443652010-12-02 19:47:57 +00001712 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1713
1714 if (log)
1715 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001716
Sean Callanan6ba533e2010-11-17 23:00:36 +00001717 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001718 op_index < num_ops;
1719 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001720 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001721 {
1722 if (m_error_stream)
1723 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1724
Sean Callanandc27aba2010-10-05 22:26:43 +00001725 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001726 }
1727
Sean Callanandc27aba2010-10-05 22:26:43 +00001728 return true;
1729}
1730
1731bool
Sean Callanan9911d2f2011-11-01 23:38:03 +00001732IRForTarget::HandleObjCClass(Value *classlist_reference)
1733{
1734 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1735
1736 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1737
1738 if (!global_variable)
1739 return false;
1740
1741 Constant *initializer = global_variable->getInitializer();
1742
1743 if (!initializer)
1744 return false;
1745
1746 if (!initializer->hasName())
1747 return false;
1748
1749 StringRef name(initializer->getName());
1750 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton16d21872011-12-03 20:02:42 +00001751 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callanan9911d2f2011-11-01 23:38:03 +00001752
1753 if (log)
1754 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1755
1756 if (class_ptr == LLDB_INVALID_ADDRESS)
1757 return false;
1758
1759 if (global_variable->use_begin() == global_variable->use_end())
1760 return false;
1761
1762 LoadInst *load_instruction = NULL;
1763
1764 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1765 i != e;
1766 ++i)
1767 {
1768 if ((load_instruction = dyn_cast<LoadInst>(*i)))
1769 break;
1770 }
1771
1772 if (!load_instruction)
1773 return false;
1774
1775 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1776 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1777
1778 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1779 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1780
1781 load_instruction->replaceAllUsesWith(class_bitcast);
1782
1783 load_instruction->eraseFromParent();
1784
1785 return true;
1786}
1787
1788bool
Sean Callananc0492742011-05-23 21:40:23 +00001789IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001790{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001791 /////////////////////////////////////////////////////////////////////////
1792 // Prepare the current basic block for execution in the remote process
1793 //
1794
Sean Callanan02fbafa2010-07-27 21:39:39 +00001795 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001796
Greg Clayton3c7feb42010-11-19 01:05:25 +00001797 for (ii = basic_block.begin();
1798 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001799 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001800 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001801 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001802
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001803 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001804
Sean Callanan97c924e2011-01-27 01:07:04 +00001805 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001806 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001807 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001808 }
1809
1810 return true;
1811}
1812
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001813bool
Sean Callananc0492742011-05-23 21:40:23 +00001814IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001815{
Sean Callananae71e302010-11-18 22:21:58 +00001816 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1817
Sean Callananc0492742011-05-23 21:40:23 +00001818 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001819 global != end;
1820 ++global)
1821 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001822 if (log)
1823 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1824 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001825 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001826
Sean Callanan9911d2f2011-11-01 23:38:03 +00001827 std::string global_name = (*global).getName().str();
1828
1829 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc7674af2011-01-17 23:42:46 +00001830 {
Sean Callananc0492742011-05-23 21:40:23 +00001831 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001832 {
1833 if (m_error_stream)
1834 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1835
Sean Callananc7674af2011-01-17 23:42:46 +00001836 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001837 }
Sean Callananc7674af2011-01-17 23:42:46 +00001838 }
Sean Callanan9911d2f2011-11-01 23:38:03 +00001839 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1840 {
1841 if (!HandleObjCClass(global))
1842 {
1843 if (m_error_stream)
1844 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1845
1846 return false;
1847 }
1848 }
Sean Callananc0492742011-05-23 21:40:23 +00001849 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001850 {
Sean Callananc0492742011-05-23 21:40:23 +00001851 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001852 {
1853 if (m_error_stream)
1854 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1855
Sean Callananc7674af2011-01-17 23:42:46 +00001856 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001857 }
Sean Callananc7674af2011-01-17 23:42:46 +00001858 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001859 }
1860
1861 return true;
1862}
1863
Sean Callananc0492742011-05-23 21:40:23 +00001864bool
1865IRForTarget::ReplaceStrings ()
1866{
1867 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1868
1869 if (!m_data_allocator)
1870 return true; // hope for the best; some clients may not want static allocation!
1871
1872 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1873
1874 OffsetsTy offsets;
1875
1876 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1877 gi != ge;
1878 ++gi)
1879 {
1880 GlobalVariable *gv = gi;
1881
1882 if (!gv->hasInitializer())
1883 continue;
1884
1885 Constant *gc = gv->getInitializer();
1886
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001887 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001888
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001889 if (gc->isNullValue())
1890 {
1891 Type *gc_type = gc->getType();
1892
1893 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1894
1895 if (!gc_array_type)
1896 continue;
1897
1898 Type *gc_element_type = gc_array_type->getElementType();
1899
1900 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1901
1902 if (gc_integer_type->getBitWidth() != 8)
1903 continue;
1904
1905 str = "";
1906 }
1907 else
1908 {
1909 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1910
1911 if (!gc_array)
1912 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001913
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001914 if (!gc_array->isCString())
1915 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001916
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001917 if (log)
1918 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001919
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001920 str = gc_array->getAsString();
1921 }
1922
Sean Callananc0492742011-05-23 21:40:23 +00001923 offsets[gv] = m_data_allocator->GetStream().GetSize();
1924
1925 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1926 }
1927
Sean Callanan9b6898f2011-07-30 02:42:06 +00001928 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001929
1930 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1931 oi != oe;
1932 ++oi)
1933 {
1934 GlobalVariable *gv = oi->first;
1935 size_t offset = oi->second;
1936
1937 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1938
1939 if (log)
1940 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1941
1942 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1943 ui != ue;
1944 ++ui)
1945 {
1946 if (log)
1947 log->Printf("Found use %s", PrintValue(*ui).c_str());
1948
1949 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1950 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1951
1952 if (const_expr)
1953 {
1954 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1955 {
1956 if (log)
1957 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1958
1959 return false;
1960 }
1961
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001962 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1963 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1964
1965 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001966 }
1967 else if (store_inst)
1968 {
1969 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1970
1971 store_inst->setOperand(0, bit_cast);
1972 }
1973 else
1974 {
1975 if (log)
1976 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1977
1978 return false;
1979 }
1980 }
1981
1982 gv->eraseFromParent();
1983 }
1984
1985 return true;
1986}
1987
1988bool
1989IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1990{
1991 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1992
1993 if (!m_data_allocator)
1994 return true;
1995
1996 typedef SmallVector <Value*, 2> ConstantList;
1997 typedef SmallVector <llvm::Instruction*, 2> UserList;
1998 typedef ConstantList::iterator ConstantIterator;
1999 typedef UserList::iterator UserIterator;
2000
2001 ConstantList static_constants;
2002 UserList static_users;
2003
2004 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2005 ii != ie;
2006 ++ii)
2007 {
2008 llvm::Instruction &inst = *ii;
2009
2010 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2011 oi != oe;
2012 ++oi)
2013 {
2014 Value *operand_val = oi->get();
2015
2016 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2017
2018 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
2019 {
2020 static_constants.push_back(operand_val);
2021 static_users.push_back(ii);
2022 }
2023 }
2024 }
2025
2026 ConstantIterator constant_iter;
2027 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00002028
Sean Callananc0492742011-05-23 21:40:23 +00002029 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2030 constant_iter != static_constants.end();
2031 ++constant_iter, ++user_iter)
2032 {
2033 Value *operand_val = *constant_iter;
2034 llvm::Instruction *inst = *user_iter;
2035
2036 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2037
2038 if (operand_constant_fp)
2039 {
2040 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2041 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2042
2043 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2044 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2045
2046 if (log)
2047 {
2048 std::string s;
2049 raw_string_ostream ss(s);
2050 for (size_t index = 0;
2051 index < operand_data_size;
2052 ++index)
2053 {
2054 ss << (uint32_t)operand_raw_data[index];
2055 ss << " ";
2056 }
2057 ss.flush();
2058
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002059 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00002060 }
2061
2062 lldb_private::DataBufferHeap data(operand_data_size, 0);
2063
2064 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
2065 {
2066 uint8_t *data_bytes = data.GetBytes();
2067
2068 for (size_t index = 0;
2069 index < operand_data_size;
2070 ++index)
2071 {
2072 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2073 }
2074 }
2075 else
2076 {
2077 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2078 }
2079
2080 uint64_t offset = m_data_allocator->GetStream().GetSize();
2081
2082 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
2083
Sean Callanan9b6898f2011-07-30 02:42:06 +00002084 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00002085
2086 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2087
2088 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2089
2090 operand_constant_fp->replaceAllUsesWith(fp_load);
2091 }
2092 }
2093
2094 return true;
2095}
2096
Sean Callanan02fbafa2010-07-27 21:39:39 +00002097static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00002098{
Sean Callanan58baaad2011-07-08 00:39:14 +00002099 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00002100
Sean Callanan6ba533e2010-11-17 23:00:36 +00002101 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00002102 return false;
2103
Sean Callanan58baaad2011-07-08 00:39:14 +00002104 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002105
2106 if ((CE = dyn_cast<ConstantExpr>(V)))
2107 {
2108 if (CE->getOpcode() != Instruction::BitCast)
2109 return false;
2110
Sean Callanan6ba533e2010-11-17 23:00:36 +00002111 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002112 }
2113
Sean Callanan6ba533e2010-11-17 23:00:36 +00002114 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00002115
2116 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2117 return false;
2118
2119 return true;
2120}
2121
Sean Callananc0492742011-05-23 21:40:23 +00002122void
2123IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00002124{
Sean Callananc0492742011-05-23 21:40:23 +00002125 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002126
2127 Value::use_iterator ui;
2128
2129 for (ui = guard_load->use_begin();
2130 ui != guard_load->use_end();
2131 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002132 {
Greg Clayton6e713402010-07-30 20:30:44 +00002133 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002134 {
2135 // do nothing for the moment
2136 }
2137 else
2138 {
2139 ui->replaceUsesOfWith(guard_load, zero);
2140 }
2141 }
Sean Callanan45839272010-07-24 01:37:44 +00002142
2143 guard_load->eraseFromParent();
2144}
2145
2146static void ExciseGuardStore(Instruction* guard_store)
2147{
2148 guard_store->eraseFromParent();
2149}
2150
2151bool
Sean Callananc0492742011-05-23 21:40:23 +00002152IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002153{
2154 ///////////////////////////////////////////////////////
2155 // Eliminate any reference to guard variables found.
2156 //
2157
Sean Callanan02fbafa2010-07-27 21:39:39 +00002158 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002159
Sean Callanan02fbafa2010-07-27 21:39:39 +00002160 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002161 typedef InstrList::iterator InstrIterator;
2162
2163 InstrList guard_loads;
2164 InstrList guard_stores;
2165
Greg Clayton3c7feb42010-11-19 01:05:25 +00002166 for (ii = basic_block.begin();
2167 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002168 ++ii)
2169 {
2170 Instruction &inst = *ii;
2171
2172 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2173 if (isGuardVariableRef(load->getPointerOperand()))
2174 guard_loads.push_back(&inst);
2175
2176 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2177 if (isGuardVariableRef(store->getPointerOperand()))
2178 guard_stores.push_back(&inst);
2179 }
2180
2181 InstrIterator iter;
2182
2183 for (iter = guard_loads.begin();
2184 iter != guard_loads.end();
2185 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002186 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002187
2188 for (iter = guard_stores.begin();
2189 iter != guard_stores.end();
2190 ++iter)
2191 ExciseGuardStore(*iter);
2192
2193 return true;
2194}
2195
Sean Callanan97c924e2011-01-27 01:07:04 +00002196// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002197bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002198IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002199{
Greg Claytone005f2c2010-11-06 01:53:30 +00002200 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002201
2202 Value::use_iterator ui;
2203
Sean Callanana48fe162010-08-11 03:57:18 +00002204 SmallVector<User*, 16> users;
2205
2206 // We do this because the use list might change, invalidating our iterator.
2207 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002208 for (ui = old_constant->use_begin();
2209 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002210 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002211 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002212
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002213 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002214 i < users.size();
2215 ++i)
2216 {
2217 User *user = users[i];
2218
Sean Callananbafd6852010-07-14 23:40:29 +00002219 if (Constant *constant = dyn_cast<Constant>(user))
2220 {
2221 // synthesize a new non-constant equivalent of the constant
2222
2223 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2224 {
2225 switch (constant_expr->getOpcode())
2226 {
2227 default:
2228 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002229 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002230 return false;
2231 case Instruction::BitCast:
2232 {
2233 // UnaryExpr
2234 // OperandList[0] is value
2235
2236 Value *s = constant_expr->getOperand(0);
2237
Greg Clayton3c7feb42010-11-19 01:05:25 +00002238 if (s == old_constant)
2239 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002240
Sean Callananc0492742011-05-23 21:40:23 +00002241 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002242
Greg Clayton3c7feb42010-11-19 01:05:25 +00002243 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002244 }
2245 break;
2246 case Instruction::GetElementPtr:
2247 {
2248 // GetElementPtrConstantExpr
2249 // OperandList[0] is base
2250 // OperandList[1]... are indices
2251
2252 Value *ptr = constant_expr->getOperand(0);
2253
Greg Clayton3c7feb42010-11-19 01:05:25 +00002254 if (ptr == old_constant)
2255 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002256
2257 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002258
2259 unsigned operand_index;
2260 unsigned num_operands = constant_expr->getNumOperands();
2261
2262 for (operand_index = 1;
2263 operand_index < num_operands;
2264 ++operand_index)
2265 {
2266 Value *operand = constant_expr->getOperand(operand_index);
2267
Greg Clayton3c7feb42010-11-19 01:05:25 +00002268 if (operand == old_constant)
2269 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002270
Sean Callanan9b6898f2011-07-30 02:42:06 +00002271 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002272 }
2273
Sean Callanan9b6898f2011-07-30 02:42:06 +00002274 ArrayRef <Value*> indices(index_vector);
2275
2276 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002277
Greg Clayton3c7feb42010-11-19 01:05:25 +00002278 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002279 }
2280 break;
2281 }
2282 }
2283 else
2284 {
2285 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002286 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002287 return false;
2288 }
2289 }
2290 else
2291 {
2292 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002293 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002294 }
2295 }
2296
2297 return true;
2298}
2299
Sean Callanan8bce6652010-07-13 21:41:46 +00002300bool
Sean Callananc0492742011-05-23 21:40:23 +00002301IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002302{
Sean Callanane8a59a82010-09-13 21:34:21 +00002303 if (!m_resolve_vars)
2304 return true;
2305
Greg Claytone005f2c2010-11-06 01:53:30 +00002306 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002307
2308 m_decl_map->DoStructLayout();
2309
2310 if (log)
2311 log->Printf("Element arrangement:");
2312
2313 uint32_t num_elements;
2314 uint32_t element_index;
2315
2316 size_t size;
2317 off_t alignment;
2318
2319 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2320 return false;
2321
Greg Clayton3c7feb42010-11-19 01:05:25 +00002322 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002323
Greg Clayton3c7feb42010-11-19 01:05:25 +00002324 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002325 {
2326 if (m_error_stream)
2327 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2328
Sean Callanan8bce6652010-07-13 21:41:46 +00002329 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002330 }
2331
Sean Callanan02fbafa2010-07-27 21:39:39 +00002332 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002333
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002334 if (argument->getName().equals("this"))
2335 {
2336 ++iter;
2337
Greg Clayton3c7feb42010-11-19 01:05:25 +00002338 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002339 {
2340 if (m_error_stream)
2341 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2342
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002343 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002344 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002345
2346 argument = iter;
2347 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002348 else if (argument->getName().equals("self"))
2349 {
2350 ++iter;
2351
2352 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002353 {
2354 if (m_error_stream)
2355 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2356
Sean Callanan3aa7da52010-12-13 22:46:15 +00002357 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002358 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002359
2360 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002361 {
2362 if (m_error_stream)
2363 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2364
Sean Callanan3aa7da52010-12-13 22:46:15 +00002365 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002366 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002367
2368 ++iter;
2369
2370 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002371 {
2372 if (m_error_stream)
2373 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2374
Sean Callanan3aa7da52010-12-13 22:46:15 +00002375 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002376 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002377
2378 argument = iter;
2379 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002380
Greg Clayton8de27c72010-10-15 22:48:33 +00002381 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002382 {
2383 if (m_error_stream)
2384 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2385
Sean Callanan8bce6652010-07-13 21:41:46 +00002386 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002387 }
2388
Sean Callanan8bce6652010-07-13 21:41:46 +00002389 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002390 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002391
Greg Clayton3c7feb42010-11-19 01:05:25 +00002392 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002393 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002394
Sean Callanan6ba533e2010-11-17 23:00:36 +00002395 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002396 {
2397 if (m_error_stream)
2398 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2399
Sean Callanan8bce6652010-07-13 21:41:46 +00002400 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002401 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002402
Sean Callananc0492742011-05-23 21:40:23 +00002403 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002404 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002405
2406 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002407 {
2408 if (m_error_stream)
2409 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
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
2414 for (element_index = 0; element_index < num_elements; ++element_index)
2415 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002416 const clang::NamedDecl *decl = NULL;
2417 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002418 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002419 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002420
Sean Callanan45690fe2010-08-30 22:17:16 +00002421 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002422 {
2423 if (m_error_stream)
2424 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2425
Sean Callanan8bce6652010-07-13 21:41:46 +00002426 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002427 }
2428
Sean Callanan8bce6652010-07-13 21:41:46 +00002429 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002430 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002431 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002432 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002433 offset);
2434
Sean Callanan9b6898f2011-07-30 02:42:06 +00002435 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002436 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002437
Sean Callananc7ca4662011-10-25 18:36:40 +00002438 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002439 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002440 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002441
Sean Callananc7ca4662011-10-25 18:36:40 +00002442 if (log)
2443 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002444
Sean Callananc7ca4662011-10-25 18:36:40 +00002445 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2446 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2447 // entry in order to produce the static variable that the AST thinks it is accessing.
2448 if (name == m_result_name && !m_result_is_pointer)
2449 {
2450 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2451
2452 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2453
2454 replacement = load;
2455 }
2456 else
2457 {
2458 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2459
2460 replacement = bit_cast;
2461 }
2462
2463 if (Constant *constant = dyn_cast<Constant>(value))
2464 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2465 else
2466 value->replaceAllUsesWith(replacement);
2467
2468 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2469 var->eraseFromParent();
2470 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002471 }
2472
2473 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002474 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002475
2476 return true;
2477}
2478
Sean Callananc0492742011-05-23 21:40:23 +00002479llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002480IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002481 uint64_t offset)
2482{
2483 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2484
Sean Callanan9b6898f2011-07-30 02:42:06 +00002485 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2486 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002487
2488 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002489
2490 llvm::Constant *offset_array[1];
2491
2492 offset_array[0] = offset_int;
2493
2494 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2495
2496 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002497 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2498
2499 return reloc_getbitcast;
2500}
2501
2502bool
2503IRForTarget::CompleteDataAllocation ()
2504{
Sean Callanan47dc4572011-09-15 02:13:07 +00002505 if (!m_data_allocator)
2506 return true;
2507
Sean Callananc0492742011-05-23 21:40:23 +00002508 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2509
2510 if (!m_data_allocator->GetStream().GetSize())
2511 return true;
2512
2513 lldb::addr_t allocation = m_data_allocator->Allocate();
2514
2515 if (log)
2516 {
2517 if (allocation)
2518 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2519 else
2520 log->Printf("Failed to allocate static data");
2521 }
2522
2523 if (!allocation)
2524 return false;
2525
Sean Callanan9b6898f2011-07-30 02:42:06 +00002526 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2527 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002528
2529 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2530 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2531
2532 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2533
2534 m_reloc_placeholder->eraseFromParent();
2535
2536 return true;
2537}
2538
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002539bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002540IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002541{
Greg Claytone005f2c2010-11-06 01:53:30 +00002542 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002543
Sean Callananc0492742011-05-23 21:40:23 +00002544 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002545 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002546
2547 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002548
2549 if (!function)
2550 {
2551 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002552 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002553
2554 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002555 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 +00002556
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002557 return false;
2558 }
Sean Callananc0492742011-05-23 21:40:23 +00002559
2560 if (!FixFunctionLinkage (*function))
2561 {
2562 if (log)
2563 log->Printf("Couldn't fix the linkage for the function");
2564
2565 return false;
2566 }
2567
Sean Callananc7ca4662011-10-25 18:36:40 +00002568 if (log)
2569 {
2570 std::string s;
2571 raw_string_ostream oss(s);
2572
2573 m_module->print(oss, NULL);
2574
2575 oss.flush();
2576
2577 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2578 }
2579
Sean Callanan9b6898f2011-07-30 02:42:06 +00002580 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002581
2582 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2583 intptr_ty,
2584 false /* isConstant */,
2585 GlobalVariable::InternalLinkage,
2586 Constant::getNullValue(intptr_ty),
2587 "reloc_placeholder",
2588 NULL /* InsertBefore */,
2589 false /* ThreadLocal */,
2590 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002591
Sean Callanan02fbafa2010-07-27 21:39:39 +00002592 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002593
Sean Callananc0492742011-05-23 21:40:23 +00002594 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002595
Sean Callanan82b74c82010-08-12 01:56:52 +00002596 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002597 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002598 //
2599
Sean Callananc0492742011-05-23 21:40:23 +00002600 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002601 {
2602 if (log)
2603 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002604
2605 // CreateResultVariable() reports its own errors, so we don't do so here
2606
Sean Callanan82b74c82010-08-12 01:56:52 +00002607 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002608 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002609
2610 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2611 {
2612 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002613 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002614 }
2615
2616 for (bbi = function->begin();
2617 bbi != function->end();
2618 ++bbi)
2619 {
2620 if (!RemoveGuards(*bbi))
2621 {
2622 if (log)
2623 log->Printf("RemoveGuards() failed");
2624
2625 // RemoveGuards() reports its own errors, so we don't do so here
2626
2627 return false;
2628 }
2629
2630 if (!RewritePersistentAllocs(*bbi))
2631 {
2632 if (log)
2633 log->Printf("RewritePersistentAllocs() failed");
2634
2635 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2636
2637 return false;
2638 }
2639 }
2640
2641 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2642 {
2643 IRInterpreter interpreter (*m_decl_map,
2644 m_error_stream);
2645
2646 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2647 {
2648 m_interpret_success = true;
2649 return true;
2650 }
2651 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002652
Sean Callanan7b8eb762011-11-01 17:33:54 +00002653 if (log && log->GetVerbose())
Sean Callananc0492742011-05-23 21:40:23 +00002654 {
2655 std::string s;
2656 raw_string_ostream oss(s);
2657
2658 m_module->print(oss, NULL);
2659
2660 oss.flush();
2661
2662 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2663 }
2664
Sean Callanan6ba533e2010-11-17 23:00:36 +00002665 ///////////////////////////////////////////////////////////////////////////////
2666 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2667 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002668
Sean Callananc0492742011-05-23 21:40:23 +00002669 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002670 {
2671 if (log)
2672 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002673
2674 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2675
Sean Callanan6ba533e2010-11-17 23:00:36 +00002676 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002677 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002678
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002679 ///////////////////////////////
2680 // Resolve function pointers
2681 //
2682
2683 if (!ResolveFunctionPointers(llvm_module, *function))
2684 {
2685 if (log)
2686 log->Printf("ResolveFunctionPointers() failed");
2687
2688 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2689
2690 return false;
2691 }
2692
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002693 for (bbi = function->begin();
2694 bbi != function->end();
2695 ++bbi)
2696 {
Sean Callananc0492742011-05-23 21:40:23 +00002697 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002698 {
2699 if (log)
2700 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002701
2702 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2703
Sean Callanana48fe162010-08-11 03:57:18 +00002704 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002705 }
Sean Callanana48fe162010-08-11 03:57:18 +00002706
Sean Callananc0492742011-05-23 21:40:23 +00002707 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002708 {
2709 if (log)
2710 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002711
2712 // ResolveCalls() reports its own errors, so we don't do so here
2713
Sean Callanan8bce6652010-07-13 21:41:46 +00002714 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002715 }
Sean Callananc0492742011-05-23 21:40:23 +00002716
2717 if (!ReplaceStaticLiterals(*bbi))
2718 {
2719 if (log)
2720 log->Printf("ReplaceStaticLiterals() failed");
2721
2722 return false;
2723 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002724 }
2725
Sean Callanan771131d2010-09-30 21:18:25 +00002726 ///////////////////////////////
2727 // Run function-level passes
2728 //
2729
Sean Callananc0492742011-05-23 21:40:23 +00002730 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002731 {
2732 if (log)
2733 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002734
2735 // ResolveExternals() reports its own errors, so we don't do so here
2736
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002737 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002738 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002739
Sean Callananc0492742011-05-23 21:40:23 +00002740 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002741 {
2742 if (log)
2743 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002744
2745 // ReplaceVariables() reports its own errors, so we don't do so here
2746
Sean Callanan771131d2010-09-30 21:18:25 +00002747 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002748 }
Sean Callanan771131d2010-09-30 21:18:25 +00002749
Sean Callananc0492742011-05-23 21:40:23 +00002750 if (!ReplaceStrings())
2751 {
2752 if (log)
2753 log->Printf("ReplaceStrings() failed");
2754
2755 return false;
2756 }
2757
2758 if (!CompleteDataAllocation())
2759 {
2760 if (log)
2761 log->Printf("CompleteDataAllocation() failed");
2762
2763 return false;
2764 }
2765
Sean Callanan7b8eb762011-11-01 17:33:54 +00002766 if (log && log->GetVerbose())
Sean Callanan8bce6652010-07-13 21:41:46 +00002767 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002768 std::string s;
2769 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002770
Sean Callananc0492742011-05-23 21:40:23 +00002771 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002772
2773 oss.flush();
2774
Greg Claytonb5037af2010-11-15 01:47:11 +00002775 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002776 }
2777
2778 return true;
2779}
2780
2781void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002782IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002783{
2784}
2785
2786PassManagerType
2787IRForTarget::getPotentialPassManagerType() const
2788{
2789 return PMT_ModulePassManager;
2790}