blob: fa4b01746940b815a10b1ddd95a511a2286a752b [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
110 std::string name = llvm_function.getNameStr();
111
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())
144 ptr_name = store_ptr->getNameStr();
145
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;
208 }
209
210 if (log && name)
211 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
212 }
213 else
214 {
215 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
216 }
217
218 // Find the address of the function.
219
220 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000221
222 if (fun_decl)
223 {
Sean Callananc7ca4662011-10-25 18:36:40 +0000224 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000225 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000226 lldb_private::ConstString alternate_mangling_const_str;
227 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
228 if (!found_it)
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000229 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000230 // Check for an alternate mangling for "std::basic_string<char>"
231 // that is part of the itanium C++ name mangling scheme
232 const char *name_cstr = name.GetCString();
233 if (strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
234 {
235 std::string alternate_mangling("_ZNKSs");
236 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
237 alternate_mangling_const_str.SetCString(alternate_mangling.c_str());
238 found_it = m_decl_map->GetFunctionAddress (alternate_mangling_const_str, fun_addr);
239 }
240 }
241
242 if (!found_it)
243 {
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000244 if (log)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000245 {
246 if (alternate_mangling_const_str)
247 log->Printf("Function \"%s\" (alternate name \"%s\") has no address", name.GetCString(), alternate_mangling_const_str.GetCString());
248 else
249 log->Printf("Function \"%s\" had no address", name.GetCString());
250 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000251
252 if (m_error_stream)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000253 {
254 if (alternate_mangling_const_str)
255 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());
256 else
257 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n", name.GetCString());
258 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000259 return false;
260 }
261 }
262 }
263 else
264 {
265 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
266 {
267 if (log)
268 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
269
270 if (m_error_stream)
271 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
272
273 return false;
274 }
275 }
276
277 if (log)
278 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), fun_addr);
279
280 return true;
281}
282
283llvm::Constant *
284IRForTarget::BuildFunctionPointer (llvm::Type *type,
285 uint64_t ptr)
286{
287 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
288 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
290 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
292}
293
Sean Callanan715f6b02011-10-31 22:11:40 +0000294void
295IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
297 const char *name)
298{
299 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
300
301 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
302 i != e;
303 ++i)
304 {
305 Value *user = *i;
306
307 if (Instruction *user_inst = dyn_cast<Instruction>(user))
308 {
309 Constant *name_array = ConstantArray::get(context, StringRef(name));
310
311 ArrayRef<Value *> md_values(name_array);
312
313 MDNode *metadata = MDNode::get(context, md_values);
314
315 user_inst->setMetadata("lldb.call.realName", metadata);
316 }
317 else
318 {
319 RegisterFunctionMetadata (context, user, name);
320 }
321 }
322}
323
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000324bool
325IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
326 llvm::Function &llvm_function)
327{
328 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
329
330 for (llvm::Module::iterator fi = llvm_module.begin();
331 fi != llvm_module.end();
332 ++fi)
333 {
334 Function *fun = fi;
335
336 bool is_decl = fun->isDeclaration();
337
338 if (log)
339 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getNameStr().c_str());
340
341 if (!is_decl)
342 continue;
343
344 if (fun->hasNUses(0))
345 continue; // ignore
346
347 uint64_t addr = LLDB_INVALID_ADDRESS;
348 lldb_private::ConstString name;
349 Constant **value_ptr = NULL;
350
351 if (!GetFunctionAddress(fun,
352 addr,
353 name,
354 value_ptr))
355 return false; // GetFunctionAddress reports its own errors
356
357 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
358
Sean Callanan715f6b02011-10-31 22:11:40 +0000359 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
360
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000361 if (value_ptr)
362 *value_ptr = value;
363
364 fun->replaceAllUsesWith(value);
365 }
366
367 return true;
368}
369
Sean Callanan47dc4572011-09-15 02:13:07 +0000370
Sean Callanan696cf5f2011-05-07 01:06:41 +0000371clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000372IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000373{
374 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
375
Sean Callanan47dc4572011-09-15 02:13:07 +0000376 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000377
378 if (!named_metadata)
379 return NULL;
380
381 unsigned num_nodes = named_metadata->getNumOperands();
382 unsigned node_index;
383
384 for (node_index = 0;
385 node_index < num_nodes;
386 ++node_index)
387 {
388 MDNode *metadata_node = named_metadata->getOperand(node_index);
389
390 if (!metadata_node)
391 return NULL;
392
393 if (metadata_node->getNumOperands() != 2)
394 continue;
395
396 if (metadata_node->getOperand(0) != global_val)
397 continue;
398
399 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
400
401 if (!constant_int)
402 return NULL;
403
404 uintptr_t ptr = constant_int->getZExtValue();
405
406 return reinterpret_cast<clang::NamedDecl *>(ptr);
407 }
408
409 return NULL;
410}
411
Sean Callanan47dc4572011-09-15 02:13:07 +0000412clang::NamedDecl *
413IRForTarget::DeclForGlobal (GlobalValue *global_val)
414{
415 return DeclForGlobal(global_val, m_module);
416}
417
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000418void
419IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
420 const lldb_private::ConstString &name,
421 lldb_private::TypeFromParser type)
422{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000423 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
424 {
425 switch (init_expr->getOpcode())
426 {
427 default:
428 return;
429 case Instruction::IntToPtr:
430 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
431 return;
432 }
433 }
434 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
435 {
436 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
437 }
438}
439
440void
Sean Callananc0492742011-05-23 21:40:23 +0000441IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000442{
443 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
444
445 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000446 return;
447
Sean Callanan696cf5f2011-05-07 01:06:41 +0000448 LoadInst *original_load = NULL;
449
450 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
451 current_value != NULL;
452 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000453 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000454 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
455 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
456
457 if (cast_inst)
458 {
459 next_value = cast_inst->getOperand(0);
460 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000461 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000462 {
463 if (isa<LoadInst>(load_inst->getPointerOperand()))
464 {
465 next_value = load_inst->getPointerOperand();
466 }
467 else
468 {
469 original_load = load_inst;
470 break;
471 }
472 }
473 else
474 {
475 return;
476 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000477 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000478
479 Value *loaded_value = original_load->getPointerOperand();
480 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
481
482 if (!loaded_global)
483 return;
484
Sean Callananc0492742011-05-23 21:40:23 +0000485 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000486
487 if (!loaded_decl)
488 return;
489
490 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
491
492 if (!loaded_var)
493 return;
494
495 if (log)
496 {
497 lldb_private::StreamString type_desc_stream;
498 type.DumpTypeDescription(&type_desc_stream);
499
500 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
501 }
502
503 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000504}
505
506bool
Sean Callananc0492742011-05-23 21:40:23 +0000507IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000508{
Greg Claytone005f2c2010-11-06 01:53:30 +0000509 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000510
Sean Callanane8a59a82010-09-13 21:34:21 +0000511 if (!m_resolve_vars)
512 return true;
513
514 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000515
Sean Callananc0492742011-05-23 21:40:23 +0000516 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000517
Sean Callanan9b6898f2011-07-30 02:42:06 +0000518 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000519 const char *result_name = NULL;
520
521 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
522 vi != ve;
523 ++vi)
524 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000525 result_name_str = vi->first().str();
526 const char *value_name = result_name_str.c_str();
527
528 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
529 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000530 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000531 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000532 m_result_is_pointer = true;
533 break;
534 }
535
Sean Callanan9b6898f2011-07-30 02:42:06 +0000536 if (strstr(value_name, "$__lldb_expr_result") &&
537 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000538 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000539 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000540 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000541 break;
542 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000543 }
544
545 if (!result_name)
546 {
547 if (log)
548 log->PutCString("Couldn't find result variable");
549
550 return true;
551 }
552
Sean Callananc04743d2010-09-28 21:13:03 +0000553 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000554 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000555
Sean Callananc0492742011-05-23 21:40:23 +0000556 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000557
558 if (!result_value)
559 {
560 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000561 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000562
Sean Callanan97c924e2011-01-27 01:07:04 +0000563 if (m_error_stream)
564 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
565
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000566 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000567 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000568
Sean Callanan82b74c82010-08-12 01:56:52 +0000569 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000570 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000571
572 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
573
574 if (!result_global)
575 {
576 if (log)
577 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000578
579 if (m_error_stream)
580 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
581
Sean Callanan82b74c82010-08-12 01:56:52 +0000582 return false;
583 }
584
Sean Callananc0492742011-05-23 21:40:23 +0000585 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000586 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000587 {
588 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000589 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000590
Sean Callanan97c924e2011-01-27 01:07:04 +0000591 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000592 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 +0000593
Sean Callanan82b74c82010-08-12 01:56:52 +0000594 return false;
595 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000596
Sean Callanan696cf5f2011-05-07 01:06:41 +0000597 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000598 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000599 std::string decl_desc_str;
600 raw_string_ostream decl_desc_stream(decl_desc_str);
601 result_decl->print(decl_desc_stream);
602 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000603
Sean Callanan696cf5f2011-05-07 01:06:41 +0000604 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000605 }
606
Sean Callanan696cf5f2011-05-07 01:06:41 +0000607 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
608 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000609 {
610 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000611 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000612
613 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000614 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 +0000615
Sean Callanan82b74c82010-08-12 01:56:52 +0000616 return false;
617 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000618
Sean Callanan82b74c82010-08-12 01:56:52 +0000619 // Get the next available result name from m_decl_map and create the persistent
620 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000621
Sean Callanan696cf5f2011-05-07 01:06:41 +0000622 // If the result is an Lvalue, it is emitted as a pointer; see
623 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000624 if (m_result_is_pointer)
625 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000626 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000627 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
628 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000629
630 if (!pointer_pointertype)
631 {
632 if (log)
633 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000634
635 if (m_error_stream)
636 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
637
Sean Callanan6a925532011-01-13 08:53:35 +0000638 return false;
639 }
640
641 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
642
Sean Callanan47dc4572011-09-15 02:13:07 +0000643 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000644 &result_decl->getASTContext());
645 }
646 else
647 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000648 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000649 &result_decl->getASTContext());
650 }
651
Sean Callanan696cf5f2011-05-07 01:06:41 +0000652 if (log)
653 {
654 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000655 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000656
657 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
658 }
659
Sean Callanan6a925532011-01-13 08:53:35 +0000660 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000661
662 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000663 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000664
665 // Construct a new result global and set up its metadata
666
Sean Callananc0492742011-05-23 21:40:23 +0000667 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000668 result_global->getType()->getElementType(),
669 false, /* not constant */
670 GlobalValue::ExternalLinkage,
671 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000672 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000673
674 // It's too late in compilation to create a new VarDecl for this, but we don't
675 // need to. We point the metadata at the old VarDecl. This creates an odd
676 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000677 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000678 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
679 // fixed up.
680
Sean Callananc0492742011-05-23 21:40:23 +0000681 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000682 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000683 false);
684
685 llvm::Value* values[2];
686 values[0] = new_result_global;
687 values[1] = new_constant_int;
688
Sean Callanan0de254a2011-05-15 22:34:38 +0000689 ArrayRef<Value*> value_ref(values, 2);
690
Sean Callananc0492742011-05-23 21:40:23 +0000691 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
692 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000693 named_metadata->addOperand(persistent_global_md);
694
695 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000696 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000697 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000698 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000699
700 if (result_global->hasNUses(0))
701 {
702 // We need to synthesize a store for this variable, because otherwise
703 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000704
Greg Clayton8de27c72010-10-15 22:48:33 +0000705 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000706 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
707
708 if (!first_entry_instruction)
709 return false;
710
711 if (!result_global->hasInitializer())
712 {
713 if (log)
714 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000715
716 if (m_error_stream)
717 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
718
Sean Callanan2e2db532010-09-07 22:43:19 +0000719 return false;
720 }
721
722 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000723
724 // Here we write the initializer into a result variable assuming it
725 // can be computed statically.
726
727 if (!m_has_side_effects)
728 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000729 //MaybeSetConstantResult (initializer,
730 // m_result_name,
731 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000732 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000733
Greg Clayton2c344ca2011-02-05 02:28:58 +0000734 StoreInst *synthesized_store = new StoreInst(initializer,
735 new_result_global,
736 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000737
738 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000739 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000740 }
741 else
742 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000743 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000744 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000745 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000746 }
747
Sean Callanan2e2db532010-09-07 22:43:19 +0000748 result_global->replaceAllUsesWith(new_result_global);
749 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000750
751 if (!m_const_result)
752 m_decl_map->AddPersistentVariable(result_decl,
753 m_result_name,
Sean Callanan47dc4572011-09-15 02:13:07 +0000754 m_result_type,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000755 true,
756 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000757
Sean Callanan82b74c82010-08-12 01:56:52 +0000758 result_global->eraseFromParent();
759
760 return true;
761}
762
Johnny Chen58021cc2011-08-09 23:10:20 +0000763#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000764static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000765{
766 if (!depth)
767 return;
768
769 depth--;
770
Johnny Chen58021cc2011-08-09 23:10:20 +0000771 if (log)
772 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000773
Greg Clayton3c7feb42010-11-19 01:05:25 +0000774 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000775 ui != ue;
776 ++ui)
777 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000778 if (log)
779 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000780 DebugUsers(log, *ui, depth);
781 }
782
Johnny Chen58021cc2011-08-09 23:10:20 +0000783 if (log)
784 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000785}
Johnny Chen58021cc2011-08-09 23:10:20 +0000786#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000787
788bool
Sean Callananc0492742011-05-23 21:40:23 +0000789IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000790 llvm::GlobalVariable *cstr,
791 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000792{
793 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
794
Sean Callanan9b6898f2011-07-30 02:42:06 +0000795 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000796
Sean Callanan9b6898f2011-07-30 02:42:06 +0000797 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
798 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000799 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000800 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
801 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000802
803 if (!m_CFStringCreateWithBytes)
804 {
805 lldb::addr_t CFStringCreateWithBytes_addr;
806
807 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
808
809 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
810 {
811 if (log)
812 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
813
Sean Callanan97c924e2011-01-27 01:07:04 +0000814 if (m_error_stream)
815 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
816
Sean Callanan6ba533e2010-11-17 23:00:36 +0000817 return false;
818 }
819
820 if (log)
821 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
822
823 // Build the function type:
824 //
825 // CFStringRef CFStringCreateWithBytes (
826 // CFAllocatorRef alloc,
827 // const UInt8 *bytes,
828 // CFIndex numBytes,
829 // CFStringEncoding encoding,
830 // Boolean isExternalRepresentation
831 // );
832 //
833 // We make the following substitutions:
834 //
835 // CFStringRef -> i8*
836 // CFAllocatorRef -> i8*
837 // UInt8 * -> i8*
838 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
839 // CFStringEncoding -> i32
840 // Boolean -> i8
841
Sean Callanan9b6898f2011-07-30 02:42:06 +0000842 Type *arg_type_array[5];
843
844 arg_type_array[0] = i8_ptr_ty;
845 arg_type_array[1] = i8_ptr_ty;
846 arg_type_array[2] = intptr_ty;
847 arg_type_array[3] = i32_ty;
848 arg_type_array[4] = i8_ty;
849
850 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
851
Sean Callananc0492742011-05-23 21:40:23 +0000852 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000853
854 // Build the constant containing the pointer to the function
855 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
856 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
857 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
858 }
859
Sean Callanan58baaad2011-07-08 00:39:14 +0000860 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000861
862 if (cstr)
863 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000864
Sean Callanan6ba533e2010-11-17 23:00:36 +0000865 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000866 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
867 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000868 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
869 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
870
Sean Callanan9b6898f2011-07-30 02:42:06 +0000871 Value *argument_array[5];
872
873 argument_array[0] = alloc_arg;
874 argument_array[1] = bytes_arg;
875 argument_array[2] = numBytes_arg;
876 argument_array[3] = encoding_arg;
877 argument_array[4] = isExternal_arg;
878
879 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000880
881 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000882 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000883 "CFStringCreateWithBytes",
884 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000885
Greg Clayton3c7feb42010-11-19 01:05:25 +0000886 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000887 {
888 if (log)
889 log->PutCString("Couldn't replace the NSString with the result of the call");
890
Sean Callanan97c924e2011-01-27 01:07:04 +0000891 if (m_error_stream)
892 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
893
Sean Callanan6ba533e2010-11-17 23:00:36 +0000894 return false;
895 }
896
Greg Clayton3c7feb42010-11-19 01:05:25 +0000897 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000898
899 return true;
900}
901
902bool
Sean Callananc0492742011-05-23 21:40:23 +0000903IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000904{
905 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
906
Sean Callananc0492742011-05-23 21:40:23 +0000907 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000908
Greg Clayton3c7feb42010-11-19 01:05:25 +0000909 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000910 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
911
912 if (!FirstEntryInstruction)
913 {
914 if (log)
915 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
916
Sean Callanan97c924e2011-01-27 01:07:04 +0000917 if (m_error_stream)
918 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
919
Sean Callanan6ba533e2010-11-17 23:00:36 +0000920 return false;
921 }
922
923 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
924 vi != ve;
925 ++vi)
926 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000927 std::string value_name = vi->first().str();
928 const char *value_name_cstr = value_name.c_str();
929
930 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000931 {
932 Value *nsstring_value = vi->second;
933
934 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
935
936 if (!nsstring_global)
937 {
938 if (log)
939 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000940
941 if (m_error_stream)
942 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
943
Sean Callanan6ba533e2010-11-17 23:00:36 +0000944 return false;
945 }
946
947 if (!nsstring_global->hasInitializer())
948 {
949 if (log)
950 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000951
952 if (m_error_stream)
953 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
954
Sean Callanan6ba533e2010-11-17 23:00:36 +0000955 return false;
956 }
957
958 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
959
960 if (!nsstring_struct)
961 {
962 if (log)
963 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000964
965 if (m_error_stream)
966 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
967
Sean Callanan6ba533e2010-11-17 23:00:36 +0000968 return false;
969 }
970
971 // We expect the following structure:
972 //
973 // struct {
974 // int *isa;
975 // int flags;
976 // char *str;
977 // long length;
978 // };
979
980 if (nsstring_struct->getNumOperands() != 4)
981 {
982 if (log)
983 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 +0000984
985 if (m_error_stream)
986 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
987
Sean Callanan6ba533e2010-11-17 23:00:36 +0000988 return false;
989 }
990
991 Constant *nsstring_member = nsstring_struct->getOperand(2);
992
993 if (!nsstring_member)
994 {
995 if (log)
996 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000997
998 if (m_error_stream)
999 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1000
Sean Callanan6ba533e2010-11-17 23:00:36 +00001001 return false;
1002 }
1003
1004 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1005
1006 if (!nsstring_expr)
1007 {
1008 if (log)
1009 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +00001010
1011 if (m_error_stream)
1012 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1013
Sean Callanan6ba533e2010-11-17 23:00:36 +00001014 return false;
1015 }
1016
1017 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1018 {
1019 if (log)
1020 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 +00001021
1022 if (m_error_stream)
1023 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1024
Sean Callanan6ba533e2010-11-17 23:00:36 +00001025 return false;
1026 }
1027
1028 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1029
1030 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1031
1032 if (!cstr_global)
1033 {
1034 if (log)
1035 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001036
1037 if (m_error_stream)
1038 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 +00001039
Sean Callanan6ba533e2010-11-17 23:00:36 +00001040 return false;
1041 }
1042
1043 if (!cstr_global->hasInitializer())
1044 {
1045 if (log)
1046 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +00001047
1048 if (m_error_stream)
1049 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1050
Sean Callanan6ba533e2010-11-17 23:00:36 +00001051 return false;
1052 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001053
1054 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001055 if (!cstr_array)
1056 {
1057 if (log)
1058 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001059
1060 if (m_error_stream)
1061 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1062
Sean Callanan6ba533e2010-11-17 23:00:36 +00001063 return false;
1064 }
1065
1066 if (!cstr_array->isCString())
1067 {
1068 if (log)
1069 log->PutCString("NSString initializer's str element is not a C string array");
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 C string\n");
1073
Sean Callanan6ba533e2010-11-17 23:00:36 +00001074 return false;
1075 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001076 */
1077
1078 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001079
1080 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001081 {
1082 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001083 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001084 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001085 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001086 }
1087
1088 if (!cstr_array)
1089 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001090
Sean Callananc0492742011-05-23 21:40:23 +00001091 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001092 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001093 if (log)
1094 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001095
1096 // We don't print an error message here because RewriteObjCConstString has done so for us.
1097
Sean Callanan6ba533e2010-11-17 23:00:36 +00001098 return false;
1099 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001100 }
1101 }
1102
1103 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1104 vi != ve;
1105 ++vi)
1106 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001107 std::string value_name = vi->first().str();
1108 const char *value_name_cstr = value_name.c_str();
1109
1110 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001111 {
1112 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1113
1114 if (!gv)
1115 {
1116 if (log)
1117 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001118
1119 if (m_error_stream)
1120 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1121
Sean Callanan6ba533e2010-11-17 23:00:36 +00001122 return false;
1123 }
1124
1125 gv->eraseFromParent();
1126
1127 break;
1128 }
1129 }
1130
1131 return true;
1132}
1133
Greg Clayton3c7feb42010-11-19 01:05:25 +00001134static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001135{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001136 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001137
Greg Clayton3c7feb42010-11-19 01:05:25 +00001138 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001139 return false;
1140
1141 return true;
1142}
1143
Sean Callanan97c924e2011-01-27 01:07:04 +00001144// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001145bool
Sean Callananc0492742011-05-23 21:40:23 +00001146IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001147{
Greg Claytone005f2c2010-11-06 01:53:30 +00001148 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001149
1150 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1151
1152 if (!load)
1153 return false;
1154
1155 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1156 //
1157 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1158 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1159 //
1160 // where %obj is the object pointer and %tmp is the selector.
1161 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001162 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1163 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001164
1165 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1166
1167 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1168
1169 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1170 return false;
1171
1172 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1173
1174 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1175
1176 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1177 return false;
1178
1179 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1180
1181 if (!osr_initializer_base)
1182 return false;
1183
1184 // Find the string's initializer (a ConstantArray) and get the string from it
1185
1186 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1187
1188 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1189 return false;
1190
1191 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1192
1193 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1194
1195 if (!omvn_initializer_array->isString())
1196 return false;
1197
1198 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1199
1200 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001201 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001202
1203 // Construct a call to sel_registerName
1204
1205 if (!m_sel_registerName)
1206 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001207 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001208
Greg Clayton8de27c72010-10-15 22:48:33 +00001209 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001210 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001211 return false;
1212
Sean Callananc2c6f772010-10-26 00:31:56 +00001213 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001214 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001215
Sean Callananf5857a02010-07-31 01:32:05 +00001216 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1217
1218 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001219 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001220 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001221 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001222
Sean Callanan9b6898f2011-07-30 02:42:06 +00001223 Type *type_array[1];
1224
1225 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1226
1227 ArrayRef<Type *> srN_arg_types(type_array, 1);
1228
Sean Callananf5857a02010-07-31 01:32:05 +00001229 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1230
1231 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001232 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1233 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001234 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001235 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001236 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1237 }
1238
Sean Callanan9b6898f2011-07-30 02:42:06 +00001239 Value *argument_array[1];
1240
Sean Callananc0492742011-05-23 21:40:23 +00001241 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001242
Sean Callanan9b6898f2011-07-30 02:42:06 +00001243 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001244
Sean Callanan9b6898f2011-07-30 02:42:06 +00001245 ArrayRef<Value *> srN_arguments(argument_array, 1);
1246
Sean Callananf5857a02010-07-31 01:32:05 +00001247 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001248 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001249 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001250 selector_load);
1251
1252 // Replace the load with the call in all users
1253
1254 selector_load->replaceAllUsesWith(srN_call);
1255
1256 selector_load->eraseFromParent();
1257
1258 return true;
1259}
1260
1261bool
Sean Callananc0492742011-05-23 21:40:23 +00001262IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001263{
Greg Claytone005f2c2010-11-06 01:53:30 +00001264 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001265
1266 BasicBlock::iterator ii;
1267
1268 typedef SmallVector <Instruction*, 2> InstrList;
1269 typedef InstrList::iterator InstrIterator;
1270
1271 InstrList selector_loads;
1272
Greg Clayton3c7feb42010-11-19 01:05:25 +00001273 for (ii = basic_block.begin();
1274 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001275 ++ii)
1276 {
1277 Instruction &inst = *ii;
1278
1279 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001280 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001281 selector_loads.push_back(&inst);
1282 }
1283
1284 InstrIterator iter;
1285
1286 for (iter = selector_loads.begin();
1287 iter != selector_loads.end();
1288 ++iter)
1289 {
Sean Callananc0492742011-05-23 21:40:23 +00001290 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001291 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001292 if (m_error_stream)
1293 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1294
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001295 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001296 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001297
Sean Callananf5857a02010-07-31 01:32:05 +00001298 return false;
1299 }
1300 }
1301
1302 return true;
1303}
1304
Sean Callanan97c924e2011-01-27 01:07:04 +00001305// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001306bool
Sean Callananc0492742011-05-23 21:40:23 +00001307IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001308{
Sean Callanan97678d12011-01-13 21:23:32 +00001309 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1310
Sean Callanana48fe162010-08-11 03:57:18 +00001311 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1312
1313 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1314
1315 if (!alloc_md || !alloc_md->getNumOperands())
1316 return false;
1317
1318 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1319
1320 if (!constant_int)
1321 return false;
1322
1323 // We attempt to register this as a new persistent variable with the DeclMap.
1324
1325 uintptr_t ptr = constant_int->getZExtValue();
1326
Sean Callanan82b74c82010-08-12 01:56:52 +00001327 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001328
Sean Callanan82b74c82010-08-12 01:56:52 +00001329 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1330 &decl->getASTContext());
1331
Greg Clayton8de27c72010-10-15 22:48:33 +00001332 StringRef decl_name (decl->getName());
1333 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001334 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001335 return false;
1336
Sean Callananc0492742011-05-23 21:40:23 +00001337 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001338 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001339 false, /* not constant */
1340 GlobalValue::ExternalLinkage,
1341 NULL, /* no initializer */
1342 alloc->getName().str().c_str());
1343
1344 // What we're going to do here is make believe this was a regular old external
1345 // variable. That means we need to make the metadata valid.
1346
Sean Callananc0492742011-05-23 21:40:23 +00001347 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001348
1349 llvm::Value* values[2];
1350 values[0] = persistent_global;
1351 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001352
1353 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001354
Sean Callananc0492742011-05-23 21:40:23 +00001355 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001356 named_metadata->addOperand(persistent_global_md);
1357
Sean Callanan97678d12011-01-13 21:23:32 +00001358 // Now, since the variable is a pointer variable, we will drop in a load of that
1359 // pointer variable.
1360
1361 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1362
1363 if (log)
1364 log->Printf("Replacing \"%s\" with \"%s\"",
1365 PrintValue(alloc).c_str(),
1366 PrintValue(persistent_load).c_str());
1367
1368 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001369 alloc->eraseFromParent();
1370
1371 return true;
1372}
1373
1374bool
Sean Callananc0492742011-05-23 21:40:23 +00001375IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001376{
Sean Callanane8a59a82010-09-13 21:34:21 +00001377 if (!m_resolve_vars)
1378 return true;
1379
Greg Claytone005f2c2010-11-06 01:53:30 +00001380 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001381
1382 BasicBlock::iterator ii;
1383
1384 typedef SmallVector <Instruction*, 2> InstrList;
1385 typedef InstrList::iterator InstrIterator;
1386
1387 InstrList pvar_allocs;
1388
Greg Clayton3c7feb42010-11-19 01:05:25 +00001389 for (ii = basic_block.begin();
1390 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001391 ++ii)
1392 {
1393 Instruction &inst = *ii;
1394
1395 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001396 {
1397 llvm::StringRef alloc_name = alloc->getName();
1398
1399 if (alloc_name.startswith("$") &&
1400 !alloc_name.startswith("$__lldb"))
1401 {
1402 if (alloc_name.find_first_of("0123456789") == 1)
1403 {
1404 if (log)
1405 log->Printf("Rejecting a numeric persistent variable.");
1406
Sean Callanan97c924e2011-01-27 01:07:04 +00001407 if (m_error_stream)
1408 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1409
Sean Callanan237e4742011-01-21 22:30:25 +00001410 return false;
1411 }
1412
Sean Callanana48fe162010-08-11 03:57:18 +00001413 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001414 }
1415 }
Sean Callanana48fe162010-08-11 03:57:18 +00001416 }
1417
1418 InstrIterator iter;
1419
1420 for (iter = pvar_allocs.begin();
1421 iter != pvar_allocs.end();
1422 ++iter)
1423 {
Sean Callananc0492742011-05-23 21:40:23 +00001424 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001425 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001426 if (m_error_stream)
1427 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1428
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001429 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001430 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001431
Sean Callanana48fe162010-08-11 03:57:18 +00001432 return false;
1433 }
1434 }
1435
1436 return true;
1437}
1438
Sean Callananc7ca4662011-10-25 18:36:40 +00001439bool
1440IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1441{
1442 if (!initializer)
1443 return true;
1444
1445 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1446
1447 if (log && log->GetVerbose())
1448 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1449
1450 Type *initializer_type = initializer->getType();
1451
1452 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1453 {
1454 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1455 return true;
1456 }
1457 else if (ConstantArray *array_initializer = dyn_cast<ConstantArray>(initializer))
1458 {
1459 if (array_initializer->isString())
1460 {
1461 std::string array_initializer_string = array_initializer->getAsString();
1462 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1463 }
1464 else
1465 {
1466 ArrayType *array_initializer_type = array_initializer->getType();
1467 Type *array_element_type = array_initializer_type->getElementType();
1468
1469 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1470
1471 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1472 {
1473 if (!MaterializeInitializer(data + (i * element_size), array_initializer->getOperand(i)))
1474 return false;
1475 }
1476 }
1477 return true;
1478 }
1479 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1480 {
1481 StructType *struct_initializer_type = struct_initializer->getType();
1482 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1483
1484 for (int i = 0;
1485 i < struct_initializer->getNumOperands();
1486 ++i)
1487 {
1488 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1489 return false;
1490 }
1491 return true;
1492 }
1493 return false;
1494}
1495
1496bool
1497IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1498{
1499 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1500 return false;
1501
1502 uint64_t offset = m_data_allocator->GetStream().GetSize();
1503
1504 llvm::Type *variable_type = global_variable->getType();
1505
1506 Constant *initializer = global_variable->getInitializer();
1507
1508 llvm::Type *initializer_type = initializer->getType();
1509
1510 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1511
1512 lldb_private::DataBufferHeap data(size, '\0');
1513
1514 if (initializer)
1515 if (!MaterializeInitializer(data.GetBytes(), initializer))
1516 return false;
1517
1518 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1519
1520 Constant *new_pointer = BuildRelocation(variable_type, offset);
1521
1522 global_variable->replaceAllUsesWith(new_pointer);
1523
1524 global_variable->eraseFromParent();
1525
1526 return true;
1527}
1528
Sean Callanan97c924e2011-01-27 01:07:04 +00001529// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001530bool
Sean Callananc0492742011-05-23 21:40:23 +00001531IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001532{
Greg Claytone005f2c2010-11-06 01:53:30 +00001533 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001534
1535 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001536 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001537
Greg Clayton8de27c72010-10-15 22:48:33 +00001538 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001539 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001540 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001541 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001542 default:
1543 break;
1544 case Instruction::GetElementPtr:
1545 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001546 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001547 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001548 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001549 }
1550 }
Sean Callananf921cf52010-12-03 19:51:05 +00001551 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001552 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001553 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1554 return MaterializeInternalVariable(global_variable);
1555
Sean Callananc0492742011-05-23 21:40:23 +00001556 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001557
Sean Callananf5857a02010-07-31 01:32:05 +00001558 if (!named_decl)
1559 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001560 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001561 return true;
1562
Sean Callanan7cd46742010-12-06 00:56:39 +00001563 if (!global_variable->hasExternalLinkage())
1564 return true;
1565
Sean Callananf5857a02010-07-31 01:32:05 +00001566 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001567 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001568
Sean Callananf5857a02010-07-31 01:32:05 +00001569 return false;
1570 }
1571
Greg Clayton8de27c72010-10-15 22:48:33 +00001572 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001573
Sean Callanan771131d2010-09-30 21:18:25 +00001574 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001575 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001576
1577 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001578 {
Sean Callanan771131d2010-09-30 21:18:25 +00001579 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001580 ast_context = &value_decl->getASTContext();
1581 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001582 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001583 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001584 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001585 }
Sean Callanan771131d2010-09-30 21:18:25 +00001586
Sean Callanan6a925532011-01-13 08:53:35 +00001587 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001588 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001589
Sean Callanan97678d12011-01-13 21:23:32 +00001590 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001591 {
1592 // The $__lldb_expr_result name indicates the the return value has allocated as
1593 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1594 // accesses to this static variable need to be redirected to the result of dereferencing
1595 // a pointer that is passed in as one of the arguments.
1596 //
1597 // Consequently, when reporting the size of the type, we report a pointer type pointing
1598 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001599 //
1600 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001601
Sean Callanan6a925532011-01-13 08:53:35 +00001602 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1603 value_type = PointerType::get(global_variable->getType(), 0);
1604 }
1605 else
1606 {
1607 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1608 value_type = global_variable->getType();
1609 }
Sean Callanan771131d2010-09-30 21:18:25 +00001610
1611 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1612 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001613
Sean Callanan771131d2010-09-30 21:18:25 +00001614 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001615 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001616 name.c_str(),
1617 qual_type.getAsString().c_str(),
1618 PrintType(value_type).c_str(),
1619 value_size,
1620 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001621
Sean Callanan8bce6652010-07-13 21:41:46 +00001622
Sean Callanan8c127202010-08-23 23:09:38 +00001623 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001624 lldb_private::ConstString (name.c_str()),
1625 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001626 value_size,
1627 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001628 {
1629 if (!global_variable->hasExternalLinkage())
1630 return true;
1631 else
1632 return false;
1633 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001634 }
Sean Callananf3143b72010-12-03 03:02:31 +00001635 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001636 {
1637 if (log)
1638 log->Printf("Function pointers aren't handled right now");
1639
1640 return false;
1641 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001642
1643 return true;
1644}
1645
Sean Callanan97c924e2011-01-27 01:07:04 +00001646// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001647bool
Sean Callananc0492742011-05-23 21:40:23 +00001648IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001649{
Sean Callananc7674af2011-01-17 23:42:46 +00001650 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1651
1652 lldb_private::ConstString name(symbol->getName().str().c_str());
1653
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001654 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001655
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001656 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001657 {
1658 if (log)
1659 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1660
1661 return false;
1662 }
1663
1664 if (log)
1665 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1666
Sean Callanan9b6898f2011-07-30 02:42:06 +00001667 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001668
Sean Callanan9b6898f2011-07-30 02:42:06 +00001669 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1670 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001671
1672 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1673
1674 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1675
1676 if (log)
1677 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1678
1679 symbol->replaceAllUsesWith(symbol_addr_ptr);
1680
1681 return true;
1682}
1683
1684bool
Sean Callananc0492742011-05-23 21:40:23 +00001685IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001686{
Sean Callanan48443652010-12-02 19:47:57 +00001687 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1688
1689 if (log)
1690 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001691
Sean Callanan6ba533e2010-11-17 23:00:36 +00001692 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001693 op_index < num_ops;
1694 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001695 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001696 {
1697 if (m_error_stream)
1698 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1699
Sean Callanandc27aba2010-10-05 22:26:43 +00001700 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001701 }
1702
Sean Callanandc27aba2010-10-05 22:26:43 +00001703 return true;
1704}
1705
1706bool
Sean Callanan9911d2f2011-11-01 23:38:03 +00001707IRForTarget::HandleObjCClass(Value *classlist_reference)
1708{
1709 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1710
1711 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1712
1713 if (!global_variable)
1714 return false;
1715
1716 Constant *initializer = global_variable->getInitializer();
1717
1718 if (!initializer)
1719 return false;
1720
1721 if (!initializer->hasName())
1722 return false;
1723
1724 StringRef name(initializer->getName());
1725 lldb_private::ConstString name_cstr(name.str().c_str());
1726 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr);
1727
1728 if (log)
1729 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1730
1731 if (class_ptr == LLDB_INVALID_ADDRESS)
1732 return false;
1733
1734 if (global_variable->use_begin() == global_variable->use_end())
1735 return false;
1736
1737 LoadInst *load_instruction = NULL;
1738
1739 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1740 i != e;
1741 ++i)
1742 {
1743 if ((load_instruction = dyn_cast<LoadInst>(*i)))
1744 break;
1745 }
1746
1747 if (!load_instruction)
1748 return false;
1749
1750 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1751 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1752
1753 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1754 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1755
1756 load_instruction->replaceAllUsesWith(class_bitcast);
1757
1758 load_instruction->eraseFromParent();
1759
1760 return true;
1761}
1762
1763bool
Sean Callananc0492742011-05-23 21:40:23 +00001764IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001765{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001766 /////////////////////////////////////////////////////////////////////////
1767 // Prepare the current basic block for execution in the remote process
1768 //
1769
Sean Callanan02fbafa2010-07-27 21:39:39 +00001770 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001771
Greg Clayton3c7feb42010-11-19 01:05:25 +00001772 for (ii = basic_block.begin();
1773 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001774 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001775 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001776 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001777
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001778 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001779
Sean Callanan97c924e2011-01-27 01:07:04 +00001780 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001781 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001782 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001783 }
1784
1785 return true;
1786}
1787
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001788bool
Sean Callananc0492742011-05-23 21:40:23 +00001789IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001790{
Sean Callananae71e302010-11-18 22:21:58 +00001791 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1792
Sean Callananc0492742011-05-23 21:40:23 +00001793 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001794 global != end;
1795 ++global)
1796 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001797 if (log)
1798 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1799 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001800 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001801
Sean Callanan9911d2f2011-11-01 23:38:03 +00001802 std::string global_name = (*global).getName().str();
1803
1804 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc7674af2011-01-17 23:42:46 +00001805 {
Sean Callananc0492742011-05-23 21:40:23 +00001806 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001807 {
1808 if (m_error_stream)
1809 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1810
Sean Callananc7674af2011-01-17 23:42:46 +00001811 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001812 }
Sean Callananc7674af2011-01-17 23:42:46 +00001813 }
Sean Callanan9911d2f2011-11-01 23:38:03 +00001814 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1815 {
1816 if (!HandleObjCClass(global))
1817 {
1818 if (m_error_stream)
1819 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1820
1821 return false;
1822 }
1823 }
Sean Callananc0492742011-05-23 21:40:23 +00001824 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001825 {
Sean Callananc0492742011-05-23 21:40:23 +00001826 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001827 {
1828 if (m_error_stream)
1829 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1830
Sean Callananc7674af2011-01-17 23:42:46 +00001831 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001832 }
Sean Callananc7674af2011-01-17 23:42:46 +00001833 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001834 }
1835
1836 return true;
1837}
1838
Sean Callananc0492742011-05-23 21:40:23 +00001839bool
1840IRForTarget::ReplaceStrings ()
1841{
1842 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1843
1844 if (!m_data_allocator)
1845 return true; // hope for the best; some clients may not want static allocation!
1846
1847 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1848
1849 OffsetsTy offsets;
1850
1851 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1852 gi != ge;
1853 ++gi)
1854 {
1855 GlobalVariable *gv = gi;
1856
1857 if (!gv->hasInitializer())
1858 continue;
1859
1860 Constant *gc = gv->getInitializer();
1861
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001862 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001863
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001864 if (gc->isNullValue())
1865 {
1866 Type *gc_type = gc->getType();
1867
1868 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1869
1870 if (!gc_array_type)
1871 continue;
1872
1873 Type *gc_element_type = gc_array_type->getElementType();
1874
1875 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1876
1877 if (gc_integer_type->getBitWidth() != 8)
1878 continue;
1879
1880 str = "";
1881 }
1882 else
1883 {
1884 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1885
1886 if (!gc_array)
1887 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001888
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001889 if (!gc_array->isCString())
1890 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001891
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001892 if (log)
1893 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001894
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001895 str = gc_array->getAsString();
1896 }
1897
Sean Callananc0492742011-05-23 21:40:23 +00001898 offsets[gv] = m_data_allocator->GetStream().GetSize();
1899
1900 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1901 }
1902
Sean Callanan9b6898f2011-07-30 02:42:06 +00001903 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001904
1905 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1906 oi != oe;
1907 ++oi)
1908 {
1909 GlobalVariable *gv = oi->first;
1910 size_t offset = oi->second;
1911
1912 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1913
1914 if (log)
1915 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1916
1917 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1918 ui != ue;
1919 ++ui)
1920 {
1921 if (log)
1922 log->Printf("Found use %s", PrintValue(*ui).c_str());
1923
1924 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1925 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1926
1927 if (const_expr)
1928 {
1929 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1930 {
1931 if (log)
1932 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1933
1934 return false;
1935 }
1936
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001937 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1938 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1939
1940 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001941 }
1942 else if (store_inst)
1943 {
1944 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1945
1946 store_inst->setOperand(0, bit_cast);
1947 }
1948 else
1949 {
1950 if (log)
1951 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1952
1953 return false;
1954 }
1955 }
1956
1957 gv->eraseFromParent();
1958 }
1959
1960 return true;
1961}
1962
1963bool
1964IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1965{
1966 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1967
1968 if (!m_data_allocator)
1969 return true;
1970
1971 typedef SmallVector <Value*, 2> ConstantList;
1972 typedef SmallVector <llvm::Instruction*, 2> UserList;
1973 typedef ConstantList::iterator ConstantIterator;
1974 typedef UserList::iterator UserIterator;
1975
1976 ConstantList static_constants;
1977 UserList static_users;
1978
1979 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1980 ii != ie;
1981 ++ii)
1982 {
1983 llvm::Instruction &inst = *ii;
1984
1985 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1986 oi != oe;
1987 ++oi)
1988 {
1989 Value *operand_val = oi->get();
1990
1991 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1992
1993 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1994 {
1995 static_constants.push_back(operand_val);
1996 static_users.push_back(ii);
1997 }
1998 }
1999 }
2000
2001 ConstantIterator constant_iter;
2002 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00002003
Sean Callananc0492742011-05-23 21:40:23 +00002004 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2005 constant_iter != static_constants.end();
2006 ++constant_iter, ++user_iter)
2007 {
2008 Value *operand_val = *constant_iter;
2009 llvm::Instruction *inst = *user_iter;
2010
2011 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2012
2013 if (operand_constant_fp)
2014 {
2015 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2016 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2017
2018 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2019 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2020
2021 if (log)
2022 {
2023 std::string s;
2024 raw_string_ostream ss(s);
2025 for (size_t index = 0;
2026 index < operand_data_size;
2027 ++index)
2028 {
2029 ss << (uint32_t)operand_raw_data[index];
2030 ss << " ";
2031 }
2032 ss.flush();
2033
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002034 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00002035 }
2036
2037 lldb_private::DataBufferHeap data(operand_data_size, 0);
2038
2039 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
2040 {
2041 uint8_t *data_bytes = data.GetBytes();
2042
2043 for (size_t index = 0;
2044 index < operand_data_size;
2045 ++index)
2046 {
2047 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2048 }
2049 }
2050 else
2051 {
2052 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2053 }
2054
2055 uint64_t offset = m_data_allocator->GetStream().GetSize();
2056
2057 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
2058
Sean Callanan9b6898f2011-07-30 02:42:06 +00002059 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00002060
2061 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2062
2063 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2064
2065 operand_constant_fp->replaceAllUsesWith(fp_load);
2066 }
2067 }
2068
2069 return true;
2070}
2071
Sean Callanan02fbafa2010-07-27 21:39:39 +00002072static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00002073{
Sean Callanan58baaad2011-07-08 00:39:14 +00002074 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00002075
Sean Callanan6ba533e2010-11-17 23:00:36 +00002076 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00002077 return false;
2078
Sean Callanan58baaad2011-07-08 00:39:14 +00002079 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002080
2081 if ((CE = dyn_cast<ConstantExpr>(V)))
2082 {
2083 if (CE->getOpcode() != Instruction::BitCast)
2084 return false;
2085
Sean Callanan6ba533e2010-11-17 23:00:36 +00002086 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002087 }
2088
Sean Callanan6ba533e2010-11-17 23:00:36 +00002089 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00002090
2091 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2092 return false;
2093
2094 return true;
2095}
2096
Sean Callananc0492742011-05-23 21:40:23 +00002097void
2098IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00002099{
Sean Callananc0492742011-05-23 21:40:23 +00002100 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002101
2102 Value::use_iterator ui;
2103
2104 for (ui = guard_load->use_begin();
2105 ui != guard_load->use_end();
2106 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002107 {
Greg Clayton6e713402010-07-30 20:30:44 +00002108 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002109 {
2110 // do nothing for the moment
2111 }
2112 else
2113 {
2114 ui->replaceUsesOfWith(guard_load, zero);
2115 }
2116 }
Sean Callanan45839272010-07-24 01:37:44 +00002117
2118 guard_load->eraseFromParent();
2119}
2120
2121static void ExciseGuardStore(Instruction* guard_store)
2122{
2123 guard_store->eraseFromParent();
2124}
2125
2126bool
Sean Callananc0492742011-05-23 21:40:23 +00002127IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002128{
2129 ///////////////////////////////////////////////////////
2130 // Eliminate any reference to guard variables found.
2131 //
2132
Sean Callanan02fbafa2010-07-27 21:39:39 +00002133 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002134
Sean Callanan02fbafa2010-07-27 21:39:39 +00002135 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002136 typedef InstrList::iterator InstrIterator;
2137
2138 InstrList guard_loads;
2139 InstrList guard_stores;
2140
Greg Clayton3c7feb42010-11-19 01:05:25 +00002141 for (ii = basic_block.begin();
2142 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002143 ++ii)
2144 {
2145 Instruction &inst = *ii;
2146
2147 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2148 if (isGuardVariableRef(load->getPointerOperand()))
2149 guard_loads.push_back(&inst);
2150
2151 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2152 if (isGuardVariableRef(store->getPointerOperand()))
2153 guard_stores.push_back(&inst);
2154 }
2155
2156 InstrIterator iter;
2157
2158 for (iter = guard_loads.begin();
2159 iter != guard_loads.end();
2160 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002161 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002162
2163 for (iter = guard_stores.begin();
2164 iter != guard_stores.end();
2165 ++iter)
2166 ExciseGuardStore(*iter);
2167
2168 return true;
2169}
2170
Sean Callanan97c924e2011-01-27 01:07:04 +00002171// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002172bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002173IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002174{
Greg Claytone005f2c2010-11-06 01:53:30 +00002175 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002176
2177 Value::use_iterator ui;
2178
Sean Callanana48fe162010-08-11 03:57:18 +00002179 SmallVector<User*, 16> users;
2180
2181 // We do this because the use list might change, invalidating our iterator.
2182 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002183 for (ui = old_constant->use_begin();
2184 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002185 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002186 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002187
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002188 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002189 i < users.size();
2190 ++i)
2191 {
2192 User *user = users[i];
2193
Sean Callananbafd6852010-07-14 23:40:29 +00002194 if (Constant *constant = dyn_cast<Constant>(user))
2195 {
2196 // synthesize a new non-constant equivalent of the constant
2197
2198 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2199 {
2200 switch (constant_expr->getOpcode())
2201 {
2202 default:
2203 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002204 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002205 return false;
2206 case Instruction::BitCast:
2207 {
2208 // UnaryExpr
2209 // OperandList[0] is value
2210
2211 Value *s = constant_expr->getOperand(0);
2212
Greg Clayton3c7feb42010-11-19 01:05:25 +00002213 if (s == old_constant)
2214 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002215
Sean Callananc0492742011-05-23 21:40:23 +00002216 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002217
Greg Clayton3c7feb42010-11-19 01:05:25 +00002218 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002219 }
2220 break;
2221 case Instruction::GetElementPtr:
2222 {
2223 // GetElementPtrConstantExpr
2224 // OperandList[0] is base
2225 // OperandList[1]... are indices
2226
2227 Value *ptr = constant_expr->getOperand(0);
2228
Greg Clayton3c7feb42010-11-19 01:05:25 +00002229 if (ptr == old_constant)
2230 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002231
2232 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002233
2234 unsigned operand_index;
2235 unsigned num_operands = constant_expr->getNumOperands();
2236
2237 for (operand_index = 1;
2238 operand_index < num_operands;
2239 ++operand_index)
2240 {
2241 Value *operand = constant_expr->getOperand(operand_index);
2242
Greg Clayton3c7feb42010-11-19 01:05:25 +00002243 if (operand == old_constant)
2244 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002245
Sean Callanan9b6898f2011-07-30 02:42:06 +00002246 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002247 }
2248
Sean Callanan9b6898f2011-07-30 02:42:06 +00002249 ArrayRef <Value*> indices(index_vector);
2250
2251 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002252
Greg Clayton3c7feb42010-11-19 01:05:25 +00002253 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002254 }
2255 break;
2256 }
2257 }
2258 else
2259 {
2260 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002261 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002262 return false;
2263 }
2264 }
2265 else
2266 {
2267 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002268 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002269 }
2270 }
2271
2272 return true;
2273}
2274
Sean Callanan8bce6652010-07-13 21:41:46 +00002275bool
Sean Callananc0492742011-05-23 21:40:23 +00002276IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002277{
Sean Callanane8a59a82010-09-13 21:34:21 +00002278 if (!m_resolve_vars)
2279 return true;
2280
Greg Claytone005f2c2010-11-06 01:53:30 +00002281 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002282
2283 m_decl_map->DoStructLayout();
2284
2285 if (log)
2286 log->Printf("Element arrangement:");
2287
2288 uint32_t num_elements;
2289 uint32_t element_index;
2290
2291 size_t size;
2292 off_t alignment;
2293
2294 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2295 return false;
2296
Greg Clayton3c7feb42010-11-19 01:05:25 +00002297 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002298
Greg Clayton3c7feb42010-11-19 01:05:25 +00002299 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002300 {
2301 if (m_error_stream)
2302 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2303
Sean Callanan8bce6652010-07-13 21:41:46 +00002304 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002305 }
2306
Sean Callanan02fbafa2010-07-27 21:39:39 +00002307 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002308
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002309 if (argument->getName().equals("this"))
2310 {
2311 ++iter;
2312
Greg Clayton3c7feb42010-11-19 01:05:25 +00002313 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002314 {
2315 if (m_error_stream)
2316 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2317
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002318 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002319 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002320
2321 argument = iter;
2322 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002323 else if (argument->getName().equals("self"))
2324 {
2325 ++iter;
2326
2327 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002328 {
2329 if (m_error_stream)
2330 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2331
Sean Callanan3aa7da52010-12-13 22:46:15 +00002332 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002333 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002334
2335 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002336 {
2337 if (m_error_stream)
2338 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2339
Sean Callanan3aa7da52010-12-13 22:46:15 +00002340 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002341 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002342
2343 ++iter;
2344
2345 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002346 {
2347 if (m_error_stream)
2348 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2349
Sean Callanan3aa7da52010-12-13 22:46:15 +00002350 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002351 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002352
2353 argument = iter;
2354 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002355
Greg Clayton8de27c72010-10-15 22:48:33 +00002356 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002357 {
2358 if (m_error_stream)
2359 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2360
Sean Callanan8bce6652010-07-13 21:41:46 +00002361 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002362 }
2363
Sean Callanan8bce6652010-07-13 21:41:46 +00002364 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002365 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002366
Greg Clayton3c7feb42010-11-19 01:05:25 +00002367 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002368 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002369
Sean Callanan6ba533e2010-11-17 23:00:36 +00002370 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002371 {
2372 if (m_error_stream)
2373 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2374
Sean Callanan8bce6652010-07-13 21:41:46 +00002375 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002376 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002377
Sean Callananc0492742011-05-23 21:40:23 +00002378 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002379 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002380
2381 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002382 {
2383 if (m_error_stream)
2384 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2385
Sean Callanan8bce6652010-07-13 21:41:46 +00002386 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002387 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002388
2389 for (element_index = 0; element_index < num_elements; ++element_index)
2390 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002391 const clang::NamedDecl *decl = NULL;
2392 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002393 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002394 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002395
Sean Callanan45690fe2010-08-30 22:17:16 +00002396 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002397 {
2398 if (m_error_stream)
2399 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2400
Sean Callanan8bce6652010-07-13 21:41:46 +00002401 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002402 }
2403
Sean Callanan8bce6652010-07-13 21:41:46 +00002404 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002405 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002406 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002407 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002408 offset);
2409
Sean Callanan9b6898f2011-07-30 02:42:06 +00002410 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002411 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002412
Sean Callananc7ca4662011-10-25 18:36:40 +00002413 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002414 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002415 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002416
Sean Callananc7ca4662011-10-25 18:36:40 +00002417 if (log)
2418 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002419
Sean Callananc7ca4662011-10-25 18:36:40 +00002420 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2421 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2422 // entry in order to produce the static variable that the AST thinks it is accessing.
2423 if (name == m_result_name && !m_result_is_pointer)
2424 {
2425 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2426
2427 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2428
2429 replacement = load;
2430 }
2431 else
2432 {
2433 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2434
2435 replacement = bit_cast;
2436 }
2437
2438 if (Constant *constant = dyn_cast<Constant>(value))
2439 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2440 else
2441 value->replaceAllUsesWith(replacement);
2442
2443 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2444 var->eraseFromParent();
2445 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002446 }
2447
2448 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002449 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002450
2451 return true;
2452}
2453
Sean Callananc0492742011-05-23 21:40:23 +00002454llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002455IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002456 uint64_t offset)
2457{
2458 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2459
Sean Callanan9b6898f2011-07-30 02:42:06 +00002460 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2461 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002462
2463 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002464
2465 llvm::Constant *offset_array[1];
2466
2467 offset_array[0] = offset_int;
2468
2469 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2470
2471 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002472 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2473
2474 return reloc_getbitcast;
2475}
2476
2477bool
2478IRForTarget::CompleteDataAllocation ()
2479{
Sean Callanan47dc4572011-09-15 02:13:07 +00002480 if (!m_data_allocator)
2481 return true;
2482
Sean Callananc0492742011-05-23 21:40:23 +00002483 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2484
2485 if (!m_data_allocator->GetStream().GetSize())
2486 return true;
2487
2488 lldb::addr_t allocation = m_data_allocator->Allocate();
2489
2490 if (log)
2491 {
2492 if (allocation)
2493 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2494 else
2495 log->Printf("Failed to allocate static data");
2496 }
2497
2498 if (!allocation)
2499 return false;
2500
Sean Callanan9b6898f2011-07-30 02:42:06 +00002501 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2502 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002503
2504 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2505 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2506
2507 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2508
2509 m_reloc_placeholder->eraseFromParent();
2510
2511 return true;
2512}
2513
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002514bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002515IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002516{
Greg Claytone005f2c2010-11-06 01:53:30 +00002517 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002518
Sean Callananc0492742011-05-23 21:40:23 +00002519 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002520 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002521
2522 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002523
2524 if (!function)
2525 {
2526 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002527 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002528
2529 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002530 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 +00002531
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002532 return false;
2533 }
Sean Callananc0492742011-05-23 21:40:23 +00002534
2535 if (!FixFunctionLinkage (*function))
2536 {
2537 if (log)
2538 log->Printf("Couldn't fix the linkage for the function");
2539
2540 return false;
2541 }
2542
Sean Callananc7ca4662011-10-25 18:36:40 +00002543 if (log)
2544 {
2545 std::string s;
2546 raw_string_ostream oss(s);
2547
2548 m_module->print(oss, NULL);
2549
2550 oss.flush();
2551
2552 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2553 }
2554
Sean Callanan9b6898f2011-07-30 02:42:06 +00002555 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002556
2557 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2558 intptr_ty,
2559 false /* isConstant */,
2560 GlobalVariable::InternalLinkage,
2561 Constant::getNullValue(intptr_ty),
2562 "reloc_placeholder",
2563 NULL /* InsertBefore */,
2564 false /* ThreadLocal */,
2565 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002566
Sean Callanan02fbafa2010-07-27 21:39:39 +00002567 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002568
Sean Callananc0492742011-05-23 21:40:23 +00002569 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002570
Sean Callanan82b74c82010-08-12 01:56:52 +00002571 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002572 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002573 //
2574
Sean Callananc0492742011-05-23 21:40:23 +00002575 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002576 {
2577 if (log)
2578 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002579
2580 // CreateResultVariable() reports its own errors, so we don't do so here
2581
Sean Callanan82b74c82010-08-12 01:56:52 +00002582 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002583 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002584
2585 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2586 {
2587 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002588 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002589 }
2590
2591 for (bbi = function->begin();
2592 bbi != function->end();
2593 ++bbi)
2594 {
2595 if (!RemoveGuards(*bbi))
2596 {
2597 if (log)
2598 log->Printf("RemoveGuards() failed");
2599
2600 // RemoveGuards() reports its own errors, so we don't do so here
2601
2602 return false;
2603 }
2604
2605 if (!RewritePersistentAllocs(*bbi))
2606 {
2607 if (log)
2608 log->Printf("RewritePersistentAllocs() failed");
2609
2610 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2611
2612 return false;
2613 }
2614 }
2615
2616 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2617 {
2618 IRInterpreter interpreter (*m_decl_map,
2619 m_error_stream);
2620
2621 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2622 {
2623 m_interpret_success = true;
2624 return true;
2625 }
2626 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002627
Sean Callanan7b8eb762011-11-01 17:33:54 +00002628 if (log && log->GetVerbose())
Sean Callananc0492742011-05-23 21:40:23 +00002629 {
2630 std::string s;
2631 raw_string_ostream oss(s);
2632
2633 m_module->print(oss, NULL);
2634
2635 oss.flush();
2636
2637 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2638 }
2639
Sean Callanan6ba533e2010-11-17 23:00:36 +00002640 ///////////////////////////////////////////////////////////////////////////////
2641 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2642 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002643
Sean Callananc0492742011-05-23 21:40:23 +00002644 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002645 {
2646 if (log)
2647 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002648
2649 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2650
Sean Callanan6ba533e2010-11-17 23:00:36 +00002651 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002652 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002653
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002654 ///////////////////////////////
2655 // Resolve function pointers
2656 //
2657
2658 if (!ResolveFunctionPointers(llvm_module, *function))
2659 {
2660 if (log)
2661 log->Printf("ResolveFunctionPointers() failed");
2662
2663 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2664
2665 return false;
2666 }
2667
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002668 for (bbi = function->begin();
2669 bbi != function->end();
2670 ++bbi)
2671 {
Sean Callananc0492742011-05-23 21:40:23 +00002672 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002673 {
2674 if (log)
2675 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002676
2677 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2678
Sean Callanana48fe162010-08-11 03:57:18 +00002679 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002680 }
Sean Callanana48fe162010-08-11 03:57:18 +00002681
Sean Callananc0492742011-05-23 21:40:23 +00002682 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002683 {
2684 if (log)
2685 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002686
2687 // ResolveCalls() reports its own errors, so we don't do so here
2688
Sean Callanan8bce6652010-07-13 21:41:46 +00002689 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002690 }
Sean Callananc0492742011-05-23 21:40:23 +00002691
2692 if (!ReplaceStaticLiterals(*bbi))
2693 {
2694 if (log)
2695 log->Printf("ReplaceStaticLiterals() failed");
2696
2697 return false;
2698 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002699 }
2700
Sean Callanan771131d2010-09-30 21:18:25 +00002701 ///////////////////////////////
2702 // Run function-level passes
2703 //
2704
Sean Callananc0492742011-05-23 21:40:23 +00002705 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002706 {
2707 if (log)
2708 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002709
2710 // ResolveExternals() reports its own errors, so we don't do so here
2711
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002712 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002713 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002714
Sean Callananc0492742011-05-23 21:40:23 +00002715 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002716 {
2717 if (log)
2718 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002719
2720 // ReplaceVariables() reports its own errors, so we don't do so here
2721
Sean Callanan771131d2010-09-30 21:18:25 +00002722 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002723 }
Sean Callanan771131d2010-09-30 21:18:25 +00002724
Sean Callananc0492742011-05-23 21:40:23 +00002725 if (!ReplaceStrings())
2726 {
2727 if (log)
2728 log->Printf("ReplaceStrings() failed");
2729
2730 return false;
2731 }
2732
2733 if (!CompleteDataAllocation())
2734 {
2735 if (log)
2736 log->Printf("CompleteDataAllocation() failed");
2737
2738 return false;
2739 }
2740
Sean Callanan7b8eb762011-11-01 17:33:54 +00002741 if (log && log->GetVerbose())
Sean Callanan8bce6652010-07-13 21:41:46 +00002742 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002743 std::string s;
2744 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002745
Sean Callananc0492742011-05-23 21:40:23 +00002746 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002747
2748 oss.flush();
2749
Greg Claytonb5037af2010-11-15 01:47:11 +00002750 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002751 }
2752
2753 return true;
2754}
2755
2756void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002757IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002758{
2759}
2760
2761PassManagerType
2762IRForTarget::getPotentialPassManagerType() const
2763{
2764 return PMT_ModulePassManager;
2765}