blob: c6d7f2dea2eb8241c0c240b9539bc540f1b87600 [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
Sean Callananc41606f2011-11-15 19:13:54 +00001502 if (global_variable == m_reloc_placeholder)
1503 return true;
1504
Sean Callananc7ca4662011-10-25 18:36:40 +00001505 uint64_t offset = m_data_allocator->GetStream().GetSize();
1506
1507 llvm::Type *variable_type = global_variable->getType();
1508
1509 Constant *initializer = global_variable->getInitializer();
1510
1511 llvm::Type *initializer_type = initializer->getType();
1512
1513 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1514
1515 lldb_private::DataBufferHeap data(size, '\0');
1516
1517 if (initializer)
1518 if (!MaterializeInitializer(data.GetBytes(), initializer))
1519 return false;
1520
1521 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1522
1523 Constant *new_pointer = BuildRelocation(variable_type, offset);
1524
1525 global_variable->replaceAllUsesWith(new_pointer);
1526
1527 global_variable->eraseFromParent();
1528
1529 return true;
1530}
1531
Sean Callanan97c924e2011-01-27 01:07:04 +00001532// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001533bool
Sean Callananc0492742011-05-23 21:40:23 +00001534IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001535{
Greg Claytone005f2c2010-11-06 01:53:30 +00001536 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001537
1538 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001539 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001540
Greg Clayton8de27c72010-10-15 22:48:33 +00001541 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001542 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001543 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001544 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001545 default:
1546 break;
1547 case Instruction::GetElementPtr:
1548 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001549 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001550 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001551 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001552 }
1553 }
Sean Callananf921cf52010-12-03 19:51:05 +00001554 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001555 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001556 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1557 return MaterializeInternalVariable(global_variable);
1558
Sean Callananc0492742011-05-23 21:40:23 +00001559 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001560
Sean Callananf5857a02010-07-31 01:32:05 +00001561 if (!named_decl)
1562 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001563 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001564 return true;
1565
Sean Callanan7cd46742010-12-06 00:56:39 +00001566 if (!global_variable->hasExternalLinkage())
1567 return true;
1568
Sean Callananf5857a02010-07-31 01:32:05 +00001569 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001570 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001571
Sean Callananf5857a02010-07-31 01:32:05 +00001572 return false;
1573 }
1574
Greg Clayton8de27c72010-10-15 22:48:33 +00001575 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001576
Sean Callanan771131d2010-09-30 21:18:25 +00001577 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001578 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001579
1580 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001581 {
Sean Callanan771131d2010-09-30 21:18:25 +00001582 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001583 ast_context = &value_decl->getASTContext();
1584 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001585 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001586 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001587 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001588 }
Sean Callanan771131d2010-09-30 21:18:25 +00001589
Sean Callanan6a925532011-01-13 08:53:35 +00001590 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001591 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001592
Sean Callanan97678d12011-01-13 21:23:32 +00001593 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001594 {
1595 // The $__lldb_expr_result name indicates the the return value has allocated as
1596 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1597 // accesses to this static variable need to be redirected to the result of dereferencing
1598 // a pointer that is passed in as one of the arguments.
1599 //
1600 // Consequently, when reporting the size of the type, we report a pointer type pointing
1601 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001602 //
1603 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001604
Sean Callanan6a925532011-01-13 08:53:35 +00001605 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1606 value_type = PointerType::get(global_variable->getType(), 0);
1607 }
1608 else
1609 {
1610 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1611 value_type = global_variable->getType();
1612 }
Sean Callanan771131d2010-09-30 21:18:25 +00001613
1614 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1615 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001616
Sean Callanan771131d2010-09-30 21:18:25 +00001617 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001618 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001619 name.c_str(),
1620 qual_type.getAsString().c_str(),
1621 PrintType(value_type).c_str(),
1622 value_size,
1623 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001624
Sean Callanan8bce6652010-07-13 21:41:46 +00001625
Sean Callanan8c127202010-08-23 23:09:38 +00001626 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001627 lldb_private::ConstString (name.c_str()),
1628 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001629 value_size,
1630 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001631 {
1632 if (!global_variable->hasExternalLinkage())
1633 return true;
1634 else
1635 return false;
1636 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001637 }
Sean Callananf3143b72010-12-03 03:02:31 +00001638 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001639 {
1640 if (log)
1641 log->Printf("Function pointers aren't handled right now");
1642
1643 return false;
1644 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001645
1646 return true;
1647}
1648
Sean Callanan97c924e2011-01-27 01:07:04 +00001649// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001650bool
Sean Callananc0492742011-05-23 21:40:23 +00001651IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001652{
Sean Callananc7674af2011-01-17 23:42:46 +00001653 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1654
1655 lldb_private::ConstString name(symbol->getName().str().c_str());
1656
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001657 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001658
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001659 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001660 {
1661 if (log)
1662 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1663
1664 return false;
1665 }
1666
1667 if (log)
1668 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1669
Sean Callanan9b6898f2011-07-30 02:42:06 +00001670 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001671
Sean Callanan9b6898f2011-07-30 02:42:06 +00001672 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1673 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001674
1675 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1676
1677 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1678
1679 if (log)
1680 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1681
1682 symbol->replaceAllUsesWith(symbol_addr_ptr);
1683
1684 return true;
1685}
1686
1687bool
Sean Callananc0492742011-05-23 21:40:23 +00001688IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001689{
Sean Callanan48443652010-12-02 19:47:57 +00001690 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1691
1692 if (log)
1693 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001694
Sean Callanan6ba533e2010-11-17 23:00:36 +00001695 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001696 op_index < num_ops;
1697 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001698 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001699 {
1700 if (m_error_stream)
1701 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1702
Sean Callanandc27aba2010-10-05 22:26:43 +00001703 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001704 }
1705
Sean Callanandc27aba2010-10-05 22:26:43 +00001706 return true;
1707}
1708
1709bool
Sean Callanan9911d2f2011-11-01 23:38:03 +00001710IRForTarget::HandleObjCClass(Value *classlist_reference)
1711{
1712 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1713
1714 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1715
1716 if (!global_variable)
1717 return false;
1718
1719 Constant *initializer = global_variable->getInitializer();
1720
1721 if (!initializer)
1722 return false;
1723
1724 if (!initializer->hasName())
1725 return false;
1726
1727 StringRef name(initializer->getName());
1728 lldb_private::ConstString name_cstr(name.str().c_str());
1729 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr);
1730
1731 if (log)
1732 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1733
1734 if (class_ptr == LLDB_INVALID_ADDRESS)
1735 return false;
1736
1737 if (global_variable->use_begin() == global_variable->use_end())
1738 return false;
1739
1740 LoadInst *load_instruction = NULL;
1741
1742 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1743 i != e;
1744 ++i)
1745 {
1746 if ((load_instruction = dyn_cast<LoadInst>(*i)))
1747 break;
1748 }
1749
1750 if (!load_instruction)
1751 return false;
1752
1753 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1754 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1755
1756 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1757 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1758
1759 load_instruction->replaceAllUsesWith(class_bitcast);
1760
1761 load_instruction->eraseFromParent();
1762
1763 return true;
1764}
1765
1766bool
Sean Callananc0492742011-05-23 21:40:23 +00001767IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001768{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001769 /////////////////////////////////////////////////////////////////////////
1770 // Prepare the current basic block for execution in the remote process
1771 //
1772
Sean Callanan02fbafa2010-07-27 21:39:39 +00001773 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001774
Greg Clayton3c7feb42010-11-19 01:05:25 +00001775 for (ii = basic_block.begin();
1776 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001777 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001778 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001779 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001780
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001781 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001782
Sean Callanan97c924e2011-01-27 01:07:04 +00001783 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001784 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001785 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001786 }
1787
1788 return true;
1789}
1790
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001791bool
Sean Callananc0492742011-05-23 21:40:23 +00001792IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001793{
Sean Callananae71e302010-11-18 22:21:58 +00001794 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1795
Sean Callananc0492742011-05-23 21:40:23 +00001796 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001797 global != end;
1798 ++global)
1799 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001800 if (log)
1801 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1802 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001803 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001804
Sean Callanan9911d2f2011-11-01 23:38:03 +00001805 std::string global_name = (*global).getName().str();
1806
1807 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc7674af2011-01-17 23:42:46 +00001808 {
Sean Callananc0492742011-05-23 21:40:23 +00001809 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001810 {
1811 if (m_error_stream)
1812 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1813
Sean Callananc7674af2011-01-17 23:42:46 +00001814 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001815 }
Sean Callananc7674af2011-01-17 23:42:46 +00001816 }
Sean Callanan9911d2f2011-11-01 23:38:03 +00001817 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1818 {
1819 if (!HandleObjCClass(global))
1820 {
1821 if (m_error_stream)
1822 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1823
1824 return false;
1825 }
1826 }
Sean Callananc0492742011-05-23 21:40:23 +00001827 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001828 {
Sean Callananc0492742011-05-23 21:40:23 +00001829 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001830 {
1831 if (m_error_stream)
1832 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1833
Sean Callananc7674af2011-01-17 23:42:46 +00001834 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001835 }
Sean Callananc7674af2011-01-17 23:42:46 +00001836 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001837 }
1838
1839 return true;
1840}
1841
Sean Callananc0492742011-05-23 21:40:23 +00001842bool
1843IRForTarget::ReplaceStrings ()
1844{
1845 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1846
1847 if (!m_data_allocator)
1848 return true; // hope for the best; some clients may not want static allocation!
1849
1850 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1851
1852 OffsetsTy offsets;
1853
1854 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1855 gi != ge;
1856 ++gi)
1857 {
1858 GlobalVariable *gv = gi;
1859
1860 if (!gv->hasInitializer())
1861 continue;
1862
1863 Constant *gc = gv->getInitializer();
1864
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001865 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001866
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001867 if (gc->isNullValue())
1868 {
1869 Type *gc_type = gc->getType();
1870
1871 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1872
1873 if (!gc_array_type)
1874 continue;
1875
1876 Type *gc_element_type = gc_array_type->getElementType();
1877
1878 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1879
1880 if (gc_integer_type->getBitWidth() != 8)
1881 continue;
1882
1883 str = "";
1884 }
1885 else
1886 {
1887 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1888
1889 if (!gc_array)
1890 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001891
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001892 if (!gc_array->isCString())
1893 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001894
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001895 if (log)
1896 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001897
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001898 str = gc_array->getAsString();
1899 }
1900
Sean Callananc0492742011-05-23 21:40:23 +00001901 offsets[gv] = m_data_allocator->GetStream().GetSize();
1902
1903 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1904 }
1905
Sean Callanan9b6898f2011-07-30 02:42:06 +00001906 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001907
1908 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1909 oi != oe;
1910 ++oi)
1911 {
1912 GlobalVariable *gv = oi->first;
1913 size_t offset = oi->second;
1914
1915 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1916
1917 if (log)
1918 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1919
1920 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1921 ui != ue;
1922 ++ui)
1923 {
1924 if (log)
1925 log->Printf("Found use %s", PrintValue(*ui).c_str());
1926
1927 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1928 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1929
1930 if (const_expr)
1931 {
1932 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1933 {
1934 if (log)
1935 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1936
1937 return false;
1938 }
1939
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001940 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1941 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1942
1943 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001944 }
1945 else if (store_inst)
1946 {
1947 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1948
1949 store_inst->setOperand(0, bit_cast);
1950 }
1951 else
1952 {
1953 if (log)
1954 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1955
1956 return false;
1957 }
1958 }
1959
1960 gv->eraseFromParent();
1961 }
1962
1963 return true;
1964}
1965
1966bool
1967IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1968{
1969 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1970
1971 if (!m_data_allocator)
1972 return true;
1973
1974 typedef SmallVector <Value*, 2> ConstantList;
1975 typedef SmallVector <llvm::Instruction*, 2> UserList;
1976 typedef ConstantList::iterator ConstantIterator;
1977 typedef UserList::iterator UserIterator;
1978
1979 ConstantList static_constants;
1980 UserList static_users;
1981
1982 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1983 ii != ie;
1984 ++ii)
1985 {
1986 llvm::Instruction &inst = *ii;
1987
1988 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1989 oi != oe;
1990 ++oi)
1991 {
1992 Value *operand_val = oi->get();
1993
1994 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1995
1996 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1997 {
1998 static_constants.push_back(operand_val);
1999 static_users.push_back(ii);
2000 }
2001 }
2002 }
2003
2004 ConstantIterator constant_iter;
2005 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00002006
Sean Callananc0492742011-05-23 21:40:23 +00002007 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2008 constant_iter != static_constants.end();
2009 ++constant_iter, ++user_iter)
2010 {
2011 Value *operand_val = *constant_iter;
2012 llvm::Instruction *inst = *user_iter;
2013
2014 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2015
2016 if (operand_constant_fp)
2017 {
2018 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2019 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2020
2021 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2022 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2023
2024 if (log)
2025 {
2026 std::string s;
2027 raw_string_ostream ss(s);
2028 for (size_t index = 0;
2029 index < operand_data_size;
2030 ++index)
2031 {
2032 ss << (uint32_t)operand_raw_data[index];
2033 ss << " ";
2034 }
2035 ss.flush();
2036
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002037 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00002038 }
2039
2040 lldb_private::DataBufferHeap data(operand_data_size, 0);
2041
2042 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
2043 {
2044 uint8_t *data_bytes = data.GetBytes();
2045
2046 for (size_t index = 0;
2047 index < operand_data_size;
2048 ++index)
2049 {
2050 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2051 }
2052 }
2053 else
2054 {
2055 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2056 }
2057
2058 uint64_t offset = m_data_allocator->GetStream().GetSize();
2059
2060 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
2061
Sean Callanan9b6898f2011-07-30 02:42:06 +00002062 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00002063
2064 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2065
2066 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2067
2068 operand_constant_fp->replaceAllUsesWith(fp_load);
2069 }
2070 }
2071
2072 return true;
2073}
2074
Sean Callanan02fbafa2010-07-27 21:39:39 +00002075static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00002076{
Sean Callanan58baaad2011-07-08 00:39:14 +00002077 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00002078
Sean Callanan6ba533e2010-11-17 23:00:36 +00002079 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00002080 return false;
2081
Sean Callanan58baaad2011-07-08 00:39:14 +00002082 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002083
2084 if ((CE = dyn_cast<ConstantExpr>(V)))
2085 {
2086 if (CE->getOpcode() != Instruction::BitCast)
2087 return false;
2088
Sean Callanan6ba533e2010-11-17 23:00:36 +00002089 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002090 }
2091
Sean Callanan6ba533e2010-11-17 23:00:36 +00002092 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00002093
2094 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2095 return false;
2096
2097 return true;
2098}
2099
Sean Callananc0492742011-05-23 21:40:23 +00002100void
2101IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00002102{
Sean Callananc0492742011-05-23 21:40:23 +00002103 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002104
2105 Value::use_iterator ui;
2106
2107 for (ui = guard_load->use_begin();
2108 ui != guard_load->use_end();
2109 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002110 {
Greg Clayton6e713402010-07-30 20:30:44 +00002111 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002112 {
2113 // do nothing for the moment
2114 }
2115 else
2116 {
2117 ui->replaceUsesOfWith(guard_load, zero);
2118 }
2119 }
Sean Callanan45839272010-07-24 01:37:44 +00002120
2121 guard_load->eraseFromParent();
2122}
2123
2124static void ExciseGuardStore(Instruction* guard_store)
2125{
2126 guard_store->eraseFromParent();
2127}
2128
2129bool
Sean Callananc0492742011-05-23 21:40:23 +00002130IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002131{
2132 ///////////////////////////////////////////////////////
2133 // Eliminate any reference to guard variables found.
2134 //
2135
Sean Callanan02fbafa2010-07-27 21:39:39 +00002136 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002137
Sean Callanan02fbafa2010-07-27 21:39:39 +00002138 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002139 typedef InstrList::iterator InstrIterator;
2140
2141 InstrList guard_loads;
2142 InstrList guard_stores;
2143
Greg Clayton3c7feb42010-11-19 01:05:25 +00002144 for (ii = basic_block.begin();
2145 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002146 ++ii)
2147 {
2148 Instruction &inst = *ii;
2149
2150 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2151 if (isGuardVariableRef(load->getPointerOperand()))
2152 guard_loads.push_back(&inst);
2153
2154 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2155 if (isGuardVariableRef(store->getPointerOperand()))
2156 guard_stores.push_back(&inst);
2157 }
2158
2159 InstrIterator iter;
2160
2161 for (iter = guard_loads.begin();
2162 iter != guard_loads.end();
2163 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002164 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002165
2166 for (iter = guard_stores.begin();
2167 iter != guard_stores.end();
2168 ++iter)
2169 ExciseGuardStore(*iter);
2170
2171 return true;
2172}
2173
Sean Callanan97c924e2011-01-27 01:07:04 +00002174// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002175bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002176IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002177{
Greg Claytone005f2c2010-11-06 01:53:30 +00002178 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002179
2180 Value::use_iterator ui;
2181
Sean Callanana48fe162010-08-11 03:57:18 +00002182 SmallVector<User*, 16> users;
2183
2184 // We do this because the use list might change, invalidating our iterator.
2185 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002186 for (ui = old_constant->use_begin();
2187 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002188 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002189 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002190
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002191 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002192 i < users.size();
2193 ++i)
2194 {
2195 User *user = users[i];
2196
Sean Callananbafd6852010-07-14 23:40:29 +00002197 if (Constant *constant = dyn_cast<Constant>(user))
2198 {
2199 // synthesize a new non-constant equivalent of the constant
2200
2201 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2202 {
2203 switch (constant_expr->getOpcode())
2204 {
2205 default:
2206 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002207 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002208 return false;
2209 case Instruction::BitCast:
2210 {
2211 // UnaryExpr
2212 // OperandList[0] is value
2213
2214 Value *s = constant_expr->getOperand(0);
2215
Greg Clayton3c7feb42010-11-19 01:05:25 +00002216 if (s == old_constant)
2217 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002218
Sean Callananc0492742011-05-23 21:40:23 +00002219 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002220
Greg Clayton3c7feb42010-11-19 01:05:25 +00002221 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002222 }
2223 break;
2224 case Instruction::GetElementPtr:
2225 {
2226 // GetElementPtrConstantExpr
2227 // OperandList[0] is base
2228 // OperandList[1]... are indices
2229
2230 Value *ptr = constant_expr->getOperand(0);
2231
Greg Clayton3c7feb42010-11-19 01:05:25 +00002232 if (ptr == old_constant)
2233 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002234
2235 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002236
2237 unsigned operand_index;
2238 unsigned num_operands = constant_expr->getNumOperands();
2239
2240 for (operand_index = 1;
2241 operand_index < num_operands;
2242 ++operand_index)
2243 {
2244 Value *operand = constant_expr->getOperand(operand_index);
2245
Greg Clayton3c7feb42010-11-19 01:05:25 +00002246 if (operand == old_constant)
2247 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002248
Sean Callanan9b6898f2011-07-30 02:42:06 +00002249 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002250 }
2251
Sean Callanan9b6898f2011-07-30 02:42:06 +00002252 ArrayRef <Value*> indices(index_vector);
2253
2254 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002255
Greg Clayton3c7feb42010-11-19 01:05:25 +00002256 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002257 }
2258 break;
2259 }
2260 }
2261 else
2262 {
2263 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002264 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002265 return false;
2266 }
2267 }
2268 else
2269 {
2270 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002271 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002272 }
2273 }
2274
2275 return true;
2276}
2277
Sean Callanan8bce6652010-07-13 21:41:46 +00002278bool
Sean Callananc0492742011-05-23 21:40:23 +00002279IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002280{
Sean Callanane8a59a82010-09-13 21:34:21 +00002281 if (!m_resolve_vars)
2282 return true;
2283
Greg Claytone005f2c2010-11-06 01:53:30 +00002284 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002285
2286 m_decl_map->DoStructLayout();
2287
2288 if (log)
2289 log->Printf("Element arrangement:");
2290
2291 uint32_t num_elements;
2292 uint32_t element_index;
2293
2294 size_t size;
2295 off_t alignment;
2296
2297 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2298 return false;
2299
Greg Clayton3c7feb42010-11-19 01:05:25 +00002300 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002301
Greg Clayton3c7feb42010-11-19 01:05:25 +00002302 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002303 {
2304 if (m_error_stream)
2305 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2306
Sean Callanan8bce6652010-07-13 21:41:46 +00002307 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002308 }
2309
Sean Callanan02fbafa2010-07-27 21:39:39 +00002310 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002311
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002312 if (argument->getName().equals("this"))
2313 {
2314 ++iter;
2315
Greg Clayton3c7feb42010-11-19 01:05:25 +00002316 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002317 {
2318 if (m_error_stream)
2319 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2320
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002321 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002322 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002323
2324 argument = iter;
2325 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002326 else if (argument->getName().equals("self"))
2327 {
2328 ++iter;
2329
2330 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002331 {
2332 if (m_error_stream)
2333 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2334
Sean Callanan3aa7da52010-12-13 22:46:15 +00002335 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002336 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002337
2338 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002339 {
2340 if (m_error_stream)
2341 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2342
Sean Callanan3aa7da52010-12-13 22:46:15 +00002343 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002344 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002345
2346 ++iter;
2347
2348 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002349 {
2350 if (m_error_stream)
2351 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2352
Sean Callanan3aa7da52010-12-13 22:46:15 +00002353 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002354 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002355
2356 argument = iter;
2357 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002358
Greg Clayton8de27c72010-10-15 22:48:33 +00002359 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002360 {
2361 if (m_error_stream)
2362 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2363
Sean Callanan8bce6652010-07-13 21:41:46 +00002364 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002365 }
2366
Sean Callanan8bce6652010-07-13 21:41:46 +00002367 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002368 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002369
Greg Clayton3c7feb42010-11-19 01:05:25 +00002370 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002371 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002372
Sean Callanan6ba533e2010-11-17 23:00:36 +00002373 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002374 {
2375 if (m_error_stream)
2376 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2377
Sean Callanan8bce6652010-07-13 21:41:46 +00002378 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002379 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002380
Sean Callananc0492742011-05-23 21:40:23 +00002381 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002382 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002383
2384 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002385 {
2386 if (m_error_stream)
2387 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2388
Sean Callanan8bce6652010-07-13 21:41:46 +00002389 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002390 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002391
2392 for (element_index = 0; element_index < num_elements; ++element_index)
2393 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002394 const clang::NamedDecl *decl = NULL;
2395 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002396 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002397 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002398
Sean Callanan45690fe2010-08-30 22:17:16 +00002399 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002400 {
2401 if (m_error_stream)
2402 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2403
Sean Callanan8bce6652010-07-13 21:41:46 +00002404 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002405 }
2406
Sean Callanan8bce6652010-07-13 21:41:46 +00002407 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002408 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002409 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002410 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002411 offset);
2412
Sean Callanan9b6898f2011-07-30 02:42:06 +00002413 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002414 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002415
Sean Callananc7ca4662011-10-25 18:36:40 +00002416 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002417 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002418 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002419
Sean Callananc7ca4662011-10-25 18:36:40 +00002420 if (log)
2421 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002422
Sean Callananc7ca4662011-10-25 18:36:40 +00002423 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2424 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2425 // entry in order to produce the static variable that the AST thinks it is accessing.
2426 if (name == m_result_name && !m_result_is_pointer)
2427 {
2428 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2429
2430 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2431
2432 replacement = load;
2433 }
2434 else
2435 {
2436 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2437
2438 replacement = bit_cast;
2439 }
2440
2441 if (Constant *constant = dyn_cast<Constant>(value))
2442 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2443 else
2444 value->replaceAllUsesWith(replacement);
2445
2446 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2447 var->eraseFromParent();
2448 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002449 }
2450
2451 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002452 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002453
2454 return true;
2455}
2456
Sean Callananc0492742011-05-23 21:40:23 +00002457llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002458IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002459 uint64_t offset)
2460{
2461 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2462
Sean Callanan9b6898f2011-07-30 02:42:06 +00002463 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2464 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002465
2466 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002467
2468 llvm::Constant *offset_array[1];
2469
2470 offset_array[0] = offset_int;
2471
2472 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2473
2474 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002475 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2476
2477 return reloc_getbitcast;
2478}
2479
2480bool
2481IRForTarget::CompleteDataAllocation ()
2482{
Sean Callanan47dc4572011-09-15 02:13:07 +00002483 if (!m_data_allocator)
2484 return true;
2485
Sean Callananc0492742011-05-23 21:40:23 +00002486 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2487
2488 if (!m_data_allocator->GetStream().GetSize())
2489 return true;
2490
2491 lldb::addr_t allocation = m_data_allocator->Allocate();
2492
2493 if (log)
2494 {
2495 if (allocation)
2496 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2497 else
2498 log->Printf("Failed to allocate static data");
2499 }
2500
2501 if (!allocation)
2502 return false;
2503
Sean Callanan9b6898f2011-07-30 02:42:06 +00002504 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2505 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002506
2507 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2508 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2509
2510 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2511
2512 m_reloc_placeholder->eraseFromParent();
2513
2514 return true;
2515}
2516
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002517bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002518IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002519{
Greg Claytone005f2c2010-11-06 01:53:30 +00002520 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002521
Sean Callananc0492742011-05-23 21:40:23 +00002522 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002523 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002524
2525 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002526
2527 if (!function)
2528 {
2529 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002530 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002531
2532 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002533 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 +00002534
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002535 return false;
2536 }
Sean Callananc0492742011-05-23 21:40:23 +00002537
2538 if (!FixFunctionLinkage (*function))
2539 {
2540 if (log)
2541 log->Printf("Couldn't fix the linkage for the function");
2542
2543 return false;
2544 }
2545
Sean Callananc7ca4662011-10-25 18:36:40 +00002546 if (log)
2547 {
2548 std::string s;
2549 raw_string_ostream oss(s);
2550
2551 m_module->print(oss, NULL);
2552
2553 oss.flush();
2554
2555 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2556 }
2557
Sean Callanan9b6898f2011-07-30 02:42:06 +00002558 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002559
2560 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2561 intptr_ty,
2562 false /* isConstant */,
2563 GlobalVariable::InternalLinkage,
2564 Constant::getNullValue(intptr_ty),
2565 "reloc_placeholder",
2566 NULL /* InsertBefore */,
2567 false /* ThreadLocal */,
2568 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002569
Sean Callanan02fbafa2010-07-27 21:39:39 +00002570 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002571
Sean Callananc0492742011-05-23 21:40:23 +00002572 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002573
Sean Callanan82b74c82010-08-12 01:56:52 +00002574 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002575 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002576 //
2577
Sean Callananc0492742011-05-23 21:40:23 +00002578 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002579 {
2580 if (log)
2581 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002582
2583 // CreateResultVariable() reports its own errors, so we don't do so here
2584
Sean Callanan82b74c82010-08-12 01:56:52 +00002585 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002586 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002587
2588 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2589 {
2590 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002591 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002592 }
2593
2594 for (bbi = function->begin();
2595 bbi != function->end();
2596 ++bbi)
2597 {
2598 if (!RemoveGuards(*bbi))
2599 {
2600 if (log)
2601 log->Printf("RemoveGuards() failed");
2602
2603 // RemoveGuards() reports its own errors, so we don't do so here
2604
2605 return false;
2606 }
2607
2608 if (!RewritePersistentAllocs(*bbi))
2609 {
2610 if (log)
2611 log->Printf("RewritePersistentAllocs() failed");
2612
2613 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2614
2615 return false;
2616 }
2617 }
2618
2619 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2620 {
2621 IRInterpreter interpreter (*m_decl_map,
2622 m_error_stream);
2623
2624 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2625 {
2626 m_interpret_success = true;
2627 return true;
2628 }
2629 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002630
Sean Callanan7b8eb762011-11-01 17:33:54 +00002631 if (log && log->GetVerbose())
Sean Callananc0492742011-05-23 21:40:23 +00002632 {
2633 std::string s;
2634 raw_string_ostream oss(s);
2635
2636 m_module->print(oss, NULL);
2637
2638 oss.flush();
2639
2640 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2641 }
2642
Sean Callanan6ba533e2010-11-17 23:00:36 +00002643 ///////////////////////////////////////////////////////////////////////////////
2644 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2645 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002646
Sean Callananc0492742011-05-23 21:40:23 +00002647 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002648 {
2649 if (log)
2650 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002651
2652 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2653
Sean Callanan6ba533e2010-11-17 23:00:36 +00002654 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002655 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002656
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002657 ///////////////////////////////
2658 // Resolve function pointers
2659 //
2660
2661 if (!ResolveFunctionPointers(llvm_module, *function))
2662 {
2663 if (log)
2664 log->Printf("ResolveFunctionPointers() failed");
2665
2666 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2667
2668 return false;
2669 }
2670
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002671 for (bbi = function->begin();
2672 bbi != function->end();
2673 ++bbi)
2674 {
Sean Callananc0492742011-05-23 21:40:23 +00002675 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002676 {
2677 if (log)
2678 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002679
2680 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2681
Sean Callanana48fe162010-08-11 03:57:18 +00002682 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002683 }
Sean Callanana48fe162010-08-11 03:57:18 +00002684
Sean Callananc0492742011-05-23 21:40:23 +00002685 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002686 {
2687 if (log)
2688 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002689
2690 // ResolveCalls() reports its own errors, so we don't do so here
2691
Sean Callanan8bce6652010-07-13 21:41:46 +00002692 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002693 }
Sean Callananc0492742011-05-23 21:40:23 +00002694
2695 if (!ReplaceStaticLiterals(*bbi))
2696 {
2697 if (log)
2698 log->Printf("ReplaceStaticLiterals() failed");
2699
2700 return false;
2701 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002702 }
2703
Sean Callanan771131d2010-09-30 21:18:25 +00002704 ///////////////////////////////
2705 // Run function-level passes
2706 //
2707
Sean Callananc0492742011-05-23 21:40:23 +00002708 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002709 {
2710 if (log)
2711 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002712
2713 // ResolveExternals() reports its own errors, so we don't do so here
2714
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002715 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002716 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002717
Sean Callananc0492742011-05-23 21:40:23 +00002718 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002719 {
2720 if (log)
2721 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002722
2723 // ReplaceVariables() reports its own errors, so we don't do so here
2724
Sean Callanan771131d2010-09-30 21:18:25 +00002725 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002726 }
Sean Callanan771131d2010-09-30 21:18:25 +00002727
Sean Callananc0492742011-05-23 21:40:23 +00002728 if (!ReplaceStrings())
2729 {
2730 if (log)
2731 log->Printf("ReplaceStrings() failed");
2732
2733 return false;
2734 }
2735
2736 if (!CompleteDataAllocation())
2737 {
2738 if (log)
2739 log->Printf("CompleteDataAllocation() failed");
2740
2741 return false;
2742 }
2743
Sean Callanan7b8eb762011-11-01 17:33:54 +00002744 if (log && log->GetVerbose())
Sean Callanan8bce6652010-07-13 21:41:46 +00002745 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002746 std::string s;
2747 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002748
Sean Callananc0492742011-05-23 21:40:23 +00002749 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002750
2751 oss.flush();
2752
Greg Claytonb5037af2010-11-15 01:47:11 +00002753 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002754 }
2755
2756 return true;
2757}
2758
2759void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002760IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002761{
2762}
2763
2764PassManagerType
2765IRForTarget::getPotentialPassManagerType() const
2766{
2767 return PMT_ModulePassManager;
2768}