blob: 2c0d8ba80fa36522e9e087697ec420872a91ba26 [file] [log] [blame]
Sean Callanan47dc4572011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
Sean Callanan2a8c3382011-04-14 02:01:31 +000013#include "llvm/Constants.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000014#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000015#include "llvm/Instructions.h"
Sean Callanan3cb1fd82010-09-28 23:55:00 +000016#include "llvm/Intrinsics.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000017#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000018#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000019#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000020
21#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000022
Greg Clayton8de27c72010-10-15 22:48:33 +000023#include "lldb/Core/ConstString.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000024#include "lldb/Core/dwarf.h"
25#include "lldb/Core/Log.h"
26#include "lldb/Core/Scalar.h"
27#include "lldb/Core/StreamString.h"
28#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callanan47dc4572011-09-15 02:13:07 +000029#include "lldb/Expression/IRInterpreter.h"
Sean Callananc0492742011-05-23 21:40:23 +000030#include "lldb/Host/Endian.h"
Sean Callanan696cf5f2011-05-07 01:06:41 +000031#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000032
33#include <map>
34
35using namespace llvm;
36
Sean Callanan3351dac2010-08-18 18:50:51 +000037static char ID;
38
Sean Callananc0492742011-05-23 21:40:23 +000039IRForTarget::StaticDataAllocator::StaticDataAllocator()
40{
41}
42
43IRForTarget::StaticDataAllocator::~StaticDataAllocator()
44{
45}
46
Greg Clayton3c7feb42010-11-19 01:05:25 +000047IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
48 bool resolve_vars,
Sean Callanan47dc4572011-09-15 02:13:07 +000049 lldb_private::ExecutionPolicy execution_policy,
Sean Callanan696cf5f2011-05-07 01:06:41 +000050 lldb::ClangExpressionVariableSP &const_result,
Sean Callananc0492742011-05-23 21:40:23 +000051 StaticDataAllocator *data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +000052 lldb_private::Stream *error_stream,
Greg Clayton3c7feb42010-11-19 01:05:25 +000053 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000054 ModulePass(ID),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000055 m_resolve_vars(resolve_vars),
Sean Callanan47dc4572011-09-15 02:13:07 +000056 m_execution_policy(execution_policy),
57 m_interpret_success(false),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000058 m_func_name(func_name),
Sean Callananc0492742011-05-23 21:40:23 +000059 m_module(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000060 m_decl_map(decl_map),
61 m_data_allocator(data_allocator),
Sean Callanan6ba533e2010-11-17 23:00:36 +000062 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000063 m_sel_registerName(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000064 m_const_result(const_result),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000065 m_error_stream(error_stream),
Sean Callanan6a925532011-01-13 08:53:35 +000066 m_has_side_effects(false),
Sean Callanan696cf5f2011-05-07 01:06:41 +000067 m_result_store(NULL),
68 m_result_is_pointer(false),
Sean Callananc0492742011-05-23 21:40:23 +000069 m_reloc_placeholder(NULL)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000070{
71}
72
Sean Callanan771131d2010-09-30 21:18:25 +000073/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000074
75static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000076PrintValue(const Value *value, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000077{
78 std::string s;
79 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000080 value->print(rso);
Sean Callanana48fe162010-08-11 03:57:18 +000081 rso.flush();
82 if (truncate)
83 s.resize(s.length() - 1);
84 return s;
85}
86
Sean Callanan771131d2010-09-30 21:18:25 +000087static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000088PrintType(const Type *type, bool truncate = false)
Sean Callanan771131d2010-09-30 21:18:25 +000089{
90 std::string s;
91 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000092 type->print(rso);
Sean Callanan771131d2010-09-30 21:18:25 +000093 rso.flush();
94 if (truncate)
95 s.resize(s.length() - 1);
96 return s;
97}
98
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000099IRForTarget::~IRForTarget()
100{
101}
102
Sean Callananc0492742011-05-23 21:40:23 +0000103bool
104IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
105{
106 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
107
108 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
109
Sean Callananfecc09c2011-11-19 02:54:21 +0000110 std::string name = llvm_function.getName().str();
Sean Callananc0492742011-05-23 21:40:23 +0000111
112 return true;
113}
114
Sean Callanan82b74c82010-08-12 01:56:52 +0000115bool
Sean Callananc0492742011-05-23 21:40:23 +0000116IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000117{
118 llvm::Function::iterator bbi;
119 BasicBlock::iterator ii;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000120
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000121 for (bbi = llvm_function.begin();
122 bbi != llvm_function.end();
123 ++bbi)
124 {
125 BasicBlock &basic_block = *bbi;
126
127 for (ii = basic_block.begin();
128 ii != basic_block.end();
129 ++ii)
130 {
131 switch (ii->getOpcode())
132 {
133 default:
134 return true;
135 case Instruction::Store:
136 {
137 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
138
139 Value *store_ptr = store_inst->getPointerOperand();
140
Sean Callanan696cf5f2011-05-07 01:06:41 +0000141 std::string ptr_name;
142
143 if (store_ptr->hasName())
Sean Callananfecc09c2011-11-19 02:54:21 +0000144 ptr_name = store_ptr->getName().str();
Sean Callanan696cf5f2011-05-07 01:06:41 +0000145
146 if (isa <AllocaInst> (store_ptr))
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000147 break;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000148
149 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
150 {
151 if (ptr_name.find("GV") == std::string::npos)
152 m_result_store = store_inst;
153 }
154 else
155 {
156 return true;
157 }
158
159 break;
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000160 }
161 case Instruction::Load:
162 case Instruction::Alloca:
163 case Instruction::GetElementPtr:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000164 case Instruction::BitCast:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000165 case Instruction::Ret:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000166 case Instruction::ICmp:
167 case Instruction::Br:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000168 break;
169 }
170 }
171 }
172
173 return false;
174}
175
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000176bool
177IRForTarget::GetFunctionAddress (llvm::Function *fun,
178 uint64_t &fun_addr,
179 lldb_private::ConstString &name,
180 Constant **&value_ptr)
181{
182 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
183
184 fun_addr = LLDB_INVALID_ADDRESS;
185 name.Clear();
186 value_ptr = NULL;
187
188 if (fun->isIntrinsic())
189 {
190 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
191
192 switch (intrinsic_id)
193 {
194 default:
195 if (log)
196 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
197
198 if (m_error_stream)
199 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
200
201 return false;
202 case Intrinsic::memcpy:
203 {
204 static lldb_private::ConstString g_memcpy_str ("memcpy");
205 name = g_memcpy_str;
206 }
207 break;
Sean Callanan7befa302011-11-16 00:20:50 +0000208 case Intrinsic::memset:
209 {
210 static lldb_private::ConstString g_memset_str ("memset");
211 name = g_memset_str;
212 }
213 break;
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000214 }
215
216 if (log && name)
217 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
218 }
219 else
220 {
221 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
222 }
223
224 // Find the address of the function.
225
226 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000227
228 if (fun_decl)
229 {
Sean Callananc7ca4662011-10-25 18:36:40 +0000230 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000231 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000232 lldb_private::ConstString alternate_mangling_const_str;
233 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
234 if (!found_it)
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000235 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000236 // Check for an alternate mangling for "std::basic_string<char>"
237 // that is part of the itanium C++ name mangling scheme
238 const char *name_cstr = name.GetCString();
239 if (strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
240 {
241 std::string alternate_mangling("_ZNKSs");
242 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
243 alternate_mangling_const_str.SetCString(alternate_mangling.c_str());
244 found_it = m_decl_map->GetFunctionAddress (alternate_mangling_const_str, fun_addr);
245 }
246 }
247
248 if (!found_it)
249 {
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000250 if (log)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000251 {
252 if (alternate_mangling_const_str)
253 log->Printf("Function \"%s\" (alternate name \"%s\") has no address", name.GetCString(), alternate_mangling_const_str.GetCString());
254 else
255 log->Printf("Function \"%s\" had no address", name.GetCString());
256 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000257
258 if (m_error_stream)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000259 {
260 if (alternate_mangling_const_str)
261 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n", name.GetCString(), alternate_mangling_const_str.GetCString());
262 else
263 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n", name.GetCString());
264 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000265 return false;
266 }
267 }
268 }
269 else
270 {
271 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
272 {
273 if (log)
274 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
275
276 if (m_error_stream)
277 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
278
279 return false;
280 }
281 }
282
283 if (log)
284 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), fun_addr);
285
286 return true;
287}
288
289llvm::Constant *
290IRForTarget::BuildFunctionPointer (llvm::Type *type,
291 uint64_t ptr)
292{
293 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
294 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
295 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
296 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
297 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
298}
299
Sean Callanan715f6b02011-10-31 22:11:40 +0000300void
301IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
302 llvm::Value *function_ptr,
303 const char *name)
304{
305 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
306
307 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
308 i != e;
309 ++i)
310 {
311 Value *user = *i;
312
313 if (Instruction *user_inst = dyn_cast<Instruction>(user))
314 {
315 Constant *name_array = ConstantArray::get(context, StringRef(name));
316
317 ArrayRef<Value *> md_values(name_array);
318
319 MDNode *metadata = MDNode::get(context, md_values);
320
321 user_inst->setMetadata("lldb.call.realName", metadata);
322 }
323 else
324 {
325 RegisterFunctionMetadata (context, user, name);
326 }
327 }
328}
329
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000330bool
331IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
332 llvm::Function &llvm_function)
333{
334 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
335
336 for (llvm::Module::iterator fi = llvm_module.begin();
337 fi != llvm_module.end();
338 ++fi)
339 {
340 Function *fun = fi;
341
342 bool is_decl = fun->isDeclaration();
343
344 if (log)
Sean Callananfecc09c2011-11-19 02:54:21 +0000345 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000346
347 if (!is_decl)
348 continue;
349
350 if (fun->hasNUses(0))
351 continue; // ignore
352
353 uint64_t addr = LLDB_INVALID_ADDRESS;
354 lldb_private::ConstString name;
355 Constant **value_ptr = NULL;
356
357 if (!GetFunctionAddress(fun,
358 addr,
359 name,
360 value_ptr))
361 return false; // GetFunctionAddress reports its own errors
362
363 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
364
Sean Callanan715f6b02011-10-31 22:11:40 +0000365 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
366
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000367 if (value_ptr)
368 *value_ptr = value;
369
370 fun->replaceAllUsesWith(value);
371 }
372
373 return true;
374}
375
Sean Callanan47dc4572011-09-15 02:13:07 +0000376
Sean Callanan696cf5f2011-05-07 01:06:41 +0000377clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000378IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000379{
380 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
381
Sean Callanan47dc4572011-09-15 02:13:07 +0000382 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000383
384 if (!named_metadata)
385 return NULL;
386
387 unsigned num_nodes = named_metadata->getNumOperands();
388 unsigned node_index;
389
390 for (node_index = 0;
391 node_index < num_nodes;
392 ++node_index)
393 {
394 MDNode *metadata_node = named_metadata->getOperand(node_index);
395
396 if (!metadata_node)
397 return NULL;
398
399 if (metadata_node->getNumOperands() != 2)
400 continue;
401
402 if (metadata_node->getOperand(0) != global_val)
403 continue;
404
405 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
406
407 if (!constant_int)
408 return NULL;
409
410 uintptr_t ptr = constant_int->getZExtValue();
411
412 return reinterpret_cast<clang::NamedDecl *>(ptr);
413 }
414
415 return NULL;
416}
417
Sean Callanan47dc4572011-09-15 02:13:07 +0000418clang::NamedDecl *
419IRForTarget::DeclForGlobal (GlobalValue *global_val)
420{
421 return DeclForGlobal(global_val, m_module);
422}
423
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000424void
425IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
426 const lldb_private::ConstString &name,
427 lldb_private::TypeFromParser type)
428{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000429 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
430 {
431 switch (init_expr->getOpcode())
432 {
433 default:
434 return;
435 case Instruction::IntToPtr:
436 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
437 return;
438 }
439 }
440 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
441 {
442 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
443 }
444}
445
446void
Sean Callananc0492742011-05-23 21:40:23 +0000447IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000448{
449 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
450
451 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000452 return;
453
Sean Callanan696cf5f2011-05-07 01:06:41 +0000454 LoadInst *original_load = NULL;
455
456 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
457 current_value != NULL;
458 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000459 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000460 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
461 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
462
463 if (cast_inst)
464 {
465 next_value = cast_inst->getOperand(0);
466 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000467 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000468 {
469 if (isa<LoadInst>(load_inst->getPointerOperand()))
470 {
471 next_value = load_inst->getPointerOperand();
472 }
473 else
474 {
475 original_load = load_inst;
476 break;
477 }
478 }
479 else
480 {
481 return;
482 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000483 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000484
485 Value *loaded_value = original_load->getPointerOperand();
486 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
487
488 if (!loaded_global)
489 return;
490
Sean Callananc0492742011-05-23 21:40:23 +0000491 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000492
493 if (!loaded_decl)
494 return;
495
496 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
497
498 if (!loaded_var)
499 return;
500
501 if (log)
502 {
503 lldb_private::StreamString type_desc_stream;
504 type.DumpTypeDescription(&type_desc_stream);
505
506 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
507 }
508
509 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000510}
511
512bool
Sean Callananc0492742011-05-23 21:40:23 +0000513IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000514{
Greg Claytone005f2c2010-11-06 01:53:30 +0000515 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000516
Sean Callanane8a59a82010-09-13 21:34:21 +0000517 if (!m_resolve_vars)
518 return true;
519
520 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000521
Sean Callananc0492742011-05-23 21:40:23 +0000522 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000523
Sean Callanan9b6898f2011-07-30 02:42:06 +0000524 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000525 const char *result_name = NULL;
526
527 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
528 vi != ve;
529 ++vi)
530 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000531 result_name_str = vi->first().str();
532 const char *value_name = result_name_str.c_str();
533
534 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
535 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000536 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000537 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000538 m_result_is_pointer = true;
539 break;
540 }
541
Sean Callanan9b6898f2011-07-30 02:42:06 +0000542 if (strstr(value_name, "$__lldb_expr_result") &&
543 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000544 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000545 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000546 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000547 break;
548 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000549 }
550
551 if (!result_name)
552 {
553 if (log)
554 log->PutCString("Couldn't find result variable");
555
556 return true;
557 }
558
Sean Callananc04743d2010-09-28 21:13:03 +0000559 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000560 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000561
Sean Callananc0492742011-05-23 21:40:23 +0000562 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000563
564 if (!result_value)
565 {
566 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000567 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000568
Sean Callanan97c924e2011-01-27 01:07:04 +0000569 if (m_error_stream)
570 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
571
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000572 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000573 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000574
Sean Callanan82b74c82010-08-12 01:56:52 +0000575 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000576 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000577
578 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
579
580 if (!result_global)
581 {
582 if (log)
583 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000584
585 if (m_error_stream)
586 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
587
Sean Callanan82b74c82010-08-12 01:56:52 +0000588 return false;
589 }
590
Sean Callananc0492742011-05-23 21:40:23 +0000591 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000592 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000593 {
594 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000595 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000596
Sean Callanan97c924e2011-01-27 01:07:04 +0000597 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000598 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000599
Sean Callanan82b74c82010-08-12 01:56:52 +0000600 return false;
601 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000602
Sean Callanan696cf5f2011-05-07 01:06:41 +0000603 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000604 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000605 std::string decl_desc_str;
606 raw_string_ostream decl_desc_stream(decl_desc_str);
607 result_decl->print(decl_desc_stream);
608 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000609
Sean Callanan696cf5f2011-05-07 01:06:41 +0000610 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000611 }
612
Sean Callanan696cf5f2011-05-07 01:06:41 +0000613 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
614 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000615 {
616 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000617 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000618
619 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000620 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000621
Sean Callanan82b74c82010-08-12 01:56:52 +0000622 return false;
623 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000624
Sean Callanan82b74c82010-08-12 01:56:52 +0000625 // Get the next available result name from m_decl_map and create the persistent
626 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000627
Sean Callanan696cf5f2011-05-07 01:06:41 +0000628 // If the result is an Lvalue, it is emitted as a pointer; see
629 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000630 if (m_result_is_pointer)
631 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000632 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000633 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan6a925532011-01-13 08:53:35 +0000634
Sean Callanan21f2e192011-12-14 01:13:04 +0000635 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
636 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan4fdf7952011-12-08 19:04:34 +0000637
638 if (pointer_pointertype)
639 {
640 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
641
642 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
643 &result_decl->getASTContext());
644 }
645 else if (pointer_objcobjpointertype)
646 {
647 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
648
649 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
650 &result_decl->getASTContext());
651 }
652 else
Sean Callanan6a925532011-01-13 08:53:35 +0000653 {
654 if (log)
655 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000656
657 if (m_error_stream)
658 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
659
Sean Callanan6a925532011-01-13 08:53:35 +0000660 return false;
661 }
Sean Callanan6a925532011-01-13 08:53:35 +0000662 }
663 else
664 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000665 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000666 &result_decl->getASTContext());
667 }
668
669 if (m_result_type.GetClangTypeBitWidth() == 0)
670 {
671 lldb_private::StreamString type_desc_stream;
672 m_result_type.DumpTypeDescription(&type_desc_stream);
673
674 if (log)
675 log->Printf("Result type has size 0");
676
677 if (m_error_stream)
Sean Callananb6f9ee72011-12-21 23:44:05 +0000678 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000679 type_desc_stream.GetData());
Sean Callananb6f9ee72011-12-21 23:44:05 +0000680 return false;
Sean Callanan6a925532011-01-13 08:53:35 +0000681 }
682
Sean Callanan696cf5f2011-05-07 01:06:41 +0000683 if (log)
684 {
685 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000686 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000687
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000688 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan696cf5f2011-05-07 01:06:41 +0000689 }
690
Sean Callanan6a925532011-01-13 08:53:35 +0000691 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000692
693 if (log)
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000694 log->Printf("Creating a new result global: \"%s\" with size 0x%x",
695 m_result_name.GetCString(),
696 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanan82b74c82010-08-12 01:56:52 +0000697
698 // Construct a new result global and set up its metadata
699
Sean Callananc0492742011-05-23 21:40:23 +0000700 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000701 result_global->getType()->getElementType(),
702 false, /* not constant */
703 GlobalValue::ExternalLinkage,
704 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000705 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000706
707 // It's too late in compilation to create a new VarDecl for this, but we don't
708 // need to. We point the metadata at the old VarDecl. This creates an odd
709 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000710 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000711 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
712 // fixed up.
713
Sean Callananc0492742011-05-23 21:40:23 +0000714 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000715 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000716 false);
717
718 llvm::Value* values[2];
719 values[0] = new_result_global;
720 values[1] = new_constant_int;
721
Sean Callanan0de254a2011-05-15 22:34:38 +0000722 ArrayRef<Value*> value_ref(values, 2);
723
Sean Callananc0492742011-05-23 21:40:23 +0000724 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
725 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000726 named_metadata->addOperand(persistent_global_md);
727
728 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000729 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000730 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000731 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000732
733 if (result_global->hasNUses(0))
734 {
735 // We need to synthesize a store for this variable, because otherwise
736 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000737
Greg Clayton8de27c72010-10-15 22:48:33 +0000738 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000739 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
740
741 if (!first_entry_instruction)
742 return false;
743
744 if (!result_global->hasInitializer())
745 {
746 if (log)
747 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000748
749 if (m_error_stream)
750 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
751
Sean Callanan2e2db532010-09-07 22:43:19 +0000752 return false;
753 }
754
755 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000756
757 // Here we write the initializer into a result variable assuming it
758 // can be computed statically.
759
760 if (!m_has_side_effects)
761 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000762 //MaybeSetConstantResult (initializer,
763 // m_result_name,
764 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000765 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000766
Greg Clayton2c344ca2011-02-05 02:28:58 +0000767 StoreInst *synthesized_store = new StoreInst(initializer,
768 new_result_global,
769 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000770
771 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000772 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000773 }
774 else
775 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000776 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000777 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000778 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000779 }
780
Sean Callanan2e2db532010-09-07 22:43:19 +0000781 result_global->replaceAllUsesWith(new_result_global);
782 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000783
784 if (!m_const_result)
Sean Callanan5a55c7a2011-11-18 03:28:09 +0000785 if (!m_decl_map->AddPersistentVariable(result_decl,
786 m_result_name,
787 m_result_type,
788 true,
789 m_result_is_pointer))
790 return false;
Sean Callanan2e2db532010-09-07 22:43:19 +0000791
Sean Callanan82b74c82010-08-12 01:56:52 +0000792 result_global->eraseFromParent();
793
794 return true;
795}
796
Johnny Chen58021cc2011-08-09 23:10:20 +0000797#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000798static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000799{
800 if (!depth)
801 return;
802
803 depth--;
804
Johnny Chen58021cc2011-08-09 23:10:20 +0000805 if (log)
806 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000807
Greg Clayton3c7feb42010-11-19 01:05:25 +0000808 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000809 ui != ue;
810 ++ui)
811 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000812 if (log)
813 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000814 DebugUsers(log, *ui, depth);
815 }
816
Johnny Chen58021cc2011-08-09 23:10:20 +0000817 if (log)
818 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000819}
Johnny Chen58021cc2011-08-09 23:10:20 +0000820#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000821
822bool
Sean Callananc0492742011-05-23 21:40:23 +0000823IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000824 llvm::GlobalVariable *cstr,
825 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000826{
827 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
828
Sean Callanan9b6898f2011-07-30 02:42:06 +0000829 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000830
Sean Callanan9b6898f2011-07-30 02:42:06 +0000831 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
832 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000833 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000834 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
835 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000836
837 if (!m_CFStringCreateWithBytes)
838 {
839 lldb::addr_t CFStringCreateWithBytes_addr;
840
841 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
842
843 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
844 {
845 if (log)
846 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
847
Sean Callanan97c924e2011-01-27 01:07:04 +0000848 if (m_error_stream)
849 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
850
Sean Callanan6ba533e2010-11-17 23:00:36 +0000851 return false;
852 }
853
854 if (log)
855 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
856
857 // Build the function type:
858 //
859 // CFStringRef CFStringCreateWithBytes (
860 // CFAllocatorRef alloc,
861 // const UInt8 *bytes,
862 // CFIndex numBytes,
863 // CFStringEncoding encoding,
864 // Boolean isExternalRepresentation
865 // );
866 //
867 // We make the following substitutions:
868 //
869 // CFStringRef -> i8*
870 // CFAllocatorRef -> i8*
871 // UInt8 * -> i8*
872 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
873 // CFStringEncoding -> i32
874 // Boolean -> i8
875
Sean Callanan9b6898f2011-07-30 02:42:06 +0000876 Type *arg_type_array[5];
877
878 arg_type_array[0] = i8_ptr_ty;
879 arg_type_array[1] = i8_ptr_ty;
880 arg_type_array[2] = intptr_ty;
881 arg_type_array[3] = i32_ty;
882 arg_type_array[4] = i8_ty;
883
884 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
885
Sean Callananc0492742011-05-23 21:40:23 +0000886 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000887
888 // Build the constant containing the pointer to the function
889 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
890 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
891 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
892 }
893
Sean Callanan58baaad2011-07-08 00:39:14 +0000894 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000895
896 if (cstr)
897 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000898
Sean Callanan6ba533e2010-11-17 23:00:36 +0000899 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000900 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
901 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000902 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
903 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
904
Sean Callanan9b6898f2011-07-30 02:42:06 +0000905 Value *argument_array[5];
906
907 argument_array[0] = alloc_arg;
908 argument_array[1] = bytes_arg;
909 argument_array[2] = numBytes_arg;
910 argument_array[3] = encoding_arg;
911 argument_array[4] = isExternal_arg;
912
913 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000914
915 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000916 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000917 "CFStringCreateWithBytes",
918 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000919
Greg Clayton3c7feb42010-11-19 01:05:25 +0000920 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000921 {
922 if (log)
923 log->PutCString("Couldn't replace the NSString with the result of the call");
924
Sean Callanan97c924e2011-01-27 01:07:04 +0000925 if (m_error_stream)
926 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
927
Sean Callanan6ba533e2010-11-17 23:00:36 +0000928 return false;
929 }
930
Greg Clayton3c7feb42010-11-19 01:05:25 +0000931 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000932
933 return true;
934}
935
936bool
Sean Callananc0492742011-05-23 21:40:23 +0000937IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000938{
939 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
940
Sean Callananc0492742011-05-23 21:40:23 +0000941 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000942
Greg Clayton3c7feb42010-11-19 01:05:25 +0000943 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000944 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
945
946 if (!FirstEntryInstruction)
947 {
948 if (log)
949 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
950
Sean Callanan97c924e2011-01-27 01:07:04 +0000951 if (m_error_stream)
952 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
953
Sean Callanan6ba533e2010-11-17 23:00:36 +0000954 return false;
955 }
956
957 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
958 vi != ve;
959 ++vi)
960 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000961 std::string value_name = vi->first().str();
962 const char *value_name_cstr = value_name.c_str();
963
964 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000965 {
966 Value *nsstring_value = vi->second;
967
968 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
969
970 if (!nsstring_global)
971 {
972 if (log)
973 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000974
975 if (m_error_stream)
976 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
977
Sean Callanan6ba533e2010-11-17 23:00:36 +0000978 return false;
979 }
980
981 if (!nsstring_global->hasInitializer())
982 {
983 if (log)
984 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000985
986 if (m_error_stream)
987 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
988
Sean Callanan6ba533e2010-11-17 23:00:36 +0000989 return false;
990 }
991
992 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
993
994 if (!nsstring_struct)
995 {
996 if (log)
997 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000998
999 if (m_error_stream)
1000 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
1001
Sean Callanan6ba533e2010-11-17 23:00:36 +00001002 return false;
1003 }
1004
1005 // We expect the following structure:
1006 //
1007 // struct {
1008 // int *isa;
1009 // int flags;
1010 // char *str;
1011 // long length;
1012 // };
1013
1014 if (nsstring_struct->getNumOperands() != 4)
1015 {
1016 if (log)
1017 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 +00001018
1019 if (m_error_stream)
1020 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
1021
Sean Callanan6ba533e2010-11-17 23:00:36 +00001022 return false;
1023 }
1024
1025 Constant *nsstring_member = nsstring_struct->getOperand(2);
1026
1027 if (!nsstring_member)
1028 {
1029 if (log)
1030 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +00001031
1032 if (m_error_stream)
1033 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1034
Sean Callanan6ba533e2010-11-17 23:00:36 +00001035 return false;
1036 }
1037
1038 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1039
1040 if (!nsstring_expr)
1041 {
1042 if (log)
1043 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +00001044
1045 if (m_error_stream)
1046 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1047
Sean Callanan6ba533e2010-11-17 23:00:36 +00001048 return false;
1049 }
1050
1051 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1052 {
1053 if (log)
1054 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 +00001055
1056 if (m_error_stream)
1057 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1058
Sean Callanan6ba533e2010-11-17 23:00:36 +00001059 return false;
1060 }
1061
1062 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1063
1064 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1065
1066 if (!cstr_global)
1067 {
1068 if (log)
1069 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001070
1071 if (m_error_stream)
1072 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 +00001073
Sean Callanan6ba533e2010-11-17 23:00:36 +00001074 return false;
1075 }
1076
1077 if (!cstr_global->hasInitializer())
1078 {
1079 if (log)
1080 log->PutCString("NSString initializer's str element does not have an initializer");
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 initialized data\n");
1084
Sean Callanan6ba533e2010-11-17 23:00:36 +00001085 return false;
1086 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001087
1088 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001089 if (!cstr_array)
1090 {
1091 if (log)
1092 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001093
1094 if (m_error_stream)
1095 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1096
Sean Callanan6ba533e2010-11-17 23:00:36 +00001097 return false;
1098 }
1099
1100 if (!cstr_array->isCString())
1101 {
1102 if (log)
1103 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +00001104
1105 if (m_error_stream)
1106 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1107
Sean Callanan6ba533e2010-11-17 23:00:36 +00001108 return false;
1109 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001110 */
1111
1112 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001113
1114 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001115 {
1116 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001117 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001118 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001119 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001120 }
1121
1122 if (!cstr_array)
1123 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001124
Sean Callananc0492742011-05-23 21:40:23 +00001125 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001126 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001127 if (log)
1128 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001129
1130 // We don't print an error message here because RewriteObjCConstString has done so for us.
1131
Sean Callanan6ba533e2010-11-17 23:00:36 +00001132 return false;
1133 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001134 }
1135 }
1136
1137 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1138 vi != ve;
1139 ++vi)
1140 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001141 std::string value_name = vi->first().str();
1142 const char *value_name_cstr = value_name.c_str();
1143
1144 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001145 {
1146 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1147
1148 if (!gv)
1149 {
1150 if (log)
1151 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001152
1153 if (m_error_stream)
1154 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1155
Sean Callanan6ba533e2010-11-17 23:00:36 +00001156 return false;
1157 }
1158
1159 gv->eraseFromParent();
1160
1161 break;
1162 }
1163 }
1164
1165 return true;
1166}
1167
Greg Clayton3c7feb42010-11-19 01:05:25 +00001168static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001169{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001170 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001171
Greg Clayton3c7feb42010-11-19 01:05:25 +00001172 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001173 return false;
1174
1175 return true;
1176}
1177
Sean Callanan97c924e2011-01-27 01:07:04 +00001178// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001179bool
Sean Callananc0492742011-05-23 21:40:23 +00001180IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001181{
Greg Claytone005f2c2010-11-06 01:53:30 +00001182 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001183
1184 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1185
1186 if (!load)
1187 return false;
1188
1189 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1190 //
1191 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1192 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1193 //
1194 // where %obj is the object pointer and %tmp is the selector.
1195 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001196 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1197 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001198
1199 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1200
1201 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1202
1203 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1204 return false;
1205
1206 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1207
1208 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1209
1210 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1211 return false;
1212
1213 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1214
1215 if (!osr_initializer_base)
1216 return false;
1217
1218 // Find the string's initializer (a ConstantArray) and get the string from it
1219
1220 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1221
1222 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1223 return false;
1224
1225 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1226
1227 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1228
1229 if (!omvn_initializer_array->isString())
1230 return false;
1231
1232 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1233
1234 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001235 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001236
1237 // Construct a call to sel_registerName
1238
1239 if (!m_sel_registerName)
1240 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001241 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001242
Greg Clayton8de27c72010-10-15 22:48:33 +00001243 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001244 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001245 return false;
1246
Sean Callananc2c6f772010-10-26 00:31:56 +00001247 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001248 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001249
Sean Callananf5857a02010-07-31 01:32:05 +00001250 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1251
1252 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001253 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001254 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001255 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001256
Sean Callanan9b6898f2011-07-30 02:42:06 +00001257 Type *type_array[1];
1258
1259 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1260
1261 ArrayRef<Type *> srN_arg_types(type_array, 1);
1262
Sean Callananf5857a02010-07-31 01:32:05 +00001263 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1264
1265 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001266 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1267 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001268 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001269 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001270 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1271 }
1272
Sean Callanan9b6898f2011-07-30 02:42:06 +00001273 Value *argument_array[1];
1274
Sean Callananc0492742011-05-23 21:40:23 +00001275 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001276
Sean Callanan9b6898f2011-07-30 02:42:06 +00001277 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001278
Sean Callanan9b6898f2011-07-30 02:42:06 +00001279 ArrayRef<Value *> srN_arguments(argument_array, 1);
1280
Sean Callananf5857a02010-07-31 01:32:05 +00001281 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001282 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001283 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001284 selector_load);
1285
1286 // Replace the load with the call in all users
1287
1288 selector_load->replaceAllUsesWith(srN_call);
1289
1290 selector_load->eraseFromParent();
1291
1292 return true;
1293}
1294
1295bool
Sean Callananc0492742011-05-23 21:40:23 +00001296IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001297{
Greg Claytone005f2c2010-11-06 01:53:30 +00001298 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001299
1300 BasicBlock::iterator ii;
1301
1302 typedef SmallVector <Instruction*, 2> InstrList;
1303 typedef InstrList::iterator InstrIterator;
1304
1305 InstrList selector_loads;
1306
Greg Clayton3c7feb42010-11-19 01:05:25 +00001307 for (ii = basic_block.begin();
1308 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001309 ++ii)
1310 {
1311 Instruction &inst = *ii;
1312
1313 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001314 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001315 selector_loads.push_back(&inst);
1316 }
1317
1318 InstrIterator iter;
1319
1320 for (iter = selector_loads.begin();
1321 iter != selector_loads.end();
1322 ++iter)
1323 {
Sean Callananc0492742011-05-23 21:40:23 +00001324 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001325 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001326 if (m_error_stream)
1327 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1328
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001329 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001330 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001331
Sean Callananf5857a02010-07-31 01:32:05 +00001332 return false;
1333 }
1334 }
1335
1336 return true;
1337}
1338
Sean Callanan97c924e2011-01-27 01:07:04 +00001339// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001340bool
Sean Callananc0492742011-05-23 21:40:23 +00001341IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001342{
Sean Callanan97678d12011-01-13 21:23:32 +00001343 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1344
Sean Callanana48fe162010-08-11 03:57:18 +00001345 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1346
1347 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1348
1349 if (!alloc_md || !alloc_md->getNumOperands())
1350 return false;
1351
1352 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1353
1354 if (!constant_int)
1355 return false;
1356
1357 // We attempt to register this as a new persistent variable with the DeclMap.
1358
1359 uintptr_t ptr = constant_int->getZExtValue();
1360
Sean Callanan82b74c82010-08-12 01:56:52 +00001361 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001362
Sean Callanan82b74c82010-08-12 01:56:52 +00001363 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1364 &decl->getASTContext());
1365
Greg Clayton8de27c72010-10-15 22:48:33 +00001366 StringRef decl_name (decl->getName());
1367 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001368 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001369 return false;
1370
Sean Callananc0492742011-05-23 21:40:23 +00001371 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001372 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001373 false, /* not constant */
1374 GlobalValue::ExternalLinkage,
1375 NULL, /* no initializer */
1376 alloc->getName().str().c_str());
1377
1378 // What we're going to do here is make believe this was a regular old external
1379 // variable. That means we need to make the metadata valid.
1380
Sean Callananc0492742011-05-23 21:40:23 +00001381 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001382
1383 llvm::Value* values[2];
1384 values[0] = persistent_global;
1385 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001386
1387 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001388
Sean Callananc0492742011-05-23 21:40:23 +00001389 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001390 named_metadata->addOperand(persistent_global_md);
1391
Sean Callanan97678d12011-01-13 21:23:32 +00001392 // Now, since the variable is a pointer variable, we will drop in a load of that
1393 // pointer variable.
1394
1395 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1396
1397 if (log)
1398 log->Printf("Replacing \"%s\" with \"%s\"",
1399 PrintValue(alloc).c_str(),
1400 PrintValue(persistent_load).c_str());
1401
1402 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001403 alloc->eraseFromParent();
1404
1405 return true;
1406}
1407
1408bool
Sean Callananc0492742011-05-23 21:40:23 +00001409IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001410{
Sean Callanane8a59a82010-09-13 21:34:21 +00001411 if (!m_resolve_vars)
1412 return true;
1413
Greg Claytone005f2c2010-11-06 01:53:30 +00001414 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001415
1416 BasicBlock::iterator ii;
1417
1418 typedef SmallVector <Instruction*, 2> InstrList;
1419 typedef InstrList::iterator InstrIterator;
1420
1421 InstrList pvar_allocs;
1422
Greg Clayton3c7feb42010-11-19 01:05:25 +00001423 for (ii = basic_block.begin();
1424 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001425 ++ii)
1426 {
1427 Instruction &inst = *ii;
1428
1429 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001430 {
1431 llvm::StringRef alloc_name = alloc->getName();
1432
1433 if (alloc_name.startswith("$") &&
1434 !alloc_name.startswith("$__lldb"))
1435 {
1436 if (alloc_name.find_first_of("0123456789") == 1)
1437 {
1438 if (log)
1439 log->Printf("Rejecting a numeric persistent variable.");
1440
Sean Callanan97c924e2011-01-27 01:07:04 +00001441 if (m_error_stream)
1442 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1443
Sean Callanan237e4742011-01-21 22:30:25 +00001444 return false;
1445 }
1446
Sean Callanana48fe162010-08-11 03:57:18 +00001447 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001448 }
1449 }
Sean Callanana48fe162010-08-11 03:57:18 +00001450 }
1451
1452 InstrIterator iter;
1453
1454 for (iter = pvar_allocs.begin();
1455 iter != pvar_allocs.end();
1456 ++iter)
1457 {
Sean Callananc0492742011-05-23 21:40:23 +00001458 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001459 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001460 if (m_error_stream)
1461 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1462
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001463 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001464 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001465
Sean Callanana48fe162010-08-11 03:57:18 +00001466 return false;
1467 }
1468 }
1469
1470 return true;
1471}
1472
Sean Callananc7ca4662011-10-25 18:36:40 +00001473bool
1474IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1475{
1476 if (!initializer)
1477 return true;
1478
1479 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1480
1481 if (log && log->GetVerbose())
1482 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1483
1484 Type *initializer_type = initializer->getType();
1485
1486 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1487 {
1488 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1489 return true;
1490 }
1491 else if (ConstantArray *array_initializer = dyn_cast<ConstantArray>(initializer))
1492 {
1493 if (array_initializer->isString())
1494 {
1495 std::string array_initializer_string = array_initializer->getAsString();
1496 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1497 }
1498 else
1499 {
1500 ArrayType *array_initializer_type = array_initializer->getType();
1501 Type *array_element_type = array_initializer_type->getElementType();
1502
1503 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1504
1505 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1506 {
1507 if (!MaterializeInitializer(data + (i * element_size), array_initializer->getOperand(i)))
1508 return false;
1509 }
1510 }
1511 return true;
1512 }
1513 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1514 {
1515 StructType *struct_initializer_type = struct_initializer->getType();
1516 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1517
1518 for (int i = 0;
1519 i < struct_initializer->getNumOperands();
1520 ++i)
1521 {
1522 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1523 return false;
1524 }
1525 return true;
1526 }
1527 return false;
1528}
1529
1530bool
1531IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1532{
1533 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1534 return false;
1535
Sean Callananc41606f2011-11-15 19:13:54 +00001536 if (global_variable == m_reloc_placeholder)
1537 return true;
1538
Sean Callananc7ca4662011-10-25 18:36:40 +00001539 uint64_t offset = m_data_allocator->GetStream().GetSize();
1540
1541 llvm::Type *variable_type = global_variable->getType();
1542
1543 Constant *initializer = global_variable->getInitializer();
1544
1545 llvm::Type *initializer_type = initializer->getType();
1546
1547 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1548
1549 lldb_private::DataBufferHeap data(size, '\0');
1550
1551 if (initializer)
1552 if (!MaterializeInitializer(data.GetBytes(), initializer))
1553 return false;
1554
1555 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1556
1557 Constant *new_pointer = BuildRelocation(variable_type, offset);
1558
1559 global_variable->replaceAllUsesWith(new_pointer);
1560
1561 global_variable->eraseFromParent();
1562
1563 return true;
1564}
1565
Sean Callanan97c924e2011-01-27 01:07:04 +00001566// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001567bool
Sean Callananc0492742011-05-23 21:40:23 +00001568IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001569{
Greg Claytone005f2c2010-11-06 01:53:30 +00001570 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001571
1572 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001573 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001574
Greg Clayton8de27c72010-10-15 22:48:33 +00001575 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001576 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001577 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001578 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001579 default:
1580 break;
1581 case Instruction::GetElementPtr:
1582 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001583 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001584 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001585 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001586 }
1587 }
Sean Callananf921cf52010-12-03 19:51:05 +00001588 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001589 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001590 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1591 return MaterializeInternalVariable(global_variable);
1592
Sean Callananc0492742011-05-23 21:40:23 +00001593 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001594
Sean Callananf5857a02010-07-31 01:32:05 +00001595 if (!named_decl)
1596 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001597 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001598 return true;
1599
Sean Callanan7cd46742010-12-06 00:56:39 +00001600 if (!global_variable->hasExternalLinkage())
1601 return true;
1602
Sean Callananf5857a02010-07-31 01:32:05 +00001603 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001604 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001605
Sean Callananf5857a02010-07-31 01:32:05 +00001606 return false;
1607 }
1608
Greg Clayton8de27c72010-10-15 22:48:33 +00001609 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001610
Sean Callanan771131d2010-09-30 21:18:25 +00001611 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001612 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001613
1614 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001615 {
Sean Callanan771131d2010-09-30 21:18:25 +00001616 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001617 ast_context = &value_decl->getASTContext();
1618 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001619 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001620 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001621 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001622 }
Sean Callanan771131d2010-09-30 21:18:25 +00001623
Sean Callanan6a925532011-01-13 08:53:35 +00001624 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001625 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001626
Sean Callanan97678d12011-01-13 21:23:32 +00001627 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001628 {
1629 // The $__lldb_expr_result name indicates the the return value has allocated as
1630 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1631 // accesses to this static variable need to be redirected to the result of dereferencing
1632 // a pointer that is passed in as one of the arguments.
1633 //
1634 // Consequently, when reporting the size of the type, we report a pointer type pointing
1635 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001636 //
1637 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001638
Sean Callanan6a925532011-01-13 08:53:35 +00001639 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1640 value_type = PointerType::get(global_variable->getType(), 0);
1641 }
1642 else
1643 {
1644 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1645 value_type = global_variable->getType();
1646 }
Sean Callanan771131d2010-09-30 21:18:25 +00001647
1648 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1649 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001650
Sean Callanan771131d2010-09-30 21:18:25 +00001651 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001652 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001653 name.c_str(),
1654 qual_type.getAsString().c_str(),
1655 PrintType(value_type).c_str(),
1656 value_size,
1657 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001658
Sean Callanan8bce6652010-07-13 21:41:46 +00001659
Sean Callanan8c127202010-08-23 23:09:38 +00001660 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001661 lldb_private::ConstString (name.c_str()),
1662 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001663 value_size,
1664 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001665 {
1666 if (!global_variable->hasExternalLinkage())
1667 return true;
1668 else
1669 return false;
1670 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001671 }
Sean Callananf3143b72010-12-03 03:02:31 +00001672 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001673 {
1674 if (log)
1675 log->Printf("Function pointers aren't handled right now");
1676
1677 return false;
1678 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001679
1680 return true;
1681}
1682
Sean Callanan97c924e2011-01-27 01:07:04 +00001683// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001684bool
Sean Callananc0492742011-05-23 21:40:23 +00001685IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001686{
Sean Callananc7674af2011-01-17 23:42:46 +00001687 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1688
1689 lldb_private::ConstString name(symbol->getName().str().c_str());
1690
Sean Callanan21ef5bb2011-12-01 02:04:16 +00001691 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc7674af2011-01-17 23:42:46 +00001692
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001693 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001694 {
1695 if (log)
1696 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1697
1698 return false;
1699 }
1700
1701 if (log)
1702 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1703
Sean Callanan9b6898f2011-07-30 02:42:06 +00001704 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001705
Sean Callanan9b6898f2011-07-30 02:42:06 +00001706 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1707 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001708
1709 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1710
1711 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1712
1713 if (log)
1714 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1715
1716 symbol->replaceAllUsesWith(symbol_addr_ptr);
1717
1718 return true;
1719}
1720
1721bool
Sean Callananc0492742011-05-23 21:40:23 +00001722IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001723{
Sean Callanan48443652010-12-02 19:47:57 +00001724 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1725
1726 if (log)
1727 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001728
Sean Callanan6ba533e2010-11-17 23:00:36 +00001729 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001730 op_index < num_ops;
1731 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001732 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001733 {
1734 if (m_error_stream)
1735 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1736
Sean Callanandc27aba2010-10-05 22:26:43 +00001737 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001738 }
1739
Sean Callanandc27aba2010-10-05 22:26:43 +00001740 return true;
1741}
1742
1743bool
Sean Callanan9911d2f2011-11-01 23:38:03 +00001744IRForTarget::HandleObjCClass(Value *classlist_reference)
1745{
1746 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1747
1748 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1749
1750 if (!global_variable)
1751 return false;
1752
1753 Constant *initializer = global_variable->getInitializer();
1754
1755 if (!initializer)
1756 return false;
1757
1758 if (!initializer->hasName())
1759 return false;
1760
1761 StringRef name(initializer->getName());
1762 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton16d21872011-12-03 20:02:42 +00001763 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callanan9911d2f2011-11-01 23:38:03 +00001764
1765 if (log)
1766 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1767
1768 if (class_ptr == LLDB_INVALID_ADDRESS)
1769 return false;
1770
1771 if (global_variable->use_begin() == global_variable->use_end())
1772 return false;
1773
1774 LoadInst *load_instruction = NULL;
1775
1776 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1777 i != e;
1778 ++i)
1779 {
1780 if ((load_instruction = dyn_cast<LoadInst>(*i)))
1781 break;
1782 }
1783
1784 if (!load_instruction)
1785 return false;
1786
1787 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1788 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1789
1790 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1791 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1792
1793 load_instruction->replaceAllUsesWith(class_bitcast);
1794
1795 load_instruction->eraseFromParent();
1796
1797 return true;
1798}
1799
1800bool
Sean Callananc0492742011-05-23 21:40:23 +00001801IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001802{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001803 /////////////////////////////////////////////////////////////////////////
1804 // Prepare the current basic block for execution in the remote process
1805 //
1806
Sean Callanan02fbafa2010-07-27 21:39:39 +00001807 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001808
Greg Clayton3c7feb42010-11-19 01:05:25 +00001809 for (ii = basic_block.begin();
1810 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001811 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001812 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001813 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001814
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001815 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001816
Sean Callanan97c924e2011-01-27 01:07:04 +00001817 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001818 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001819 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001820 }
1821
1822 return true;
1823}
1824
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001825bool
Sean Callananc0492742011-05-23 21:40:23 +00001826IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001827{
Sean Callananae71e302010-11-18 22:21:58 +00001828 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1829
Sean Callananc0492742011-05-23 21:40:23 +00001830 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001831 global != end;
1832 ++global)
1833 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001834 if (log)
1835 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1836 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001837 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001838
Sean Callanan9911d2f2011-11-01 23:38:03 +00001839 std::string global_name = (*global).getName().str();
1840
1841 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc7674af2011-01-17 23:42:46 +00001842 {
Sean Callananc0492742011-05-23 21:40:23 +00001843 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001844 {
1845 if (m_error_stream)
1846 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1847
Sean Callananc7674af2011-01-17 23:42:46 +00001848 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001849 }
Sean Callananc7674af2011-01-17 23:42:46 +00001850 }
Sean Callanan9911d2f2011-11-01 23:38:03 +00001851 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1852 {
1853 if (!HandleObjCClass(global))
1854 {
1855 if (m_error_stream)
1856 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1857
1858 return false;
1859 }
1860 }
Sean Callananc0492742011-05-23 21:40:23 +00001861 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001862 {
Sean Callananc0492742011-05-23 21:40:23 +00001863 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001864 {
1865 if (m_error_stream)
1866 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1867
Sean Callananc7674af2011-01-17 23:42:46 +00001868 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001869 }
Sean Callananc7674af2011-01-17 23:42:46 +00001870 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001871 }
1872
1873 return true;
1874}
1875
Sean Callananc0492742011-05-23 21:40:23 +00001876bool
1877IRForTarget::ReplaceStrings ()
1878{
1879 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1880
1881 if (!m_data_allocator)
1882 return true; // hope for the best; some clients may not want static allocation!
1883
1884 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1885
1886 OffsetsTy offsets;
1887
1888 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1889 gi != ge;
1890 ++gi)
1891 {
1892 GlobalVariable *gv = gi;
1893
1894 if (!gv->hasInitializer())
1895 continue;
1896
1897 Constant *gc = gv->getInitializer();
1898
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001899 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001900
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001901 if (gc->isNullValue())
1902 {
1903 Type *gc_type = gc->getType();
1904
1905 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1906
1907 if (!gc_array_type)
1908 continue;
1909
1910 Type *gc_element_type = gc_array_type->getElementType();
1911
1912 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1913
1914 if (gc_integer_type->getBitWidth() != 8)
1915 continue;
1916
1917 str = "";
1918 }
1919 else
1920 {
1921 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1922
1923 if (!gc_array)
1924 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001925
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001926 if (!gc_array->isCString())
1927 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001928
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001929 if (log)
1930 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001931
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001932 str = gc_array->getAsString();
1933 }
1934
Sean Callananc0492742011-05-23 21:40:23 +00001935 offsets[gv] = m_data_allocator->GetStream().GetSize();
1936
1937 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1938 }
1939
Sean Callanan9b6898f2011-07-30 02:42:06 +00001940 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001941
1942 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1943 oi != oe;
1944 ++oi)
1945 {
1946 GlobalVariable *gv = oi->first;
1947 size_t offset = oi->second;
1948
1949 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1950
1951 if (log)
1952 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1953
1954 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1955 ui != ue;
1956 ++ui)
1957 {
1958 if (log)
1959 log->Printf("Found use %s", PrintValue(*ui).c_str());
1960
1961 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1962 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1963
1964 if (const_expr)
1965 {
1966 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1967 {
1968 if (log)
1969 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1970
1971 return false;
1972 }
1973
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001974 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1975 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1976
1977 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001978 }
1979 else if (store_inst)
1980 {
1981 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1982
1983 store_inst->setOperand(0, bit_cast);
1984 }
1985 else
1986 {
1987 if (log)
1988 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1989
1990 return false;
1991 }
1992 }
1993
1994 gv->eraseFromParent();
1995 }
1996
1997 return true;
1998}
1999
2000bool
2001IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
2002{
2003 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2004
2005 if (!m_data_allocator)
2006 return true;
2007
2008 typedef SmallVector <Value*, 2> ConstantList;
2009 typedef SmallVector <llvm::Instruction*, 2> UserList;
2010 typedef ConstantList::iterator ConstantIterator;
2011 typedef UserList::iterator UserIterator;
2012
2013 ConstantList static_constants;
2014 UserList static_users;
2015
2016 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2017 ii != ie;
2018 ++ii)
2019 {
2020 llvm::Instruction &inst = *ii;
2021
2022 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2023 oi != oe;
2024 ++oi)
2025 {
2026 Value *operand_val = oi->get();
2027
2028 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2029
2030 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
2031 {
2032 static_constants.push_back(operand_val);
2033 static_users.push_back(ii);
2034 }
2035 }
2036 }
2037
2038 ConstantIterator constant_iter;
2039 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00002040
Sean Callananc0492742011-05-23 21:40:23 +00002041 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2042 constant_iter != static_constants.end();
2043 ++constant_iter, ++user_iter)
2044 {
2045 Value *operand_val = *constant_iter;
2046 llvm::Instruction *inst = *user_iter;
2047
2048 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2049
2050 if (operand_constant_fp)
2051 {
2052 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2053 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2054
2055 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2056 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2057
2058 if (log)
2059 {
2060 std::string s;
2061 raw_string_ostream ss(s);
2062 for (size_t index = 0;
2063 index < operand_data_size;
2064 ++index)
2065 {
2066 ss << (uint32_t)operand_raw_data[index];
2067 ss << " ";
2068 }
2069 ss.flush();
2070
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002071 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00002072 }
2073
2074 lldb_private::DataBufferHeap data(operand_data_size, 0);
2075
2076 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
2077 {
2078 uint8_t *data_bytes = data.GetBytes();
2079
2080 for (size_t index = 0;
2081 index < operand_data_size;
2082 ++index)
2083 {
2084 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2085 }
2086 }
2087 else
2088 {
2089 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2090 }
2091
2092 uint64_t offset = m_data_allocator->GetStream().GetSize();
2093
2094 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
2095
Sean Callanan9b6898f2011-07-30 02:42:06 +00002096 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00002097
2098 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2099
2100 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2101
2102 operand_constant_fp->replaceAllUsesWith(fp_load);
2103 }
2104 }
2105
2106 return true;
2107}
2108
Sean Callanan02fbafa2010-07-27 21:39:39 +00002109static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00002110{
Sean Callanan58baaad2011-07-08 00:39:14 +00002111 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00002112
Sean Callanan6ba533e2010-11-17 23:00:36 +00002113 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00002114 return false;
2115
Sean Callanan58baaad2011-07-08 00:39:14 +00002116 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002117
2118 if ((CE = dyn_cast<ConstantExpr>(V)))
2119 {
2120 if (CE->getOpcode() != Instruction::BitCast)
2121 return false;
2122
Sean Callanan6ba533e2010-11-17 23:00:36 +00002123 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002124 }
2125
Sean Callanan6ba533e2010-11-17 23:00:36 +00002126 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00002127
2128 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2129 return false;
2130
2131 return true;
2132}
2133
Sean Callananc0492742011-05-23 21:40:23 +00002134void
2135IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00002136{
Sean Callananc0492742011-05-23 21:40:23 +00002137 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002138
2139 Value::use_iterator ui;
2140
2141 for (ui = guard_load->use_begin();
2142 ui != guard_load->use_end();
2143 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002144 {
Greg Clayton6e713402010-07-30 20:30:44 +00002145 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002146 {
2147 // do nothing for the moment
2148 }
2149 else
2150 {
2151 ui->replaceUsesOfWith(guard_load, zero);
2152 }
2153 }
Sean Callanan45839272010-07-24 01:37:44 +00002154
2155 guard_load->eraseFromParent();
2156}
2157
2158static void ExciseGuardStore(Instruction* guard_store)
2159{
2160 guard_store->eraseFromParent();
2161}
2162
2163bool
Sean Callananc0492742011-05-23 21:40:23 +00002164IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002165{
2166 ///////////////////////////////////////////////////////
2167 // Eliminate any reference to guard variables found.
2168 //
2169
Sean Callanan02fbafa2010-07-27 21:39:39 +00002170 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002171
Sean Callanan02fbafa2010-07-27 21:39:39 +00002172 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002173 typedef InstrList::iterator InstrIterator;
2174
2175 InstrList guard_loads;
2176 InstrList guard_stores;
2177
Greg Clayton3c7feb42010-11-19 01:05:25 +00002178 for (ii = basic_block.begin();
2179 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002180 ++ii)
2181 {
2182 Instruction &inst = *ii;
2183
2184 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2185 if (isGuardVariableRef(load->getPointerOperand()))
2186 guard_loads.push_back(&inst);
2187
2188 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2189 if (isGuardVariableRef(store->getPointerOperand()))
2190 guard_stores.push_back(&inst);
2191 }
2192
2193 InstrIterator iter;
2194
2195 for (iter = guard_loads.begin();
2196 iter != guard_loads.end();
2197 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002198 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002199
2200 for (iter = guard_stores.begin();
2201 iter != guard_stores.end();
2202 ++iter)
2203 ExciseGuardStore(*iter);
2204
2205 return true;
2206}
2207
Sean Callanan97c924e2011-01-27 01:07:04 +00002208// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002209bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002210IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002211{
Greg Claytone005f2c2010-11-06 01:53:30 +00002212 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002213
2214 Value::use_iterator ui;
2215
Sean Callanana48fe162010-08-11 03:57:18 +00002216 SmallVector<User*, 16> users;
2217
2218 // We do this because the use list might change, invalidating our iterator.
2219 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002220 for (ui = old_constant->use_begin();
2221 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002222 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002223 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002224
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002225 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002226 i < users.size();
2227 ++i)
2228 {
2229 User *user = users[i];
2230
Sean Callananbafd6852010-07-14 23:40:29 +00002231 if (Constant *constant = dyn_cast<Constant>(user))
2232 {
2233 // synthesize a new non-constant equivalent of the constant
2234
2235 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2236 {
2237 switch (constant_expr->getOpcode())
2238 {
2239 default:
2240 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002241 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002242 return false;
2243 case Instruction::BitCast:
2244 {
2245 // UnaryExpr
2246 // OperandList[0] is value
2247
2248 Value *s = constant_expr->getOperand(0);
2249
Greg Clayton3c7feb42010-11-19 01:05:25 +00002250 if (s == old_constant)
2251 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002252
Sean Callananc0492742011-05-23 21:40:23 +00002253 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002254
Greg Clayton3c7feb42010-11-19 01:05:25 +00002255 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002256 }
2257 break;
2258 case Instruction::GetElementPtr:
2259 {
2260 // GetElementPtrConstantExpr
2261 // OperandList[0] is base
2262 // OperandList[1]... are indices
2263
2264 Value *ptr = constant_expr->getOperand(0);
2265
Greg Clayton3c7feb42010-11-19 01:05:25 +00002266 if (ptr == old_constant)
2267 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002268
2269 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002270
2271 unsigned operand_index;
2272 unsigned num_operands = constant_expr->getNumOperands();
2273
2274 for (operand_index = 1;
2275 operand_index < num_operands;
2276 ++operand_index)
2277 {
2278 Value *operand = constant_expr->getOperand(operand_index);
2279
Greg Clayton3c7feb42010-11-19 01:05:25 +00002280 if (operand == old_constant)
2281 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002282
Sean Callanan9b6898f2011-07-30 02:42:06 +00002283 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002284 }
2285
Sean Callanan9b6898f2011-07-30 02:42:06 +00002286 ArrayRef <Value*> indices(index_vector);
2287
2288 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002289
Greg Clayton3c7feb42010-11-19 01:05:25 +00002290 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002291 }
2292 break;
2293 }
2294 }
2295 else
2296 {
2297 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002298 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002299 return false;
2300 }
2301 }
2302 else
2303 {
2304 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002305 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002306 }
2307 }
2308
2309 return true;
2310}
2311
Sean Callanan8bce6652010-07-13 21:41:46 +00002312bool
Sean Callananc0492742011-05-23 21:40:23 +00002313IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002314{
Sean Callanane8a59a82010-09-13 21:34:21 +00002315 if (!m_resolve_vars)
2316 return true;
2317
Greg Claytone005f2c2010-11-06 01:53:30 +00002318 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002319
2320 m_decl_map->DoStructLayout();
2321
2322 if (log)
2323 log->Printf("Element arrangement:");
2324
2325 uint32_t num_elements;
2326 uint32_t element_index;
2327
2328 size_t size;
2329 off_t alignment;
2330
2331 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2332 return false;
2333
Greg Clayton3c7feb42010-11-19 01:05:25 +00002334 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002335
Greg Clayton3c7feb42010-11-19 01:05:25 +00002336 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002337 {
2338 if (m_error_stream)
2339 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2340
Sean Callanan8bce6652010-07-13 21:41:46 +00002341 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002342 }
2343
Sean Callanan02fbafa2010-07-27 21:39:39 +00002344 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002345
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002346 if (argument->getName().equals("this"))
2347 {
2348 ++iter;
2349
Greg Clayton3c7feb42010-11-19 01:05:25 +00002350 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002351 {
2352 if (m_error_stream)
2353 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2354
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002355 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002356 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002357
2358 argument = iter;
2359 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002360 else if (argument->getName().equals("self"))
2361 {
2362 ++iter;
2363
2364 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002365 {
2366 if (m_error_stream)
2367 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2368
Sean Callanan3aa7da52010-12-13 22:46:15 +00002369 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002370 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002371
2372 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002373 {
2374 if (m_error_stream)
2375 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2376
Sean Callanan3aa7da52010-12-13 22:46:15 +00002377 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002378 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002379
2380 ++iter;
2381
2382 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002383 {
2384 if (m_error_stream)
2385 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2386
Sean Callanan3aa7da52010-12-13 22:46:15 +00002387 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002388 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002389
2390 argument = iter;
2391 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002392
Greg Clayton8de27c72010-10-15 22:48:33 +00002393 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002394 {
2395 if (m_error_stream)
2396 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2397
Sean Callanan8bce6652010-07-13 21:41:46 +00002398 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002399 }
2400
Sean Callanan8bce6652010-07-13 21:41:46 +00002401 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002402 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002403
Greg Clayton3c7feb42010-11-19 01:05:25 +00002404 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002405 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002406
Sean Callanan6ba533e2010-11-17 23:00:36 +00002407 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002408 {
2409 if (m_error_stream)
2410 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2411
Sean Callanan8bce6652010-07-13 21:41:46 +00002412 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002413 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002414
Sean Callananc0492742011-05-23 21:40:23 +00002415 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002416 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002417
2418 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002419 {
2420 if (m_error_stream)
2421 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2422
Sean Callanan8bce6652010-07-13 21:41:46 +00002423 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002424 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002425
2426 for (element_index = 0; element_index < num_elements; ++element_index)
2427 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002428 const clang::NamedDecl *decl = NULL;
2429 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002430 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002431 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002432
Sean Callanan45690fe2010-08-30 22:17:16 +00002433 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002434 {
2435 if (m_error_stream)
2436 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2437
Sean Callanan8bce6652010-07-13 21:41:46 +00002438 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002439 }
2440
Sean Callanan8bce6652010-07-13 21:41:46 +00002441 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002442 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002443 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002444 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002445 offset);
2446
Sean Callanan9b6898f2011-07-30 02:42:06 +00002447 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002448 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002449
Sean Callananc7ca4662011-10-25 18:36:40 +00002450 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002451 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002452 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002453
Sean Callananc7ca4662011-10-25 18:36:40 +00002454 if (log)
2455 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002456
Sean Callananc7ca4662011-10-25 18:36:40 +00002457 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2458 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2459 // entry in order to produce the static variable that the AST thinks it is accessing.
2460 if (name == m_result_name && !m_result_is_pointer)
2461 {
2462 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2463
2464 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2465
2466 replacement = load;
2467 }
2468 else
2469 {
2470 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2471
2472 replacement = bit_cast;
2473 }
2474
2475 if (Constant *constant = dyn_cast<Constant>(value))
2476 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2477 else
2478 value->replaceAllUsesWith(replacement);
2479
2480 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2481 var->eraseFromParent();
2482 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002483 }
2484
2485 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002486 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002487
2488 return true;
2489}
2490
Sean Callananc0492742011-05-23 21:40:23 +00002491llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002492IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002493 uint64_t offset)
2494{
2495 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2496
Sean Callanan9b6898f2011-07-30 02:42:06 +00002497 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2498 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002499
2500 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002501
2502 llvm::Constant *offset_array[1];
2503
2504 offset_array[0] = offset_int;
2505
2506 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2507
2508 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002509 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2510
2511 return reloc_getbitcast;
2512}
2513
2514bool
2515IRForTarget::CompleteDataAllocation ()
2516{
Sean Callanan47dc4572011-09-15 02:13:07 +00002517 if (!m_data_allocator)
2518 return true;
2519
Sean Callananc0492742011-05-23 21:40:23 +00002520 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2521
2522 if (!m_data_allocator->GetStream().GetSize())
2523 return true;
2524
2525 lldb::addr_t allocation = m_data_allocator->Allocate();
2526
2527 if (log)
2528 {
2529 if (allocation)
2530 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2531 else
2532 log->Printf("Failed to allocate static data");
2533 }
2534
2535 if (!allocation)
2536 return false;
2537
Sean Callanan9b6898f2011-07-30 02:42:06 +00002538 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2539 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002540
2541 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2542 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2543
2544 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2545
2546 m_reloc_placeholder->eraseFromParent();
2547
2548 return true;
2549}
2550
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002551bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002552IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002553{
Greg Claytone005f2c2010-11-06 01:53:30 +00002554 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002555
Sean Callananc0492742011-05-23 21:40:23 +00002556 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002557 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002558
2559 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002560
2561 if (!function)
2562 {
2563 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002564 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002565
2566 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002567 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 +00002568
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002569 return false;
2570 }
Sean Callananc0492742011-05-23 21:40:23 +00002571
2572 if (!FixFunctionLinkage (*function))
2573 {
2574 if (log)
2575 log->Printf("Couldn't fix the linkage for the function");
2576
2577 return false;
2578 }
2579
Sean Callananc7ca4662011-10-25 18:36:40 +00002580 if (log)
2581 {
2582 std::string s;
2583 raw_string_ostream oss(s);
2584
2585 m_module->print(oss, NULL);
2586
2587 oss.flush();
2588
2589 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2590 }
2591
Sean Callanan9b6898f2011-07-30 02:42:06 +00002592 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002593
2594 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2595 intptr_ty,
2596 false /* isConstant */,
2597 GlobalVariable::InternalLinkage,
2598 Constant::getNullValue(intptr_ty),
2599 "reloc_placeholder",
2600 NULL /* InsertBefore */,
2601 false /* ThreadLocal */,
2602 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002603
Sean Callanan02fbafa2010-07-27 21:39:39 +00002604 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002605
Sean Callananc0492742011-05-23 21:40:23 +00002606 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002607
Sean Callanan82b74c82010-08-12 01:56:52 +00002608 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002609 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002610 //
2611
Sean Callananc0492742011-05-23 21:40:23 +00002612 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002613 {
2614 if (log)
2615 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002616
2617 // CreateResultVariable() reports its own errors, so we don't do so here
2618
Sean Callanan82b74c82010-08-12 01:56:52 +00002619 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002620 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002621
2622 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2623 {
2624 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002625 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002626 }
2627
2628 for (bbi = function->begin();
2629 bbi != function->end();
2630 ++bbi)
2631 {
2632 if (!RemoveGuards(*bbi))
2633 {
2634 if (log)
2635 log->Printf("RemoveGuards() failed");
2636
2637 // RemoveGuards() reports its own errors, so we don't do so here
2638
2639 return false;
2640 }
2641
2642 if (!RewritePersistentAllocs(*bbi))
2643 {
2644 if (log)
2645 log->Printf("RewritePersistentAllocs() failed");
2646
2647 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2648
2649 return false;
2650 }
2651 }
2652
2653 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2654 {
2655 IRInterpreter interpreter (*m_decl_map,
2656 m_error_stream);
2657
2658 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2659 {
2660 m_interpret_success = true;
2661 return true;
2662 }
2663 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002664
Sean Callanan7b8eb762011-11-01 17:33:54 +00002665 if (log && log->GetVerbose())
Sean Callananc0492742011-05-23 21:40:23 +00002666 {
2667 std::string s;
2668 raw_string_ostream oss(s);
2669
2670 m_module->print(oss, NULL);
2671
2672 oss.flush();
2673
2674 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2675 }
2676
Sean Callanan6ba533e2010-11-17 23:00:36 +00002677 ///////////////////////////////////////////////////////////////////////////////
2678 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2679 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002680
Sean Callananc0492742011-05-23 21:40:23 +00002681 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002682 {
2683 if (log)
2684 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002685
2686 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2687
Sean Callanan6ba533e2010-11-17 23:00:36 +00002688 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002689 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002690
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002691 ///////////////////////////////
2692 // Resolve function pointers
2693 //
2694
2695 if (!ResolveFunctionPointers(llvm_module, *function))
2696 {
2697 if (log)
2698 log->Printf("ResolveFunctionPointers() failed");
2699
2700 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2701
2702 return false;
2703 }
2704
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002705 for (bbi = function->begin();
2706 bbi != function->end();
2707 ++bbi)
2708 {
Sean Callananc0492742011-05-23 21:40:23 +00002709 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002710 {
2711 if (log)
2712 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002713
2714 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2715
Sean Callanana48fe162010-08-11 03:57:18 +00002716 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002717 }
Sean Callanana48fe162010-08-11 03:57:18 +00002718
Sean Callananc0492742011-05-23 21:40:23 +00002719 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002720 {
2721 if (log)
2722 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002723
2724 // ResolveCalls() reports its own errors, so we don't do so here
2725
Sean Callanan8bce6652010-07-13 21:41:46 +00002726 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002727 }
Sean Callananc0492742011-05-23 21:40:23 +00002728
2729 if (!ReplaceStaticLiterals(*bbi))
2730 {
2731 if (log)
2732 log->Printf("ReplaceStaticLiterals() failed");
2733
2734 return false;
2735 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002736 }
2737
Sean Callanan771131d2010-09-30 21:18:25 +00002738 ///////////////////////////////
2739 // Run function-level passes
2740 //
2741
Sean Callananc0492742011-05-23 21:40:23 +00002742 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002743 {
2744 if (log)
2745 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002746
2747 // ResolveExternals() reports its own errors, so we don't do so here
2748
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002749 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002750 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002751
Sean Callananc0492742011-05-23 21:40:23 +00002752 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002753 {
2754 if (log)
2755 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002756
2757 // ReplaceVariables() reports its own errors, so we don't do so here
2758
Sean Callanan771131d2010-09-30 21:18:25 +00002759 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002760 }
Sean Callanan771131d2010-09-30 21:18:25 +00002761
Sean Callananc0492742011-05-23 21:40:23 +00002762 if (!ReplaceStrings())
2763 {
2764 if (log)
2765 log->Printf("ReplaceStrings() failed");
2766
2767 return false;
2768 }
2769
2770 if (!CompleteDataAllocation())
2771 {
2772 if (log)
2773 log->Printf("CompleteDataAllocation() failed");
2774
2775 return false;
2776 }
2777
Sean Callanan7b8eb762011-11-01 17:33:54 +00002778 if (log && log->GetVerbose())
Sean Callanan8bce6652010-07-13 21:41:46 +00002779 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002780 std::string s;
2781 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002782
Sean Callananc0492742011-05-23 21:40:23 +00002783 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002784
2785 oss.flush();
2786
Greg Claytonb5037af2010-11-15 01:47:11 +00002787 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002788 }
2789
2790 return true;
2791}
2792
2793void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002794IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002795{
2796}
2797
2798PassManagerType
2799IRForTarget::getPotentialPassManagerType() const
2800{
2801 return PMT_ModulePassManager;
2802}