blob: b158732c741be6719c4a9c9f4986ec81b06bc8ef [file] [log] [blame]
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan2ab712f22010-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"
Chandler Carruth1e157582013-01-02 12:20:07 +000013#include "llvm/IR/Constants.h"
14#include "llvm/IR/DataLayout.h"
15#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/Module.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000019#include "llvm/PassManager.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000020#include "llvm/Transforms/IPO.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000021#include "llvm/IR/ValueSymbolTable.h"
Sean Callanan549c9f72010-07-13 21:41:46 +000022
23#include "clang/AST/ASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000024
25#include "lldb/Core/dwarf.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000026#include "lldb/Core/ConstString.h"
27#include "lldb/Core/DataBufferHeap.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/Scalar.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000032#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000033#include "lldb/Expression/IRInterpreter.h"
Sean Callanan79763a42011-05-23 21:40:23 +000034#include "lldb/Host/Endian.h"
Sean Callanan63697e52011-05-07 01:06:41 +000035#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000036
37#include <map>
38
39using namespace llvm;
40
Sean Callananeaacbc92010-08-18 18:50:51 +000041static char ID;
42
Sean Callanan8dfb68e2013-03-19 00:10:07 +000043IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
44 m_execution_unit(execution_unit),
45 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000046{
47}
48
Sean Callanan8dfb68e2013-03-19 00:10:07 +000049lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000050{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000051 lldb_private::Error err;
52
53 if (m_allocation != LLDB_INVALID_ADDRESS)
54 {
55 m_execution_unit.FreeNow(m_allocation);
56 m_allocation = LLDB_INVALID_ADDRESS;
57 }
58
59 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
60
61 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000062}
63
Greg Clayton1b95a6f2010-11-19 01:05:25 +000064IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
65 bool resolve_vars,
Sean Callanan3bfdaa22011-09-15 02:13:07 +000066 lldb_private::ExecutionPolicy execution_policy,
Sean Callanan63697e52011-05-07 01:06:41 +000067 lldb::ClangExpressionVariableSP &const_result,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000068 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000069 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000070 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +000071 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +000072 m_resolve_vars(resolve_vars),
Sean Callanan3bfdaa22011-09-15 02:13:07 +000073 m_execution_policy(execution_policy),
74 m_interpret_success(false),
Stephen Wilson71c21d12011-04-11 19:41:40 +000075 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +000076 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +000077 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000078 m_data_allocator(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +000079 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +000080 m_sel_registerName(NULL),
Johnny Chen44805302011-07-19 19:48:13 +000081 m_const_result(const_result),
Stephen Wilson71c21d12011-04-11 19:41:40 +000082 m_error_stream(error_stream),
Sean Callanan92adcac2011-01-13 08:53:35 +000083 m_has_side_effects(false),
Sean Callanan63697e52011-05-07 01:06:41 +000084 m_result_store(NULL),
85 m_result_is_pointer(false),
Sean Callanan79763a42011-05-23 21:40:23 +000086 m_reloc_placeholder(NULL)
Sean Callanan2ab712f22010-07-03 01:35:46 +000087{
88}
89
Sean Callanan038df5032010-09-30 21:18:25 +000090/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +000091
92static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +000093PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +000094{
95 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +000096 if (value)
97 {
98 raw_string_ostream rso(s);
99 value->print(rso);
100 rso.flush();
101 if (truncate)
102 s.resize(s.length() - 1);
103 }
Sean Callanan2235f322010-08-11 03:57:18 +0000104 return s;
105}
106
Sean Callanan038df5032010-09-30 21:18:25 +0000107static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000108PrintType(const Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000109{
110 std::string s;
111 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000112 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000113 rso.flush();
114 if (truncate)
115 s.resize(s.length() - 1);
116 return s;
117}
118
Sean Callanan2ab712f22010-07-03 01:35:46 +0000119IRForTarget::~IRForTarget()
120{
121}
122
Sean Callanan79763a42011-05-23 21:40:23 +0000123bool
124IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
125{
126 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
127
128 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
129
Sean Callanan7f27d602011-11-19 02:54:21 +0000130 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000131
132 return true;
133}
134
Sean Callanand1e5b432010-08-12 01:56:52 +0000135bool
Sean Callanan79763a42011-05-23 21:40:23 +0000136IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000137{
138 llvm::Function::iterator bbi;
139 BasicBlock::iterator ii;
Sean Callanan63697e52011-05-07 01:06:41 +0000140
Sean Callanane4ec90e2010-12-16 03:17:46 +0000141 for (bbi = llvm_function.begin();
142 bbi != llvm_function.end();
143 ++bbi)
144 {
145 BasicBlock &basic_block = *bbi;
146
147 for (ii = basic_block.begin();
148 ii != basic_block.end();
149 ++ii)
150 {
151 switch (ii->getOpcode())
152 {
153 default:
154 return true;
155 case Instruction::Store:
156 {
157 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
158
159 Value *store_ptr = store_inst->getPointerOperand();
160
Sean Callanan63697e52011-05-07 01:06:41 +0000161 std::string ptr_name;
162
163 if (store_ptr->hasName())
Sean Callanan7f27d602011-11-19 02:54:21 +0000164 ptr_name = store_ptr->getName().str();
Sean Callanan63697e52011-05-07 01:06:41 +0000165
166 if (isa <AllocaInst> (store_ptr))
Sean Callanane4ec90e2010-12-16 03:17:46 +0000167 break;
Sean Callanan63697e52011-05-07 01:06:41 +0000168
169 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
170 {
171 if (ptr_name.find("GV") == std::string::npos)
172 m_result_store = store_inst;
173 }
174 else
175 {
176 return true;
177 }
178
179 break;
Sean Callanane4ec90e2010-12-16 03:17:46 +0000180 }
181 case Instruction::Load:
182 case Instruction::Alloca:
183 case Instruction::GetElementPtr:
Sean Callanan63697e52011-05-07 01:06:41 +0000184 case Instruction::BitCast:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000185 case Instruction::Ret:
Sean Callanan63697e52011-05-07 01:06:41 +0000186 case Instruction::ICmp:
187 case Instruction::Br:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000188 break;
189 }
190 }
191 }
192
193 return false;
194}
195
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000196bool
197IRForTarget::GetFunctionAddress (llvm::Function *fun,
198 uint64_t &fun_addr,
199 lldb_private::ConstString &name,
200 Constant **&value_ptr)
201{
202 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
203
204 fun_addr = LLDB_INVALID_ADDRESS;
205 name.Clear();
206 value_ptr = NULL;
207
208 if (fun->isIntrinsic())
209 {
210 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
211
212 switch (intrinsic_id)
213 {
214 default:
215 if (log)
216 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
217
218 if (m_error_stream)
219 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
220
221 return false;
222 case Intrinsic::memcpy:
223 {
224 static lldb_private::ConstString g_memcpy_str ("memcpy");
225 name = g_memcpy_str;
226 }
227 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000228 case Intrinsic::memset:
229 {
230 static lldb_private::ConstString g_memset_str ("memset");
231 name = g_memset_str;
232 }
233 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000234 }
235
236 if (log && name)
237 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
238 }
239 else
240 {
241 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
242 }
243
244 // Find the address of the function.
245
246 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000247
248 if (fun_decl)
249 {
Sean Callananc70ed462011-10-25 18:36:40 +0000250 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000251 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000252 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000253 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
254 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000255 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000256 // Check for an alternate mangling for "std::basic_string<char>"
257 // that is part of the itanium C++ name mangling scheme
258 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000259 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000260 {
261 std::string alternate_mangling("_ZNKSs");
262 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000263 altnernate_name.SetCString(alternate_mangling.c_str());
264 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000265 }
266 }
267
268 if (!found_it)
269 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000270 lldb_private::Mangled mangled_name(name);
271 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000272 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000273 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000274 if (alt_mangled_name)
275 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
276 mangled_name.GetName().GetCString(),
277 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000278 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000279 log->Printf("Function \"%s\" had no address",
280 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000281 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000282
283 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000284 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000285 if (alt_mangled_name)
286 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
287 mangled_name.GetName().GetCString(),
288 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000289 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000290 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
291 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000292 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000293 return false;
294 }
295 }
296 }
297 else
298 {
299 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
300 {
301 if (log)
302 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
303
304 if (m_error_stream)
305 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
306
307 return false;
308 }
309 }
310
311 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000312 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000313
314 return true;
315}
316
317llvm::Constant *
318IRForTarget::BuildFunctionPointer (llvm::Type *type,
319 uint64_t ptr)
320{
321 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000322 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000323 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
324 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
325 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
326}
327
Sean Callananfc8feb82011-10-31 22:11:40 +0000328void
329IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
330 llvm::Value *function_ptr,
331 const char *name)
332{
333 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
334
335 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
336 i != e;
337 ++i)
338 {
339 Value *user = *i;
340
341 if (Instruction *user_inst = dyn_cast<Instruction>(user))
342 {
Sean Callanand2b465f2012-02-09 03:22:41 +0000343 Constant *name_array = ConstantDataArray::getString(context, StringRef(name));
Sean Callananfc8feb82011-10-31 22:11:40 +0000344
345 ArrayRef<Value *> md_values(name_array);
346
347 MDNode *metadata = MDNode::get(context, md_values);
348
349 user_inst->setMetadata("lldb.call.realName", metadata);
350 }
351 else
352 {
353 RegisterFunctionMetadata (context, user, name);
354 }
355 }
356}
357
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000358bool
359IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
360 llvm::Function &llvm_function)
361{
362 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
363
364 for (llvm::Module::iterator fi = llvm_module.begin();
365 fi != llvm_module.end();
366 ++fi)
367 {
368 Function *fun = fi;
369
370 bool is_decl = fun->isDeclaration();
371
372 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000373 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000374
375 if (!is_decl)
376 continue;
377
378 if (fun->hasNUses(0))
379 continue; // ignore
380
381 uint64_t addr = LLDB_INVALID_ADDRESS;
382 lldb_private::ConstString name;
383 Constant **value_ptr = NULL;
384
385 if (!GetFunctionAddress(fun,
386 addr,
387 name,
388 value_ptr))
389 return false; // GetFunctionAddress reports its own errors
390
391 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
392
Sean Callananfc8feb82011-10-31 22:11:40 +0000393 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
394
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000395 if (value_ptr)
396 *value_ptr = value;
397
398 fun->replaceAllUsesWith(value);
399 }
400
401 return true;
402}
403
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000404
Sean Callanan63697e52011-05-07 01:06:41 +0000405clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000406IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000407{
408 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
409
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000410 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000411
412 if (!named_metadata)
413 return NULL;
414
415 unsigned num_nodes = named_metadata->getNumOperands();
416 unsigned node_index;
417
418 for (node_index = 0;
419 node_index < num_nodes;
420 ++node_index)
421 {
422 MDNode *metadata_node = named_metadata->getOperand(node_index);
423
424 if (!metadata_node)
425 return NULL;
426
427 if (metadata_node->getNumOperands() != 2)
428 continue;
429
430 if (metadata_node->getOperand(0) != global_val)
431 continue;
432
433 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
434
435 if (!constant_int)
436 return NULL;
437
438 uintptr_t ptr = constant_int->getZExtValue();
439
440 return reinterpret_cast<clang::NamedDecl *>(ptr);
441 }
442
443 return NULL;
444}
445
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000446clang::NamedDecl *
447IRForTarget::DeclForGlobal (GlobalValue *global_val)
448{
449 return DeclForGlobal(global_val, m_module);
450}
451
Sean Callanane4ec90e2010-12-16 03:17:46 +0000452void
453IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
454 const lldb_private::ConstString &name,
455 lldb_private::TypeFromParser type)
456{
Sean Callanan63697e52011-05-07 01:06:41 +0000457 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
458 {
459 switch (init_expr->getOpcode())
460 {
461 default:
462 return;
463 case Instruction::IntToPtr:
464 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
465 return;
466 }
467 }
468 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
469 {
470 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
471 }
472}
473
474void
Sean Callanan79763a42011-05-23 21:40:23 +0000475IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan63697e52011-05-07 01:06:41 +0000476{
477 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
478
479 if (!m_result_store)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000480 return;
481
Sean Callanan63697e52011-05-07 01:06:41 +0000482 LoadInst *original_load = NULL;
483
484 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
485 current_value != NULL;
486 current_value = next_value)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000487 {
Sean Callanan63697e52011-05-07 01:06:41 +0000488 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
489 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
490
491 if (cast_inst)
492 {
493 next_value = cast_inst->getOperand(0);
494 }
Enrico Granata20edcdb2011-07-19 18:03:25 +0000495 else if (load_inst)
Sean Callanan63697e52011-05-07 01:06:41 +0000496 {
497 if (isa<LoadInst>(load_inst->getPointerOperand()))
498 {
499 next_value = load_inst->getPointerOperand();
500 }
501 else
502 {
503 original_load = load_inst;
504 break;
505 }
506 }
507 else
508 {
509 return;
510 }
Sean Callanane4ec90e2010-12-16 03:17:46 +0000511 }
Sean Callanan63697e52011-05-07 01:06:41 +0000512
Jim Ingham28eb5712012-10-12 17:34:26 +0000513 if (!original_load)
514 return;
515
Sean Callanan63697e52011-05-07 01:06:41 +0000516 Value *loaded_value = original_load->getPointerOperand();
517 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
518
519 if (!loaded_global)
520 return;
521
Sean Callanan79763a42011-05-23 21:40:23 +0000522 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000523
524 if (!loaded_decl)
525 return;
526
527 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
528
529 if (!loaded_var)
530 return;
531
532 if (log)
533 {
534 lldb_private::StreamString type_desc_stream;
535 type.DumpTypeDescription(&type_desc_stream);
536
537 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
538 }
539
540 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanane4ec90e2010-12-16 03:17:46 +0000541}
542
543bool
Sean Callanan79763a42011-05-23 21:40:23 +0000544IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000545{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000546 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000547
Sean Callanan9e6ed532010-09-13 21:34:21 +0000548 if (!m_resolve_vars)
549 return true;
550
551 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000552
Sean Callanan79763a42011-05-23 21:40:23 +0000553 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000554
Sean Callanancc427fa2011-07-30 02:42:06 +0000555 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000556 const char *result_name = NULL;
557
558 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
559 vi != ve;
560 ++vi)
561 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000562 result_name_str = vi->first().str();
563 const char *value_name = result_name_str.c_str();
564
565 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000566 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000567 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000568 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000569 m_result_is_pointer = true;
570 break;
571 }
572
Sean Callanancc427fa2011-07-30 02:42:06 +0000573 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000574 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000575 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000576 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000577 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000578 break;
579 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000580 }
581
582 if (!result_name)
583 {
584 if (log)
585 log->PutCString("Couldn't find result variable");
586
587 return true;
588 }
589
Sean Callanan46ae9e52010-09-28 21:13:03 +0000590 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000591 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000592
Sean Callanan79763a42011-05-23 21:40:23 +0000593 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000594
595 if (!result_value)
596 {
597 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000598 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000599
Sean Callanan3989fb92011-01-27 01:07:04 +0000600 if (m_error_stream)
601 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
602
Sean Callananfc55f5d2010-09-21 00:44:12 +0000603 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000604 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000605
Sean Callanand1e5b432010-08-12 01:56:52 +0000606 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000607 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000608
609 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
610
611 if (!result_global)
612 {
613 if (log)
614 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000615
616 if (m_error_stream)
617 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
618
Sean Callanand1e5b432010-08-12 01:56:52 +0000619 return false;
620 }
621
Sean Callanan79763a42011-05-23 21:40:23 +0000622 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000623 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000624 {
625 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000626 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000627
Sean Callanan3989fb92011-01-27 01:07:04 +0000628 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000629 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
Sean Callanan3989fb92011-01-27 01:07:04 +0000630
Sean Callanand1e5b432010-08-12 01:56:52 +0000631 return false;
632 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000633
Sean Callanan63697e52011-05-07 01:06:41 +0000634 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000635 {
Sean Callanan63697e52011-05-07 01:06:41 +0000636 std::string decl_desc_str;
637 raw_string_ostream decl_desc_stream(decl_desc_str);
638 result_decl->print(decl_desc_stream);
639 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000640
Sean Callanan63697e52011-05-07 01:06:41 +0000641 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000642 }
643
Sean Callanan63697e52011-05-07 01:06:41 +0000644 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
645 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000646 {
647 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000648 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000649
650 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000651 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
Sean Callanan3989fb92011-01-27 01:07:04 +0000652
Sean Callanand1e5b432010-08-12 01:56:52 +0000653 return false;
654 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000655
Sean Callanand1e5b432010-08-12 01:56:52 +0000656 // Get the next available result name from m_decl_map and create the persistent
657 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000658
Sean Callanan63697e52011-05-07 01:06:41 +0000659 // If the result is an Lvalue, it is emitted as a pointer; see
660 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000661 if (m_result_is_pointer)
662 {
Sean Callanan63697e52011-05-07 01:06:41 +0000663 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000664 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000665
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000666 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
667 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000668
669 if (pointer_pointertype)
670 {
671 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
672
673 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
674 &result_decl->getASTContext());
675 }
676 else if (pointer_objcobjpointertype)
677 {
678 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
679
680 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
681 &result_decl->getASTContext());
682 }
683 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000684 {
685 if (log)
686 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000687
688 if (m_error_stream)
689 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
690
Sean Callanan92adcac2011-01-13 08:53:35 +0000691 return false;
692 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000693 }
694 else
695 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000696 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000697 &result_decl->getASTContext());
698 }
699
700 if (m_result_type.GetClangTypeBitWidth() == 0)
701 {
702 lldb_private::StreamString type_desc_stream;
703 m_result_type.DumpTypeDescription(&type_desc_stream);
704
705 if (log)
706 log->Printf("Result type has size 0");
707
708 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000709 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000710 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000711 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000712 }
713
Sean Callanan63697e52011-05-07 01:06:41 +0000714 if (log)
715 {
716 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000717 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000718
Sean Callanan00f43622011-11-18 03:28:09 +0000719 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000720 }
721
Sean Callanan92adcac2011-01-13 08:53:35 +0000722 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanand1e5b432010-08-12 01:56:52 +0000723
724 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000725 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000726 m_result_name.GetCString(),
727 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanand1e5b432010-08-12 01:56:52 +0000728
729 // Construct a new result global and set up its metadata
730
Sean Callanan79763a42011-05-23 21:40:23 +0000731 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000732 result_global->getType()->getElementType(),
733 false, /* not constant */
734 GlobalValue::ExternalLinkage,
735 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000736 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000737
738 // It's too late in compilation to create a new VarDecl for this, but we don't
739 // need to. We point the metadata at the old VarDecl. This creates an odd
740 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000741 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000742 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
743 // fixed up.
744
Sean Callanan79763a42011-05-23 21:40:23 +0000745 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000746 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000747 false);
748
749 llvm::Value* values[2];
750 values[0] = new_result_global;
751 values[1] = new_constant_int;
752
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000753 ArrayRef<Value*> value_ref(values, 2);
754
Sean Callanan79763a42011-05-23 21:40:23 +0000755 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
756 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000757 named_metadata->addOperand(persistent_global_md);
758
759 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000760 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000761 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000762 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000763
764 if (result_global->hasNUses(0))
765 {
766 // We need to synthesize a store for this variable, because otherwise
767 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000768
Greg Clayton7b462cc2010-10-15 22:48:33 +0000769 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000770 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
771
772 if (!first_entry_instruction)
773 return false;
774
775 if (!result_global->hasInitializer())
776 {
777 if (log)
778 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000779
780 if (m_error_stream)
781 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
782
Sean Callanan1e87fff2010-09-07 22:43:19 +0000783 return false;
784 }
785
786 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000787
788 // Here we write the initializer into a result variable assuming it
789 // can be computed statically.
790
791 if (!m_has_side_effects)
792 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000793 //MaybeSetConstantResult (initializer,
794 // m_result_name,
795 // m_result_type);
Sean Callanane4ec90e2010-12-16 03:17:46 +0000796 }
Sean Callanan1e87fff2010-09-07 22:43:19 +0000797
Greg Clayton9c139312011-02-05 02:28:58 +0000798 StoreInst *synthesized_store = new StoreInst(initializer,
799 new_result_global,
800 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000801
802 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000803 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000804 }
805 else
806 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000807 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan63697e52011-05-07 01:06:41 +0000808 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000809 //MaybeSetCastResult (m_result_type);
Sean Callanan63697e52011-05-07 01:06:41 +0000810 }
811
Sean Callanan1e87fff2010-09-07 22:43:19 +0000812 result_global->replaceAllUsesWith(new_result_global);
813 }
Sean Callanan63697e52011-05-07 01:06:41 +0000814
815 if (!m_const_result)
Sean Callanan00f43622011-11-18 03:28:09 +0000816 if (!m_decl_map->AddPersistentVariable(result_decl,
817 m_result_name,
818 m_result_type,
819 true,
820 m_result_is_pointer))
821 return false;
Sean Callanan1e87fff2010-09-07 22:43:19 +0000822
Sean Callanand1e5b432010-08-12 01:56:52 +0000823 result_global->eraseFromParent();
824
825 return true;
826}
827
Johnny Chenee7a3592011-08-09 23:10:20 +0000828#if 0
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000829static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000830{
831 if (!depth)
832 return;
833
834 depth--;
835
Johnny Chenee7a3592011-08-09 23:10:20 +0000836 if (log)
837 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000838
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000839 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000840 ui != ue;
841 ++ui)
842 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000843 if (log)
844 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000845 DebugUsers(log, *ui, depth);
846 }
847
Johnny Chenee7a3592011-08-09 23:10:20 +0000848 if (log)
849 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000850}
Johnny Chenee7a3592011-08-09 23:10:20 +0000851#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000852
853bool
Sean Callanan79763a42011-05-23 21:40:23 +0000854IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000855 llvm::GlobalVariable *cstr,
856 Instruction *FirstEntryInstruction)
Sean Callananafe16a72010-11-17 23:00:36 +0000857{
858 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
859
Sean Callanancc427fa2011-07-30 02:42:06 +0000860 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000861
Sean Callanancc427fa2011-07-30 02:42:06 +0000862 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
863 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000864 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +0000865 == Module::Pointer64) ? 64 : 32);
Sean Callanancc427fa2011-07-30 02:42:06 +0000866 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
867 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000868
869 if (!m_CFStringCreateWithBytes)
870 {
871 lldb::addr_t CFStringCreateWithBytes_addr;
872
873 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
874
875 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
876 {
877 if (log)
878 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
879
Sean Callanan3989fb92011-01-27 01:07:04 +0000880 if (m_error_stream)
881 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
882
Sean Callananafe16a72010-11-17 23:00:36 +0000883 return false;
884 }
885
886 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000887 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000888
889 // Build the function type:
890 //
891 // CFStringRef CFStringCreateWithBytes (
892 // CFAllocatorRef alloc,
893 // const UInt8 *bytes,
894 // CFIndex numBytes,
895 // CFStringEncoding encoding,
896 // Boolean isExternalRepresentation
897 // );
898 //
899 // We make the following substitutions:
900 //
901 // CFStringRef -> i8*
902 // CFAllocatorRef -> i8*
903 // UInt8 * -> i8*
904 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
905 // CFStringEncoding -> i32
906 // Boolean -> i8
907
Sean Callanancc427fa2011-07-30 02:42:06 +0000908 Type *arg_type_array[5];
909
910 arg_type_array[0] = i8_ptr_ty;
911 arg_type_array[1] = i8_ptr_ty;
912 arg_type_array[2] = intptr_ty;
913 arg_type_array[3] = i32_ty;
914 arg_type_array[4] = i8_ty;
915
916 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
917
Sean Callanan79763a42011-05-23 21:40:23 +0000918 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000919
920 // Build the constant containing the pointer to the function
921 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
922 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
923 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
924 }
925
Sean Callanand2b465f2012-02-09 03:22:41 +0000926 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000927
928 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000929 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000930
Sean Callananafe16a72010-11-17 23:00:36 +0000931 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000932 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000933 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000934 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
935 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
936
Sean Callanancc427fa2011-07-30 02:42:06 +0000937 Value *argument_array[5];
938
939 argument_array[0] = alloc_arg;
940 argument_array[1] = bytes_arg;
941 argument_array[2] = numBytes_arg;
942 argument_array[3] = encoding_arg;
943 argument_array[4] = isExternal_arg;
944
945 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000946
947 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanancc427fa2011-07-30 02:42:06 +0000948 CFSCWB_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +0000949 "CFStringCreateWithBytes",
950 FirstEntryInstruction);
Sean Callanan7a55a322010-11-18 22:21:58 +0000951
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000952 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callananafe16a72010-11-17 23:00:36 +0000953 {
954 if (log)
955 log->PutCString("Couldn't replace the NSString with the result of the call");
956
Sean Callanan3989fb92011-01-27 01:07:04 +0000957 if (m_error_stream)
958 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
959
Sean Callananafe16a72010-11-17 23:00:36 +0000960 return false;
961 }
962
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000963 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000964
965 return true;
966}
967
968bool
Sean Callanan79763a42011-05-23 21:40:23 +0000969IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callananafe16a72010-11-17 23:00:36 +0000970{
971 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
972
Sean Callanan79763a42011-05-23 21:40:23 +0000973 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000974
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000975 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +0000976 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
977
978 if (!FirstEntryInstruction)
979 {
980 if (log)
981 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
982
Sean Callanan3989fb92011-01-27 01:07:04 +0000983 if (m_error_stream)
984 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
985
Sean Callananafe16a72010-11-17 23:00:36 +0000986 return false;
987 }
988
989 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
990 vi != ve;
991 ++vi)
992 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000993 std::string value_name = vi->first().str();
994 const char *value_name_cstr = value_name.c_str();
995
996 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000997 {
998 Value *nsstring_value = vi->second;
999
1000 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
1001
1002 if (!nsstring_global)
1003 {
1004 if (log)
1005 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001006
1007 if (m_error_stream)
1008 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
1009
Sean Callananafe16a72010-11-17 23:00:36 +00001010 return false;
1011 }
1012
1013 if (!nsstring_global->hasInitializer())
1014 {
1015 if (log)
1016 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +00001017
1018 if (m_error_stream)
1019 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
1020
Sean Callananafe16a72010-11-17 23:00:36 +00001021 return false;
1022 }
1023
1024 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
1025
1026 if (!nsstring_struct)
1027 {
1028 if (log)
1029 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +00001030
1031 if (m_error_stream)
1032 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
1033
Sean Callananafe16a72010-11-17 23:00:36 +00001034 return false;
1035 }
1036
1037 // We expect the following structure:
1038 //
1039 // struct {
1040 // int *isa;
1041 // int flags;
1042 // char *str;
1043 // long length;
1044 // };
1045
1046 if (nsstring_struct->getNumOperands() != 4)
1047 {
1048 if (log)
1049 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
Sean Callanan3989fb92011-01-27 01:07:04 +00001050
1051 if (m_error_stream)
1052 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
1053
Sean Callananafe16a72010-11-17 23:00:36 +00001054 return false;
1055 }
1056
1057 Constant *nsstring_member = nsstring_struct->getOperand(2);
1058
1059 if (!nsstring_member)
1060 {
1061 if (log)
1062 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +00001063
1064 if (m_error_stream)
1065 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1066
Sean Callananafe16a72010-11-17 23:00:36 +00001067 return false;
1068 }
1069
1070 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1071
1072 if (!nsstring_expr)
1073 {
1074 if (log)
1075 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +00001076
1077 if (m_error_stream)
1078 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1079
Sean Callananafe16a72010-11-17 23:00:36 +00001080 return false;
1081 }
1082
1083 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1084 {
1085 if (log)
1086 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
Sean Callanan3989fb92011-01-27 01:07:04 +00001087
1088 if (m_error_stream)
1089 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1090
Sean Callananafe16a72010-11-17 23:00:36 +00001091 return false;
1092 }
1093
1094 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1095
1096 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1097
1098 if (!cstr_global)
1099 {
1100 if (log)
1101 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001102
1103 if (m_error_stream)
1104 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan80eee3a2010-11-20 02:06:01 +00001105
Sean Callananafe16a72010-11-17 23:00:36 +00001106 return false;
1107 }
1108
1109 if (!cstr_global->hasInitializer())
1110 {
1111 if (log)
1112 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +00001113
1114 if (m_error_stream)
1115 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1116
Sean Callananafe16a72010-11-17 23:00:36 +00001117 return false;
1118 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001119
1120 /*
Sean Callananafe16a72010-11-17 23:00:36 +00001121 if (!cstr_array)
1122 {
1123 if (log)
1124 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +00001125
1126 if (m_error_stream)
1127 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1128
Sean Callananafe16a72010-11-17 23:00:36 +00001129 return false;
1130 }
1131
1132 if (!cstr_array->isCString())
1133 {
1134 if (log)
1135 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +00001136
1137 if (m_error_stream)
1138 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1139
Sean Callananafe16a72010-11-17 23:00:36 +00001140 return false;
1141 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001142 */
1143
Sean Callanand2b465f2012-02-09 03:22:41 +00001144 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +00001145
1146 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +00001147 {
1148 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +00001149 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
Sean Callanan229ce2d2011-02-10 22:17:53 +00001150 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001151 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001152 }
1153
1154 if (!cstr_array)
1155 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001156
Sean Callanan79763a42011-05-23 21:40:23 +00001157 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan3989fb92011-01-27 01:07:04 +00001158 {
Sean Callananafe16a72010-11-17 23:00:36 +00001159 if (log)
1160 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001161
1162 // We don't print an error message here because RewriteObjCConstString has done so for us.
1163
Sean Callananafe16a72010-11-17 23:00:36 +00001164 return false;
1165 }
Sean Callananafe16a72010-11-17 23:00:36 +00001166 }
1167 }
1168
1169 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1170 vi != ve;
1171 ++vi)
1172 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001173 std::string value_name = vi->first().str();
1174 const char *value_name_cstr = value_name.c_str();
1175
1176 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001177 {
1178 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1179
1180 if (!gv)
1181 {
1182 if (log)
1183 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001184
1185 if (m_error_stream)
1186 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1187
Sean Callananafe16a72010-11-17 23:00:36 +00001188 return false;
1189 }
1190
1191 gv->eraseFromParent();
1192
1193 break;
1194 }
1195 }
1196
1197 return true;
1198}
1199
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001200static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001201{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001202 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001203
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001204 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001205 return false;
1206
1207 return true;
1208}
1209
Sean Callanan3989fb92011-01-27 01:07:04 +00001210// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001211bool
Sean Callanan79763a42011-05-23 21:40:23 +00001212IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001213{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001214 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001215
1216 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1217
1218 if (!load)
1219 return false;
1220
1221 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1222 //
1223 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1224 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1225 //
1226 // where %obj is the object pointer and %tmp is the selector.
1227 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001228 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1229 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001230
1231 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1232
1233 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1234
1235 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1236 return false;
1237
1238 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1239
1240 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1241
1242 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1243 return false;
1244
1245 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1246
1247 if (!osr_initializer_base)
1248 return false;
1249
1250 // Find the string's initializer (a ConstantArray) and get the string from it
1251
1252 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1253
1254 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1255 return false;
1256
1257 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1258
Sean Callanand2b465f2012-02-09 03:22:41 +00001259 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001260
1261 if (!omvn_initializer_array->isString())
1262 return false;
1263
1264 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1265
1266 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001267 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001268
1269 // Construct a call to sel_registerName
1270
1271 if (!m_sel_registerName)
1272 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001273 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001274
Greg Clayton7b462cc2010-10-15 22:48:33 +00001275 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001276 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001277 return false;
1278
Sean Callananbe3a1b12010-10-26 00:31:56 +00001279 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001280 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001281
Sean Callanan5300d372010-07-31 01:32:05 +00001282 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1283
1284 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001285 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001286 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001287 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001288
Sean Callanancc427fa2011-07-30 02:42:06 +00001289 Type *type_array[1];
1290
1291 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1292
1293 ArrayRef<Type *> srN_arg_types(type_array, 1);
1294
Sean Callanan5300d372010-07-31 01:32:05 +00001295 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1296
1297 // Build the constant containing the pointer to the function
Sean Callanancc427fa2011-07-30 02:42:06 +00001298 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001299 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan5300d372010-07-31 01:32:05 +00001300 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001301 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001302 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1303 }
1304
Sean Callanancc427fa2011-07-30 02:42:06 +00001305 Value *argument_array[1];
1306
Sean Callanan79763a42011-05-23 21:40:23 +00001307 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001308
Sean Callanancc427fa2011-07-30 02:42:06 +00001309 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001310
Sean Callanancc427fa2011-07-30 02:42:06 +00001311 ArrayRef<Value *> srN_arguments(argument_array, 1);
1312
Sean Callanan5300d372010-07-31 01:32:05 +00001313 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001314 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001315 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001316 selector_load);
1317
1318 // Replace the load with the call in all users
1319
1320 selector_load->replaceAllUsesWith(srN_call);
1321
1322 selector_load->eraseFromParent();
1323
1324 return true;
1325}
1326
1327bool
Sean Callanan79763a42011-05-23 21:40:23 +00001328IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001329{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001330 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001331
1332 BasicBlock::iterator ii;
1333
1334 typedef SmallVector <Instruction*, 2> InstrList;
1335 typedef InstrList::iterator InstrIterator;
1336
1337 InstrList selector_loads;
1338
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001339 for (ii = basic_block.begin();
1340 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001341 ++ii)
1342 {
1343 Instruction &inst = *ii;
1344
1345 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001346 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001347 selector_loads.push_back(&inst);
1348 }
1349
1350 InstrIterator iter;
1351
1352 for (iter = selector_loads.begin();
1353 iter != selector_loads.end();
1354 ++iter)
1355 {
Sean Callanan79763a42011-05-23 21:40:23 +00001356 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001357 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001358 if (m_error_stream)
1359 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1360
Enrico Granata20edcdb2011-07-19 18:03:25 +00001361 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001362 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001363
Sean Callanan5300d372010-07-31 01:32:05 +00001364 return false;
1365 }
1366 }
1367
1368 return true;
1369}
1370
Sean Callanan3989fb92011-01-27 01:07:04 +00001371// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001372bool
Sean Callanan79763a42011-05-23 21:40:23 +00001373IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001374{
Sean Callanane1175b72011-01-13 21:23:32 +00001375 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1376
Sean Callanan2235f322010-08-11 03:57:18 +00001377 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1378
1379 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1380
1381 if (!alloc_md || !alloc_md->getNumOperands())
1382 return false;
1383
1384 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1385
1386 if (!constant_int)
1387 return false;
1388
1389 // We attempt to register this as a new persistent variable with the DeclMap.
1390
1391 uintptr_t ptr = constant_int->getZExtValue();
1392
Sean Callanand1e5b432010-08-12 01:56:52 +00001393 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001394
Sean Callanand1e5b432010-08-12 01:56:52 +00001395 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1396 &decl->getASTContext());
1397
Greg Clayton7b462cc2010-10-15 22:48:33 +00001398 StringRef decl_name (decl->getName());
1399 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001400 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001401 return false;
1402
Sean Callanan79763a42011-05-23 21:40:23 +00001403 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001404 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001405 false, /* not constant */
1406 GlobalValue::ExternalLinkage,
1407 NULL, /* no initializer */
1408 alloc->getName().str().c_str());
1409
1410 // What we're going to do here is make believe this was a regular old external
1411 // variable. That means we need to make the metadata valid.
1412
Sean Callanan585c0ec82012-07-04 01:26:26 +00001413 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001414
1415 llvm::Value* values[2];
1416 values[0] = persistent_global;
1417 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001418
1419 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001420
Sean Callanan79763a42011-05-23 21:40:23 +00001421 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001422 named_metadata->addOperand(persistent_global_md);
1423
Sean Callanane1175b72011-01-13 21:23:32 +00001424 // Now, since the variable is a pointer variable, we will drop in a load of that
1425 // pointer variable.
1426
1427 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1428
1429 if (log)
1430 log->Printf("Replacing \"%s\" with \"%s\"",
1431 PrintValue(alloc).c_str(),
1432 PrintValue(persistent_load).c_str());
1433
1434 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001435 alloc->eraseFromParent();
1436
1437 return true;
1438}
1439
1440bool
Sean Callanan79763a42011-05-23 21:40:23 +00001441IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001442{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001443 if (!m_resolve_vars)
1444 return true;
1445
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001446 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001447
1448 BasicBlock::iterator ii;
1449
1450 typedef SmallVector <Instruction*, 2> InstrList;
1451 typedef InstrList::iterator InstrIterator;
1452
1453 InstrList pvar_allocs;
1454
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001455 for (ii = basic_block.begin();
1456 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001457 ++ii)
1458 {
1459 Instruction &inst = *ii;
1460
1461 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001462 {
1463 llvm::StringRef alloc_name = alloc->getName();
1464
1465 if (alloc_name.startswith("$") &&
1466 !alloc_name.startswith("$__lldb"))
1467 {
1468 if (alloc_name.find_first_of("0123456789") == 1)
1469 {
1470 if (log)
1471 log->Printf("Rejecting a numeric persistent variable.");
1472
Sean Callanan3989fb92011-01-27 01:07:04 +00001473 if (m_error_stream)
1474 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1475
Sean Callananf694a552011-01-21 22:30:25 +00001476 return false;
1477 }
1478
Sean Callanan2235f322010-08-11 03:57:18 +00001479 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001480 }
1481 }
Sean Callanan2235f322010-08-11 03:57:18 +00001482 }
1483
1484 InstrIterator iter;
1485
1486 for (iter = pvar_allocs.begin();
1487 iter != pvar_allocs.end();
1488 ++iter)
1489 {
Sean Callanan79763a42011-05-23 21:40:23 +00001490 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001491 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001492 if (m_error_stream)
1493 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1494
Enrico Granata20edcdb2011-07-19 18:03:25 +00001495 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001496 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001497
Sean Callanan2235f322010-08-11 03:57:18 +00001498 return false;
1499 }
1500 }
1501
1502 return true;
1503}
1504
Sean Callananc70ed462011-10-25 18:36:40 +00001505bool
1506IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1507{
1508 if (!initializer)
1509 return true;
1510
1511 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1512
1513 if (log && log->GetVerbose())
1514 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1515
1516 Type *initializer_type = initializer->getType();
1517
1518 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1519 {
1520 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1521 return true;
1522 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001523 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001524 {
1525 if (array_initializer->isString())
1526 {
1527 std::string array_initializer_string = array_initializer->getAsString();
1528 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1529 }
1530 else
1531 {
1532 ArrayType *array_initializer_type = array_initializer->getType();
1533 Type *array_element_type = array_initializer_type->getElementType();
1534
1535 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1536
1537 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1538 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001539 Value *operand_value = array_initializer->getOperand(i);
1540 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1541
1542 if (!operand_constant)
1543 return false;
1544
1545 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001546 return false;
1547 }
1548 }
1549 return true;
1550 }
1551 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1552 {
1553 StructType *struct_initializer_type = struct_initializer->getType();
1554 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1555
1556 for (int i = 0;
1557 i < struct_initializer->getNumOperands();
1558 ++i)
1559 {
1560 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1561 return false;
1562 }
1563 return true;
1564 }
1565 return false;
1566}
1567
1568bool
1569IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1570{
1571 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1572 return false;
1573
Sean Callananfe5d1392011-11-15 19:13:54 +00001574 if (global_variable == m_reloc_placeholder)
1575 return true;
1576
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001577 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001578
1579 llvm::Type *variable_type = global_variable->getType();
1580
1581 Constant *initializer = global_variable->getInitializer();
1582
1583 llvm::Type *initializer_type = initializer->getType();
1584
1585 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001586 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1587
1588 const size_t mask = (align - 1);
1589 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001590 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001591 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001592
1593 lldb_private::DataBufferHeap data(size, '\0');
1594
1595 if (initializer)
1596 if (!MaterializeInitializer(data.GetBytes(), initializer))
1597 return false;
1598
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001599 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001600
1601 Constant *new_pointer = BuildRelocation(variable_type, offset);
1602
1603 global_variable->replaceAllUsesWith(new_pointer);
1604
1605 global_variable->eraseFromParent();
1606
1607 return true;
1608}
1609
Sean Callanan3989fb92011-01-27 01:07:04 +00001610// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001611bool
Sean Callanan79763a42011-05-23 21:40:23 +00001612IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001613{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001614 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001615
1616 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001617 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001618
Greg Clayton7b462cc2010-10-15 22:48:33 +00001619 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001620 {
Sean Callanan5666b672010-08-04 01:02:13 +00001621 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001622 {
Sean Callanan5666b672010-08-04 01:02:13 +00001623 default:
1624 break;
1625 case Instruction::GetElementPtr:
1626 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001627 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001628 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001629 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001630 }
1631 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001632 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001633 {
Sean Callananc70ed462011-10-25 18:36:40 +00001634 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1635 return MaterializeInternalVariable(global_variable);
1636
Sean Callanan79763a42011-05-23 21:40:23 +00001637 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001638
Sean Callanan5300d372010-07-31 01:32:05 +00001639 if (!named_decl)
1640 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001641 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001642 return true;
1643
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001644 if (!global_variable->hasExternalLinkage())
1645 return true;
1646
Sean Callanan5300d372010-07-31 01:32:05 +00001647 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001648 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001649
Sean Callanan5300d372010-07-31 01:32:05 +00001650 return false;
1651 }
1652
Greg Clayton7b462cc2010-10-15 22:48:33 +00001653 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001654
Sean Callanan038df5032010-09-30 21:18:25 +00001655 void *opaque_type = NULL;
Sean Callanan1d180662010-07-20 23:31:16 +00001656 clang::ASTContext *ast_context = NULL;
Sean Callananea22d422010-07-16 00:09:46 +00001657
1658 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callanan1d180662010-07-20 23:31:16 +00001659 {
Sean Callanan038df5032010-09-30 21:18:25 +00001660 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callanan1d180662010-07-20 23:31:16 +00001661 ast_context = &value_decl->getASTContext();
1662 }
Sean Callananea22d422010-07-16 00:09:46 +00001663 else
Sean Callanan1d180662010-07-20 23:31:16 +00001664 {
Sean Callananea22d422010-07-16 00:09:46 +00001665 return false;
Sean Callanan1d180662010-07-20 23:31:16 +00001666 }
Sean Callanan038df5032010-09-30 21:18:25 +00001667
Sean Callanan92adcac2011-01-13 08:53:35 +00001668 clang::QualType qual_type;
Sean Callanan77eaf442011-07-08 00:39:14 +00001669 const Type *value_type = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00001670
Sean Callanane1175b72011-01-13 21:23:32 +00001671 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001672 {
1673 // The $__lldb_expr_result name indicates the the return value has allocated as
1674 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1675 // accesses to this static variable need to be redirected to the result of dereferencing
1676 // a pointer that is passed in as one of the arguments.
1677 //
1678 // Consequently, when reporting the size of the type, we report a pointer type pointing
1679 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001680 //
1681 // We also do this for any user-declared persistent variables.
Sean Callanan1d180662010-07-20 23:31:16 +00001682
Sean Callanan92adcac2011-01-13 08:53:35 +00001683 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1684 value_type = PointerType::get(global_variable->getType(), 0);
1685 }
1686 else
1687 {
1688 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1689 value_type = global_variable->getType();
1690 }
Sean Callanan038df5032010-09-30 21:18:25 +00001691
Greg Claytonfaac1112013-03-14 18:31:44 +00001692 uint64_t value_size = (ast_context->getTypeSize(qual_type) + 7ull) / 8ull;
1693 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001694
Sean Callanan038df5032010-09-30 21:18:25 +00001695 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +00001696 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001697 name.c_str(),
1698 qual_type.getAsString().c_str(),
1699 PrintType(value_type).c_str(),
1700 value_size,
1701 value_alignment);
Sean Callanan17827832010-12-13 22:46:15 +00001702
Sean Callanan549c9f72010-07-13 21:41:46 +00001703
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001704 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001705 lldb_private::ConstString (name.c_str()),
1706 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001707 value_size,
1708 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001709 {
1710 if (!global_variable->hasExternalLinkage())
1711 return true;
1712 else
1713 return false;
1714 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001715 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001716 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001717 {
1718 if (log)
1719 log->Printf("Function pointers aren't handled right now");
1720
1721 return false;
1722 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001723
1724 return true;
1725}
1726
Sean Callanan3989fb92011-01-27 01:07:04 +00001727// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001728bool
Sean Callanan79763a42011-05-23 21:40:23 +00001729IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001730{
Sean Callananc3a16002011-01-17 23:42:46 +00001731 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1732
1733 lldb_private::ConstString name(symbol->getName().str().c_str());
1734
Sean Callanan947ccc72011-12-01 02:04:16 +00001735 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001736
Greg Clayton084db102011-06-23 04:25:29 +00001737 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001738 {
1739 if (log)
1740 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1741
1742 return false;
1743 }
1744
1745 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001746 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001747
Sean Callanancc427fa2011-07-30 02:42:06 +00001748 Type *symbol_type = symbol->getType();
Sean Callanancc427fa2011-07-30 02:42:06 +00001749 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001750 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc3a16002011-01-17 23:42:46 +00001751
1752 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1753
1754 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1755
1756 if (log)
1757 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1758
1759 symbol->replaceAllUsesWith(symbol_addr_ptr);
1760
1761 return true;
1762}
1763
1764bool
Sean Callanan79763a42011-05-23 21:40:23 +00001765IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001766{
Sean Callanand7a1ca22010-12-02 19:47:57 +00001767 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1768
1769 if (log)
1770 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001771
Sean Callananafe16a72010-11-17 23:00:36 +00001772 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001773 op_index < num_ops;
1774 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001775 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001776 {
1777 if (m_error_stream)
1778 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1779
Sean Callanan85a0a832010-10-05 22:26:43 +00001780 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001781 }
1782
Sean Callanan85a0a832010-10-05 22:26:43 +00001783 return true;
1784}
1785
1786bool
Sean Callananfc89c142011-11-01 23:38:03 +00001787IRForTarget::HandleObjCClass(Value *classlist_reference)
1788{
1789 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1790
1791 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1792
1793 if (!global_variable)
1794 return false;
1795
1796 Constant *initializer = global_variable->getInitializer();
1797
1798 if (!initializer)
1799 return false;
1800
1801 if (!initializer->hasName())
1802 return false;
1803
1804 StringRef name(initializer->getName());
1805 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001806 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001807
1808 if (log)
1809 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1810
1811 if (class_ptr == LLDB_INVALID_ADDRESS)
1812 return false;
1813
1814 if (global_variable->use_begin() == global_variable->use_end())
1815 return false;
1816
Sean Callanan719a4d52013-03-23 01:01:16 +00001817 SmallVector<LoadInst *, 2> load_instructions;
1818
Sean Callananfc89c142011-11-01 23:38:03 +00001819 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1820 i != e;
1821 ++i)
1822 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001823 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1824 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001825 }
1826
Sean Callanan719a4d52013-03-23 01:01:16 +00001827 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001828 return false;
1829
1830 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001831 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +00001832 == Module::Pointer64) ? 64 : 32);
Sean Callananfc89c142011-11-01 23:38:03 +00001833
1834 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001835
Sean Callanan719a4d52013-03-23 01:01:16 +00001836 for (LoadInst *load_instruction : load_instructions)
1837 {
1838 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001839
Sean Callanan719a4d52013-03-23 01:01:16 +00001840 load_instruction->replaceAllUsesWith(class_bitcast);
1841
1842 load_instruction->eraseFromParent();
1843 }
Sean Callananfc89c142011-11-01 23:38:03 +00001844
1845 return true;
1846}
1847
1848bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001849IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1850{
1851 BasicBlock::iterator ii;
1852
1853 std::vector<CallInst *> calls_to_remove;
1854
1855 for (ii = basic_block.begin();
1856 ii != basic_block.end();
1857 ++ii)
1858 {
1859 Instruction &inst = *ii;
1860
1861 CallInst *call = dyn_cast<CallInst>(&inst);
1862
1863 // MaybeHandleCallArguments handles error reporting; we are silent here
1864 if (!call)
1865 continue;
1866
1867 bool remove = false;
1868
1869 llvm::Function *func = call->getCalledFunction();
1870
1871 if (func && func->getName() == "__cxa_atexit")
1872 remove = true;
1873
1874 llvm::Value *val = call->getCalledValue();
1875
1876 if (val && val->getName() == "__cxa_atexit")
1877 remove = true;
1878
1879 if (remove)
1880 calls_to_remove.push_back(call);
1881 }
1882
1883 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1884 ci != ce;
1885 ++ci)
1886 {
1887 (*ci)->eraseFromParent();
1888 }
1889
1890 return true;
1891}
1892
1893bool
Sean Callanan79763a42011-05-23 21:40:23 +00001894IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001895{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001896 /////////////////////////////////////////////////////////////////////////
1897 // Prepare the current basic block for execution in the remote process
1898 //
1899
Sean Callanan7ea35012010-07-27 21:39:39 +00001900 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001901
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001902 for (ii = basic_block.begin();
1903 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001904 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001905 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001906 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001907
Sean Callanana4e55172010-11-08 00:31:32 +00001908 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001909
Sean Callanan3989fb92011-01-27 01:07:04 +00001910 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001911 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001912 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001913 }
1914
1915 return true;
1916}
1917
Sean Callanana4e55172010-11-08 00:31:32 +00001918bool
Sean Callanan79763a42011-05-23 21:40:23 +00001919IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001920{
Sean Callanan7a55a322010-11-18 22:21:58 +00001921 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1922
Sean Callanan79763a42011-05-23 21:40:23 +00001923 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001924 global != end;
1925 ++global)
1926 {
Sean Callanan694e2442011-12-22 21:24:49 +00001927 if (!global)
1928 {
1929 if (m_error_stream)
1930 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1931
1932 return false;
1933 }
1934
1935 std::string global_name = (*global).getName().str();
1936
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001937 if (log)
1938 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001939 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001940 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001941
1942 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001943 {
Sean Callanan79763a42011-05-23 21:40:23 +00001944 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001945 {
1946 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001947 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001948
Sean Callananc3a16002011-01-17 23:42:46 +00001949 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001950 }
Sean Callananc3a16002011-01-17 23:42:46 +00001951 }
Sean Callananfc89c142011-11-01 23:38:03 +00001952 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1953 {
1954 if (!HandleObjCClass(global))
1955 {
1956 if (m_error_stream)
1957 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1958
1959 return false;
1960 }
1961 }
Sean Callanan79763a42011-05-23 21:40:23 +00001962 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001963 {
Sean Callanan79763a42011-05-23 21:40:23 +00001964 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001965 {
1966 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001967 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001968
Sean Callananc3a16002011-01-17 23:42:46 +00001969 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001970 }
Sean Callananc3a16002011-01-17 23:42:46 +00001971 }
Sean Callanana4e55172010-11-08 00:31:32 +00001972 }
1973
1974 return true;
1975}
1976
Sean Callanan79763a42011-05-23 21:40:23 +00001977bool
1978IRForTarget::ReplaceStrings ()
1979{
1980 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1981
Sean Callanan79763a42011-05-23 21:40:23 +00001982 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1983
1984 OffsetsTy offsets;
1985
1986 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1987 gi != ge;
1988 ++gi)
1989 {
1990 GlobalVariable *gv = gi;
1991
1992 if (!gv->hasInitializer())
1993 continue;
1994
1995 Constant *gc = gv->getInitializer();
1996
Sean Callanan5207a342011-08-10 21:05:52 +00001997 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001998
Sean Callanan5207a342011-08-10 21:05:52 +00001999 if (gc->isNullValue())
2000 {
2001 Type *gc_type = gc->getType();
2002
2003 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
2004
2005 if (!gc_array_type)
2006 continue;
2007
2008 Type *gc_element_type = gc_array_type->getElementType();
2009
2010 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
2011
2012 if (gc_integer_type->getBitWidth() != 8)
2013 continue;
2014
2015 str = "";
2016 }
2017 else
2018 {
Sean Callanand2b465f2012-02-09 03:22:41 +00002019 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00002020
2021 if (!gc_array)
2022 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00002023
Sean Callanan5207a342011-08-10 21:05:52 +00002024 if (!gc_array->isCString())
2025 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00002026
Sean Callanan5207a342011-08-10 21:05:52 +00002027 if (log)
2028 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002029
Sean Callanan5207a342011-08-10 21:05:52 +00002030 str = gc_array->getAsString();
2031 }
2032
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002033 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002034
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002035 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00002036 }
2037
Sean Callanancc427fa2011-07-30 02:42:06 +00002038 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002039
2040 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
2041 oi != oe;
2042 ++oi)
2043 {
2044 GlobalVariable *gv = oi->first;
2045 size_t offset = oi->second;
2046
2047 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
2048
2049 if (log)
2050 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
2051
2052 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
2053 ui != ue;
2054 ++ui)
2055 {
2056 if (log)
2057 log->Printf("Found use %s", PrintValue(*ui).c_str());
2058
2059 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
2060 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
2061
2062 if (const_expr)
2063 {
2064 if (const_expr->getOpcode() != Instruction::GetElementPtr)
2065 {
2066 if (log)
2067 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
2068
2069 return false;
2070 }
2071
Sean Callanan5207a342011-08-10 21:05:52 +00002072 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
2073 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
2074
2075 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00002076 }
2077 else if (store_inst)
2078 {
2079 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
2080
2081 store_inst->setOperand(0, bit_cast);
2082 }
2083 else
2084 {
2085 if (log)
2086 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
2087
2088 return false;
2089 }
2090 }
2091
2092 gv->eraseFromParent();
2093 }
2094
2095 return true;
2096}
2097
2098bool
2099IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
2100{
2101 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002102
2103 typedef SmallVector <Value*, 2> ConstantList;
2104 typedef SmallVector <llvm::Instruction*, 2> UserList;
2105 typedef ConstantList::iterator ConstantIterator;
2106 typedef UserList::iterator UserIterator;
2107
2108 ConstantList static_constants;
2109 UserList static_users;
2110
2111 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2112 ii != ie;
2113 ++ii)
2114 {
2115 llvm::Instruction &inst = *ii;
2116
2117 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2118 oi != oe;
2119 ++oi)
2120 {
2121 Value *operand_val = oi->get();
2122
2123 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2124
Sean Callanan822944c2012-04-26 20:51:20 +00002125 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00002126 {
2127 static_constants.push_back(operand_val);
2128 static_users.push_back(ii);
2129 }
2130 }
2131 }
2132
2133 ConstantIterator constant_iter;
2134 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00002135
Sean Callanan79763a42011-05-23 21:40:23 +00002136 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2137 constant_iter != static_constants.end();
2138 ++constant_iter, ++user_iter)
2139 {
2140 Value *operand_val = *constant_iter;
2141 llvm::Instruction *inst = *user_iter;
2142
2143 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
Sean Callanane3333d62012-06-08 22:20:41 +00002144 Type *operand_type = operand_constant_fp->getType();
Sean Callanan79763a42011-05-23 21:40:23 +00002145
2146 if (operand_constant_fp)
2147 {
2148 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2149 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2150
2151 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2152 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2153
2154 if (log)
2155 {
2156 std::string s;
2157 raw_string_ostream ss(s);
2158 for (size_t index = 0;
2159 index < operand_data_size;
2160 ++index)
2161 {
2162 ss << (uint32_t)operand_raw_data[index];
2163 ss << " ";
2164 }
2165 ss.flush();
2166
Jason Molendafd54b362011-09-20 21:44:10 +00002167 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002168 }
2169
2170 lldb_private::DataBufferHeap data(operand_data_size, 0);
2171
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002172 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002173 {
2174 uint8_t *data_bytes = data.GetBytes();
2175
2176 for (size_t index = 0;
2177 index < operand_data_size;
2178 ++index)
2179 {
2180 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2181 }
2182 }
2183 else
2184 {
2185 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2186 }
2187
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002188 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002189
Sean Callanane3333d62012-06-08 22:20:41 +00002190 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2191
2192 const size_t mask = (align - 1);
2193 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002194 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002195 offset = aligned_offset;
2196
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002197 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002198
Sean Callanancc427fa2011-07-30 02:42:06 +00002199 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002200
2201 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2202
2203 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2204
2205 operand_constant_fp->replaceAllUsesWith(fp_load);
2206 }
2207 }
2208
2209 return true;
2210}
2211
Sean Callanan7ea35012010-07-27 21:39:39 +00002212static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002213{
Sean Callanan77eaf442011-07-08 00:39:14 +00002214 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002215
Sean Callananafe16a72010-11-17 23:00:36 +00002216 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002217 return false;
2218
Sean Callanan77eaf442011-07-08 00:39:14 +00002219 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002220
2221 if ((CE = dyn_cast<ConstantExpr>(V)))
2222 {
2223 if (CE->getOpcode() != Instruction::BitCast)
2224 return false;
2225
Sean Callananafe16a72010-11-17 23:00:36 +00002226 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002227 }
2228
Sean Callananafe16a72010-11-17 23:00:36 +00002229 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002230
2231 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2232 return false;
2233
2234 return true;
2235}
2236
Sean Callanan79763a42011-05-23 21:40:23 +00002237void
2238IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002239{
Sean Callanan79763a42011-05-23 21:40:23 +00002240 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002241
2242 Value::use_iterator ui;
2243
2244 for (ui = guard_load->use_begin();
2245 ui != guard_load->use_end();
2246 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002247 {
Greg Claytone6371122010-07-30 20:30:44 +00002248 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002249 {
2250 // do nothing for the moment
2251 }
2252 else
2253 {
2254 ui->replaceUsesOfWith(guard_load, zero);
2255 }
2256 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002257
2258 guard_load->eraseFromParent();
2259}
2260
2261static void ExciseGuardStore(Instruction* guard_store)
2262{
2263 guard_store->eraseFromParent();
2264}
2265
2266bool
Sean Callanan79763a42011-05-23 21:40:23 +00002267IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002268{
2269 ///////////////////////////////////////////////////////
2270 // Eliminate any reference to guard variables found.
2271 //
2272
Sean Callanan7ea35012010-07-27 21:39:39 +00002273 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002274
Sean Callanan7ea35012010-07-27 21:39:39 +00002275 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002276 typedef InstrList::iterator InstrIterator;
2277
2278 InstrList guard_loads;
2279 InstrList guard_stores;
2280
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002281 for (ii = basic_block.begin();
2282 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002283 ++ii)
2284 {
2285 Instruction &inst = *ii;
2286
2287 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2288 if (isGuardVariableRef(load->getPointerOperand()))
2289 guard_loads.push_back(&inst);
2290
2291 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2292 if (isGuardVariableRef(store->getPointerOperand()))
2293 guard_stores.push_back(&inst);
2294 }
2295
2296 InstrIterator iter;
2297
2298 for (iter = guard_loads.begin();
2299 iter != guard_loads.end();
2300 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002301 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002302
2303 for (iter = guard_stores.begin();
2304 iter != guard_stores.end();
2305 ++iter)
2306 ExciseGuardStore(*iter);
2307
2308 return true;
2309}
2310
Sean Callanan3989fb92011-01-27 01:07:04 +00002311// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002312bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002313IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002314{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002315 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002316
2317 Value::use_iterator ui;
2318
Sean Callanan2235f322010-08-11 03:57:18 +00002319 SmallVector<User*, 16> users;
2320
2321 // We do this because the use list might change, invalidating our iterator.
2322 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002323 for (ui = old_constant->use_begin();
2324 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002325 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002326 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002327
Johnny Chen44805302011-07-19 19:48:13 +00002328 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002329 i < users.size();
2330 ++i)
2331 {
2332 User *user = users[i];
2333
Sean Callanan7618f4e2010-07-14 23:40:29 +00002334 if (Constant *constant = dyn_cast<Constant>(user))
2335 {
2336 // synthesize a new non-constant equivalent of the constant
2337
2338 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2339 {
2340 switch (constant_expr->getOpcode())
2341 {
2342 default:
2343 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002344 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002345 return false;
2346 case Instruction::BitCast:
2347 {
2348 // UnaryExpr
2349 // OperandList[0] is value
2350
2351 Value *s = constant_expr->getOperand(0);
2352
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002353 if (s == old_constant)
2354 s = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002355
Sean Callanan79763a42011-05-23 21:40:23 +00002356 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002357
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002358 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002359 }
2360 break;
2361 case Instruction::GetElementPtr:
2362 {
2363 // GetElementPtrConstantExpr
2364 // OperandList[0] is base
2365 // OperandList[1]... are indices
2366
2367 Value *ptr = constant_expr->getOperand(0);
2368
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002369 if (ptr == old_constant)
2370 ptr = new_constant;
Sean Callanancc427fa2011-07-30 02:42:06 +00002371
2372 std::vector<Value*> index_vector;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002373
2374 unsigned operand_index;
2375 unsigned num_operands = constant_expr->getNumOperands();
2376
2377 for (operand_index = 1;
2378 operand_index < num_operands;
2379 ++operand_index)
2380 {
2381 Value *operand = constant_expr->getOperand(operand_index);
2382
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002383 if (operand == old_constant)
2384 operand = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002385
Sean Callanancc427fa2011-07-30 02:42:06 +00002386 index_vector.push_back(operand);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002387 }
2388
Sean Callanancc427fa2011-07-30 02:42:06 +00002389 ArrayRef <Value*> indices(index_vector);
2390
2391 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002392
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002393 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002394 }
2395 break;
2396 }
2397 }
2398 else
2399 {
2400 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002401 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002402 return false;
2403 }
2404 }
2405 else
2406 {
2407 // simple fall-through case for non-constants
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002408 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002409 }
2410 }
2411
2412 return true;
2413}
2414
Sean Callanan549c9f72010-07-13 21:41:46 +00002415bool
Sean Callanan79763a42011-05-23 21:40:23 +00002416IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002417{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002418 if (!m_resolve_vars)
2419 return true;
2420
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002421 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002422
2423 m_decl_map->DoStructLayout();
2424
2425 if (log)
2426 log->Printf("Element arrangement:");
2427
2428 uint32_t num_elements;
2429 uint32_t element_index;
2430
2431 size_t size;
2432 off_t alignment;
2433
2434 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2435 return false;
2436
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002437 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002438
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002439 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002440 {
2441 if (m_error_stream)
2442 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2443
Sean Callanan549c9f72010-07-13 21:41:46 +00002444 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002445 }
2446
Sean Callanan7ea35012010-07-27 21:39:39 +00002447 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002448
Sean Callananfc55f5d2010-09-21 00:44:12 +00002449 if (argument->getName().equals("this"))
2450 {
2451 ++iter;
2452
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002453 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002454 {
2455 if (m_error_stream)
2456 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2457
Sean Callananfc55f5d2010-09-21 00:44:12 +00002458 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002459 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002460
2461 argument = iter;
2462 }
Sean Callanan17827832010-12-13 22:46:15 +00002463 else if (argument->getName().equals("self"))
2464 {
2465 ++iter;
2466
2467 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002468 {
2469 if (m_error_stream)
2470 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2471
Sean Callanan17827832010-12-13 22:46:15 +00002472 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002473 }
Sean Callanan17827832010-12-13 22:46:15 +00002474
2475 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002476 {
2477 if (m_error_stream)
2478 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2479
Sean Callanan17827832010-12-13 22:46:15 +00002480 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002481 }
Sean Callanan17827832010-12-13 22:46:15 +00002482
2483 ++iter;
2484
2485 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002486 {
2487 if (m_error_stream)
2488 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2489
Sean Callanan17827832010-12-13 22:46:15 +00002490 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002491 }
Sean Callanan17827832010-12-13 22:46:15 +00002492
2493 argument = iter;
2494 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002495
Greg Clayton7b462cc2010-10-15 22:48:33 +00002496 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002497 {
2498 if (m_error_stream)
2499 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2500
Sean Callanan549c9f72010-07-13 21:41:46 +00002501 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002502 }
2503
Sean Callanan549c9f72010-07-13 21:41:46 +00002504 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002505 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002506
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002507 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002508 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002509
Sean Callananafe16a72010-11-17 23:00:36 +00002510 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002511 {
2512 if (m_error_stream)
2513 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2514
Sean Callanan549c9f72010-07-13 21:41:46 +00002515 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002516 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002517
Sean Callanan79763a42011-05-23 21:40:23 +00002518 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002519 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002520
2521 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002522 {
2523 if (m_error_stream)
2524 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2525
Sean Callanan549c9f72010-07-13 21:41:46 +00002526 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002527 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002528
2529 for (element_index = 0; element_index < num_elements; ++element_index)
2530 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002531 const clang::NamedDecl *decl = NULL;
2532 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002533 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002534 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002535
Sean Callanan823bb4c2010-08-30 22:17:16 +00002536 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002537 {
2538 if (m_error_stream)
2539 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2540
Sean Callanan549c9f72010-07-13 21:41:46 +00002541 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002542 }
2543
Sean Callanan549c9f72010-07-13 21:41:46 +00002544 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002545 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002546 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002547 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002548 offset);
2549
Sean Callanancc427fa2011-07-30 02:42:06 +00002550 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callananafe16a72010-11-17 23:00:36 +00002551 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan92adcac2011-01-13 08:53:35 +00002552
Sean Callananc70ed462011-10-25 18:36:40 +00002553 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002554 {
Sean Callananc70ed462011-10-25 18:36:40 +00002555 Value *replacement = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00002556
Sean Callananc70ed462011-10-25 18:36:40 +00002557 if (log)
2558 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002559
Sean Callananc70ed462011-10-25 18:36:40 +00002560 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2561 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2562 // entry in order to produce the static variable that the AST thinks it is accessing.
2563 if (name == m_result_name && !m_result_is_pointer)
2564 {
2565 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2566
2567 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2568
2569 replacement = load;
2570 }
2571 else
2572 {
2573 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2574
2575 replacement = bit_cast;
2576 }
2577
2578 if (Constant *constant = dyn_cast<Constant>(value))
2579 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2580 else
2581 value->replaceAllUsesWith(replacement);
2582
2583 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2584 var->eraseFromParent();
2585 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002586 }
2587
2588 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002589 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002590
2591 return true;
2592}
2593
Sean Callanan79763a42011-05-23 21:40:23 +00002594llvm::Constant *
Sean Callanancc427fa2011-07-30 02:42:06 +00002595IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callanan79763a42011-05-23 21:40:23 +00002596 uint64_t offset)
2597{
2598 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2599
Sean Callanancc427fa2011-07-30 02:42:06 +00002600 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002601 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002602
2603 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002604
2605 llvm::Constant *offset_array[1];
2606
2607 offset_array[0] = offset_int;
2608
2609 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2610
2611 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002612 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2613
2614 return reloc_getbitcast;
2615}
2616
2617bool
2618IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002619{
Sean Callanan79763a42011-05-23 21:40:23 +00002620 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2621
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002622 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002623 return true;
2624
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002625 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002626
2627 if (log)
2628 {
2629 if (allocation)
2630 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2631 else
2632 log->Printf("Failed to allocate static data");
2633 }
2634
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002635 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002636 return false;
2637
Sean Callanancc427fa2011-07-30 02:42:06 +00002638 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002639 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002640
2641 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2642 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2643
2644 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2645
2646 m_reloc_placeholder->eraseFromParent();
2647
2648 return true;
2649}
2650
Sean Callanan2ab712f22010-07-03 01:35:46 +00002651bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002652IRForTarget::StripAllGVs (Module &llvm_module)
2653{
2654 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2655 std::vector<GlobalVariable *> global_vars;
2656 std::set<GlobalVariable *>erased_vars;
2657
2658 bool erased = true;
2659
2660 while (erased)
2661 {
2662 erased = false;
2663
2664 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2665 gi != ge;
2666 ++gi)
2667 {
2668 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2669
2670 global_var->removeDeadConstantUsers();
2671
2672 if (global_var->use_empty())
2673 {
2674 if (log)
2675 log->Printf("Did remove %s",
2676 PrintValue(global_var).c_str());
2677 global_var->eraseFromParent();
2678 erased = true;
2679 break;
2680 }
2681 }
2682 }
2683
2684 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2685 gi != ge;
2686 ++gi)
2687 {
2688 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2689
2690 GlobalValue::use_iterator ui = global_var->use_begin();
2691
Jim Inghamd77557d2012-11-26 19:54:04 +00002692 if (log)
2693 log->Printf("Couldn't remove %s because of %s",
2694 PrintValue(global_var).c_str(),
2695 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002696 }
2697
2698 return true;
2699}
2700
2701bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002702IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002703{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002704 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002705
Sean Callanan79763a42011-05-23 21:40:23 +00002706 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002707 m_target_data.reset(new DataLayout(m_module));
Sean Callanan79763a42011-05-23 21:40:23 +00002708
2709 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002710
2711 if (!function)
2712 {
2713 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002714 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00002715
2716 if (m_error_stream)
Sean Callanan79763a42011-05-23 21:40:23 +00002717 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002718
Sean Callanan2ab712f22010-07-03 01:35:46 +00002719 return false;
2720 }
Sean Callanan79763a42011-05-23 21:40:23 +00002721
2722 if (!FixFunctionLinkage (*function))
2723 {
2724 if (log)
2725 log->Printf("Couldn't fix the linkage for the function");
2726
2727 return false;
2728 }
2729
Sean Callananc70ed462011-10-25 18:36:40 +00002730 if (log)
2731 {
2732 std::string s;
2733 raw_string_ostream oss(s);
2734
2735 m_module->print(oss, NULL);
2736
2737 oss.flush();
2738
2739 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2740 }
2741
Sean Callanancc427fa2011-07-30 02:42:06 +00002742 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002743
2744 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2745 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002746 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002747 GlobalVariable::InternalLinkage,
2748 Constant::getNullValue(intptr_ty),
2749 "reloc_placeholder",
2750 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002751 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002752 0 /* AddressSpace */);
Sean Callanan2ab712f22010-07-03 01:35:46 +00002753
Sean Callanan7ea35012010-07-27 21:39:39 +00002754 Function::iterator bbi;
Sean Callanan2ab712f22010-07-03 01:35:46 +00002755
Sean Callanan79763a42011-05-23 21:40:23 +00002756 m_has_side_effects = HasSideEffects(*function);
Sean Callanane4ec90e2010-12-16 03:17:46 +00002757
Sean Callanand1e5b432010-08-12 01:56:52 +00002758 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002759 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002760 //
2761
Sean Callanan79763a42011-05-23 21:40:23 +00002762 if (!CreateResultVariable(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002763 {
2764 if (log)
2765 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002766
2767 // CreateResultVariable() reports its own errors, so we don't do so here
2768
Sean Callanand1e5b432010-08-12 01:56:52 +00002769 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002770 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002771
2772 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2773 {
2774 m_interpret_success = true;
Sean Callanan63697e52011-05-07 01:06:41 +00002775 return true;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002776 }
2777
2778 for (bbi = function->begin();
2779 bbi != function->end();
2780 ++bbi)
2781 {
2782 if (!RemoveGuards(*bbi))
2783 {
2784 if (log)
2785 log->Printf("RemoveGuards() failed");
2786
2787 // RemoveGuards() reports its own errors, so we don't do so here
2788
2789 return false;
2790 }
2791
2792 if (!RewritePersistentAllocs(*bbi))
2793 {
2794 if (log)
2795 log->Printf("RewritePersistentAllocs() failed");
2796
2797 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2798
2799 return false;
2800 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002801
2802 if (!RemoveCXAAtExit(*bbi))
2803 {
2804 if (log)
2805 log->Printf("RemoveCXAAtExit() failed");
2806
2807 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2808
2809 return false;
2810 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002811 }
2812
2813 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2814 {
2815 IRInterpreter interpreter (*m_decl_map,
2816 m_error_stream);
2817
Sean Callanan175a0d02012-01-24 22:06:48 +00002818 interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module, m_interpreter_error);
2819
2820 if (m_interpreter_error.Success())
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002821 return true;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002822 }
Sean Callanan63697e52011-05-07 01:06:41 +00002823
Sean Callanan5b26f272012-02-04 08:49:35 +00002824 if (m_execution_policy == lldb_private::eExecutionPolicyNever) {
Sean Callanan4538aa22012-04-24 17:56:40 +00002825 if (m_result_name)
2826 m_decl_map->RemoveResultVariable(m_result_name);
Sean Callanan5b26f272012-02-04 08:49:35 +00002827 return false;
2828 }
2829
Sean Callananea685ae2011-11-01 17:33:54 +00002830 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002831 {
2832 std::string s;
2833 raw_string_ostream oss(s);
2834
2835 m_module->print(oss, NULL);
2836
2837 oss.flush();
2838
2839 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2840 }
2841
Sean Callananafe16a72010-11-17 23:00:36 +00002842 ///////////////////////////////////////////////////////////////////////////////
2843 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2844 //
Sean Callananafe16a72010-11-17 23:00:36 +00002845
Sean Callanan79763a42011-05-23 21:40:23 +00002846 if (!RewriteObjCConstStrings(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002847 {
2848 if (log)
2849 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002850
2851 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2852
Sean Callananafe16a72010-11-17 23:00:36 +00002853 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002854 }
Sean Callananafe16a72010-11-17 23:00:36 +00002855
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002856 ///////////////////////////////
2857 // Resolve function pointers
2858 //
2859
2860 if (!ResolveFunctionPointers(llvm_module, *function))
2861 {
2862 if (log)
2863 log->Printf("ResolveFunctionPointers() failed");
2864
2865 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2866
2867 return false;
2868 }
2869
Sean Callanan2ab712f22010-07-03 01:35:46 +00002870 for (bbi = function->begin();
2871 bbi != function->end();
2872 ++bbi)
2873 {
Sean Callanan79763a42011-05-23 21:40:23 +00002874 if (!RewriteObjCSelectors(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002875 {
2876 if (log)
2877 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002878
2879 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2880
Sean Callanan2235f322010-08-11 03:57:18 +00002881 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002882 }
Sean Callananbad134f2012-07-27 19:25:24 +00002883 }
Sean Callanan2235f322010-08-11 03:57:18 +00002884
Sean Callananbad134f2012-07-27 19:25:24 +00002885 for (bbi = function->begin();
2886 bbi != function->end();
2887 ++bbi)
2888 {
Sean Callanan79763a42011-05-23 21:40:23 +00002889 if (!ResolveCalls(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002890 {
2891 if (log)
2892 log->Printf("ResolveCalls() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002893
2894 // ResolveCalls() reports its own errors, so we don't do so here
2895
Sean Callanan549c9f72010-07-13 21:41:46 +00002896 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002897 }
Sean Callanan79763a42011-05-23 21:40:23 +00002898
2899 if (!ReplaceStaticLiterals(*bbi))
2900 {
2901 if (log)
2902 log->Printf("ReplaceStaticLiterals() failed");
2903
2904 return false;
2905 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002906 }
2907
Sean Callanan038df5032010-09-30 21:18:25 +00002908 ///////////////////////////////
2909 // Run function-level passes
2910 //
2911
Sean Callanan79763a42011-05-23 21:40:23 +00002912 if (!ResolveExternals(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002913 {
2914 if (log)
2915 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002916
2917 // ResolveExternals() reports its own errors, so we don't do so here
2918
Sean Callanana4e55172010-11-08 00:31:32 +00002919 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002920 }
Sean Callanana4e55172010-11-08 00:31:32 +00002921
Sean Callanan79763a42011-05-23 21:40:23 +00002922 if (!ReplaceVariables(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002923 {
2924 if (log)
2925 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002926
2927 // ReplaceVariables() reports its own errors, so we don't do so here
2928
Sean Callanan038df5032010-09-30 21:18:25 +00002929 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002930 }
Sean Callanan038df5032010-09-30 21:18:25 +00002931
Sean Callanan79763a42011-05-23 21:40:23 +00002932 if (!ReplaceStrings())
2933 {
2934 if (log)
2935 log->Printf("ReplaceStrings() failed");
2936
2937 return false;
2938 }
2939
2940 if (!CompleteDataAllocation())
2941 {
2942 if (log)
2943 log->Printf("CompleteDataAllocation() failed");
2944
2945 return false;
2946 }
2947
Sean Callanan3d654b32012-09-24 22:25:51 +00002948 if (!StripAllGVs(llvm_module))
2949 {
2950 if (log)
2951 log->Printf("StripAllGVs() failed");
2952 }
2953
Sean Callananea685ae2011-11-01 17:33:54 +00002954 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002955 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002956 std::string s;
2957 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002958
Sean Callanan79763a42011-05-23 21:40:23 +00002959 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002960
2961 oss.flush();
2962
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002963 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002964 }
2965
2966 return true;
2967}
2968
2969void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002970IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002971{
2972}
2973
2974PassManagerType
2975IRForTarget::getPotentialPassManagerType() const
2976{
2977 return PMT_ModulePassManager;
2978}