blob: 778c6c0b1837a65b23eab591f63879bc54e567ac [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),
Sean Callanan1582ee62013-04-18 22:06:33 +000045 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000046 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000047{
48}
49
Sean Callanan8dfb68e2013-03-19 00:10:07 +000050lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000051{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000052 lldb_private::Error err;
53
54 if (m_allocation != LLDB_INVALID_ADDRESS)
55 {
56 m_execution_unit.FreeNow(m_allocation);
57 m_allocation = LLDB_INVALID_ADDRESS;
58 }
59
60 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
61
62 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000063}
64
Greg Clayton1b95a6f2010-11-19 01:05:25 +000065IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
66 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000067 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000068 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000069 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +000070 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +000071 m_resolve_vars(resolve_vars),
72 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +000073 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +000074 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000075 m_data_allocator(execution_unit),
Sean Callanan179b5482013-04-16 23:49:09 +000076 m_memory_map(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +000077 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +000078 m_sel_registerName(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +000079 m_error_stream(error_stream),
Sean Callanan92adcac2011-01-13 08:53:35 +000080 m_has_side_effects(false),
Sean Callanan63697e52011-05-07 01:06:41 +000081 m_result_store(NULL),
82 m_result_is_pointer(false),
Sean Callanan79763a42011-05-23 21:40:23 +000083 m_reloc_placeholder(NULL)
Sean Callanan2ab712f22010-07-03 01:35:46 +000084{
85}
86
Sean Callanan038df5032010-09-30 21:18:25 +000087/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +000088
89static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +000090PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +000091{
92 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +000093 if (value)
94 {
95 raw_string_ostream rso(s);
96 value->print(rso);
97 rso.flush();
98 if (truncate)
99 s.resize(s.length() - 1);
100 }
Sean Callanan2235f322010-08-11 03:57:18 +0000101 return s;
102}
103
Sean Callanan038df5032010-09-30 21:18:25 +0000104static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000105PrintType(const Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000106{
107 std::string s;
108 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000109 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000110 rso.flush();
111 if (truncate)
112 s.resize(s.length() - 1);
113 return s;
114}
115
Sean Callanan2ab712f22010-07-03 01:35:46 +0000116IRForTarget::~IRForTarget()
117{
118}
119
Sean Callanan79763a42011-05-23 21:40:23 +0000120bool
121IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
122{
Sean Callanan79763a42011-05-23 21:40:23 +0000123 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
124
Sean Callanan7f27d602011-11-19 02:54:21 +0000125 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000126
127 return true;
128}
129
Sean Callanand1e5b432010-08-12 01:56:52 +0000130bool
Sean Callanan79763a42011-05-23 21:40:23 +0000131IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000132{
133 llvm::Function::iterator bbi;
134 BasicBlock::iterator ii;
Sean Callanan63697e52011-05-07 01:06:41 +0000135
Sean Callanane4ec90e2010-12-16 03:17:46 +0000136 for (bbi = llvm_function.begin();
137 bbi != llvm_function.end();
138 ++bbi)
139 {
140 BasicBlock &basic_block = *bbi;
141
142 for (ii = basic_block.begin();
143 ii != basic_block.end();
144 ++ii)
145 {
146 switch (ii->getOpcode())
147 {
148 default:
149 return true;
150 case Instruction::Store:
151 {
152 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
153
154 Value *store_ptr = store_inst->getPointerOperand();
155
Sean Callanan63697e52011-05-07 01:06:41 +0000156 std::string ptr_name;
157
158 if (store_ptr->hasName())
Sean Callanan7f27d602011-11-19 02:54:21 +0000159 ptr_name = store_ptr->getName().str();
Sean Callanan63697e52011-05-07 01:06:41 +0000160
161 if (isa <AllocaInst> (store_ptr))
Sean Callanane4ec90e2010-12-16 03:17:46 +0000162 break;
Sean Callanan63697e52011-05-07 01:06:41 +0000163
164 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
165 {
166 if (ptr_name.find("GV") == std::string::npos)
167 m_result_store = store_inst;
168 }
169 else
170 {
171 return true;
172 }
173
174 break;
Sean Callanane4ec90e2010-12-16 03:17:46 +0000175 }
176 case Instruction::Load:
177 case Instruction::Alloca:
178 case Instruction::GetElementPtr:
Sean Callanan63697e52011-05-07 01:06:41 +0000179 case Instruction::BitCast:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000180 case Instruction::Ret:
Sean Callanan63697e52011-05-07 01:06:41 +0000181 case Instruction::ICmp:
182 case Instruction::Br:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000183 break;
184 }
185 }
186 }
187
188 return false;
189}
190
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000191bool
192IRForTarget::GetFunctionAddress (llvm::Function *fun,
193 uint64_t &fun_addr,
194 lldb_private::ConstString &name,
195 Constant **&value_ptr)
196{
Greg Clayton5160ce52013-03-27 23:08:40 +0000197 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000198
199 fun_addr = LLDB_INVALID_ADDRESS;
200 name.Clear();
201 value_ptr = NULL;
202
203 if (fun->isIntrinsic())
204 {
205 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
206
207 switch (intrinsic_id)
208 {
209 default:
210 if (log)
211 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
212
213 if (m_error_stream)
214 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
215
216 return false;
217 case Intrinsic::memcpy:
218 {
219 static lldb_private::ConstString g_memcpy_str ("memcpy");
220 name = g_memcpy_str;
221 }
222 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000223 case Intrinsic::memset:
224 {
225 static lldb_private::ConstString g_memset_str ("memset");
226 name = g_memset_str;
227 }
228 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000229 }
230
231 if (log && name)
232 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
233 }
234 else
235 {
236 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
237 }
238
239 // Find the address of the function.
240
241 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000242
243 if (fun_decl)
244 {
Sean Callananc70ed462011-10-25 18:36:40 +0000245 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000246 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000247 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000248 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
249 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000250 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000251 // Check for an alternate mangling for "std::basic_string<char>"
252 // that is part of the itanium C++ name mangling scheme
253 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000254 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000255 {
256 std::string alternate_mangling("_ZNKSs");
257 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000258 altnernate_name.SetCString(alternate_mangling.c_str());
259 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000260 }
261 }
262
263 if (!found_it)
264 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000265 lldb_private::Mangled mangled_name(name);
266 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000267 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000268 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000269 if (alt_mangled_name)
270 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
271 mangled_name.GetName().GetCString(),
272 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000273 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000274 log->Printf("Function \"%s\" had no address",
275 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000276 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000277
278 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000279 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000280 if (alt_mangled_name)
281 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
282 mangled_name.GetName().GetCString(),
283 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000284 else if (mangled_name.GetMangledName())
285 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
286 mangled_name.GetName().GetCString(),
287 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000288 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000289 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
290 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000291 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000292 return false;
293 }
294 }
295 }
296 else
297 {
298 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
299 {
300 if (log)
301 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
302
303 if (m_error_stream)
304 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
305
306 return false;
307 }
308 }
309
310 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000311 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000312
313 return true;
314}
315
316llvm::Constant *
317IRForTarget::BuildFunctionPointer (llvm::Type *type,
318 uint64_t ptr)
319{
320 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000321 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000322 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
323 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
324 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
325}
326
Sean Callananfc8feb82011-10-31 22:11:40 +0000327void
328IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
329 llvm::Value *function_ptr,
330 const char *name)
331{
Sean Callananfc8feb82011-10-31 22:11:40 +0000332 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
333 i != e;
334 ++i)
335 {
336 Value *user = *i;
337
338 if (Instruction *user_inst = dyn_cast<Instruction>(user))
339 {
Sean Callanand2b465f2012-02-09 03:22:41 +0000340 Constant *name_array = ConstantDataArray::getString(context, StringRef(name));
Sean Callananfc8feb82011-10-31 22:11:40 +0000341
342 ArrayRef<Value *> md_values(name_array);
343
344 MDNode *metadata = MDNode::get(context, md_values);
345
346 user_inst->setMetadata("lldb.call.realName", metadata);
347 }
348 else
349 {
350 RegisterFunctionMetadata (context, user, name);
351 }
352 }
353}
354
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000355bool
356IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
357 llvm::Function &llvm_function)
358{
Greg Clayton5160ce52013-03-27 23:08:40 +0000359 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000360
361 for (llvm::Module::iterator fi = llvm_module.begin();
362 fi != llvm_module.end();
363 ++fi)
364 {
365 Function *fun = fi;
366
367 bool is_decl = fun->isDeclaration();
368
369 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000370 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000371
372 if (!is_decl)
373 continue;
374
375 if (fun->hasNUses(0))
376 continue; // ignore
377
378 uint64_t addr = LLDB_INVALID_ADDRESS;
379 lldb_private::ConstString name;
380 Constant **value_ptr = NULL;
381
382 if (!GetFunctionAddress(fun,
383 addr,
384 name,
385 value_ptr))
386 return false; // GetFunctionAddress reports its own errors
387
388 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
389
Sean Callananfc8feb82011-10-31 22:11:40 +0000390 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
391
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000392 if (value_ptr)
393 *value_ptr = value;
394
395 fun->replaceAllUsesWith(value);
396 }
397
398 return true;
399}
400
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000401
Sean Callanan63697e52011-05-07 01:06:41 +0000402clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000403IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000404{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000405 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000406
407 if (!named_metadata)
408 return NULL;
409
410 unsigned num_nodes = named_metadata->getNumOperands();
411 unsigned node_index;
412
413 for (node_index = 0;
414 node_index < num_nodes;
415 ++node_index)
416 {
417 MDNode *metadata_node = named_metadata->getOperand(node_index);
418
419 if (!metadata_node)
420 return NULL;
421
422 if (metadata_node->getNumOperands() != 2)
423 continue;
424
425 if (metadata_node->getOperand(0) != global_val)
426 continue;
427
428 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
429
430 if (!constant_int)
431 return NULL;
432
433 uintptr_t ptr = constant_int->getZExtValue();
434
435 return reinterpret_cast<clang::NamedDecl *>(ptr);
436 }
437
438 return NULL;
439}
440
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000441clang::NamedDecl *
442IRForTarget::DeclForGlobal (GlobalValue *global_val)
443{
444 return DeclForGlobal(global_val, m_module);
445}
446
Sean Callanane4ec90e2010-12-16 03:17:46 +0000447bool
Sean Callanan79763a42011-05-23 21:40:23 +0000448IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000449{
Greg Clayton5160ce52013-03-27 23:08:40 +0000450 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000451
Sean Callanan9e6ed532010-09-13 21:34:21 +0000452 if (!m_resolve_vars)
453 return true;
454
455 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000456
Sean Callanan79763a42011-05-23 21:40:23 +0000457 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000458
Sean Callanancc427fa2011-07-30 02:42:06 +0000459 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000460 const char *result_name = NULL;
461
462 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
463 vi != ve;
464 ++vi)
465 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000466 result_name_str = vi->first().str();
467 const char *value_name = result_name_str.c_str();
468
469 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000470 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000471 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000472 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000473 m_result_is_pointer = true;
474 break;
475 }
476
Sean Callanancc427fa2011-07-30 02:42:06 +0000477 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000478 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000479 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000480 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000481 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000482 break;
483 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000484 }
485
486 if (!result_name)
487 {
488 if (log)
489 log->PutCString("Couldn't find result variable");
490
491 return true;
492 }
493
Sean Callanan46ae9e52010-09-28 21:13:03 +0000494 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000495 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000496
Sean Callanan79763a42011-05-23 21:40:23 +0000497 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000498
499 if (!result_value)
500 {
501 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000502 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000503
Sean Callanan3989fb92011-01-27 01:07:04 +0000504 if (m_error_stream)
505 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
506
Sean Callananfc55f5d2010-09-21 00:44:12 +0000507 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000508 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000509
Sean Callanand1e5b432010-08-12 01:56:52 +0000510 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000511 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000512
513 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
514
515 if (!result_global)
516 {
517 if (log)
518 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000519
520 if (m_error_stream)
521 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
522
Sean Callanand1e5b432010-08-12 01:56:52 +0000523 return false;
524 }
525
Sean Callanan79763a42011-05-23 21:40:23 +0000526 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000527 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000528 {
529 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000530 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000531
Sean Callanan3989fb92011-01-27 01:07:04 +0000532 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000533 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 +0000534
Sean Callanand1e5b432010-08-12 01:56:52 +0000535 return false;
536 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000537
Sean Callanan63697e52011-05-07 01:06:41 +0000538 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000539 {
Sean Callanan63697e52011-05-07 01:06:41 +0000540 std::string decl_desc_str;
541 raw_string_ostream decl_desc_stream(decl_desc_str);
542 result_decl->print(decl_desc_stream);
543 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000544
Sean Callanan63697e52011-05-07 01:06:41 +0000545 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000546 }
547
Sean Callanan63697e52011-05-07 01:06:41 +0000548 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
549 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000550 {
551 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000552 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000553
554 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000555 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 +0000556
Sean Callanand1e5b432010-08-12 01:56:52 +0000557 return false;
558 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000559
Sean Callanand1e5b432010-08-12 01:56:52 +0000560 // Get the next available result name from m_decl_map and create the persistent
561 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000562
Sean Callanan63697e52011-05-07 01:06:41 +0000563 // If the result is an Lvalue, it is emitted as a pointer; see
564 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000565 if (m_result_is_pointer)
566 {
Sean Callanan63697e52011-05-07 01:06:41 +0000567 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000568 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000569
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000570 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
571 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000572
573 if (pointer_pointertype)
574 {
575 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
576
577 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
578 &result_decl->getASTContext());
579 }
580 else if (pointer_objcobjpointertype)
581 {
582 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
583
584 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
585 &result_decl->getASTContext());
586 }
587 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000588 {
589 if (log)
590 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000591
592 if (m_error_stream)
593 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
594
Sean Callanan92adcac2011-01-13 08:53:35 +0000595 return false;
596 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000597 }
598 else
599 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000600 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000601 &result_decl->getASTContext());
602 }
603
604 if (m_result_type.GetClangTypeBitWidth() == 0)
605 {
606 lldb_private::StreamString type_desc_stream;
607 m_result_type.DumpTypeDescription(&type_desc_stream);
608
609 if (log)
610 log->Printf("Result type has size 0");
611
612 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000613 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000614 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000615 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000616 }
617
Sean Callanan63697e52011-05-07 01:06:41 +0000618 if (log)
619 {
620 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000621 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000622
Sean Callanan00f43622011-11-18 03:28:09 +0000623 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000624 }
625
Sean Callanan1582ee62013-04-18 22:06:33 +0000626 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000627
628 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000629 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000630 m_result_name.GetCString(),
631 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanand1e5b432010-08-12 01:56:52 +0000632
633 // Construct a new result global and set up its metadata
634
Sean Callanan79763a42011-05-23 21:40:23 +0000635 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000636 result_global->getType()->getElementType(),
637 false, /* not constant */
638 GlobalValue::ExternalLinkage,
639 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000640 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000641
642 // It's too late in compilation to create a new VarDecl for this, but we don't
643 // need to. We point the metadata at the old VarDecl. This creates an odd
644 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000645 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000646 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
647 // fixed up.
648
Sean Callanan79763a42011-05-23 21:40:23 +0000649 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000650 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000651 false);
652
653 llvm::Value* values[2];
654 values[0] = new_result_global;
655 values[1] = new_constant_int;
656
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000657 ArrayRef<Value*> value_ref(values, 2);
658
Sean Callanan79763a42011-05-23 21:40:23 +0000659 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
660 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000661 named_metadata->addOperand(persistent_global_md);
662
663 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000664 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000665 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000666 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000667
668 if (result_global->hasNUses(0))
669 {
670 // We need to synthesize a store for this variable, because otherwise
671 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000672
Greg Clayton7b462cc2010-10-15 22:48:33 +0000673 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000674 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
675
676 if (!first_entry_instruction)
677 return false;
678
679 if (!result_global->hasInitializer())
680 {
681 if (log)
682 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000683
684 if (m_error_stream)
685 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
686
Sean Callanan1e87fff2010-09-07 22:43:19 +0000687 return false;
688 }
689
690 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000691
692 // Here we write the initializer into a result variable assuming it
693 // can be computed statically.
694
695 if (!m_has_side_effects)
696 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000697 //MaybeSetConstantResult (initializer,
698 // m_result_name,
699 // m_result_type);
Sean Callanane4ec90e2010-12-16 03:17:46 +0000700 }
Sean Callanan1e87fff2010-09-07 22:43:19 +0000701
Greg Clayton9c139312011-02-05 02:28:58 +0000702 StoreInst *synthesized_store = new StoreInst(initializer,
703 new_result_global,
704 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000705
706 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000707 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000708 }
709 else
710 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000711 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan63697e52011-05-07 01:06:41 +0000712 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000713 //MaybeSetCastResult (m_result_type);
Sean Callanan63697e52011-05-07 01:06:41 +0000714 }
715
Sean Callanan1e87fff2010-09-07 22:43:19 +0000716 result_global->replaceAllUsesWith(new_result_global);
717 }
718
Sean Callanan1582ee62013-04-18 22:06:33 +0000719 if (!m_decl_map->AddPersistentVariable(result_decl,
720 m_result_name,
721 m_result_type,
722 true,
723 m_result_is_pointer))
724 return false;
725
Sean Callanand1e5b432010-08-12 01:56:52 +0000726 result_global->eraseFromParent();
727
728 return true;
729}
730
Johnny Chenee7a3592011-08-09 23:10:20 +0000731#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000732static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000733{
734 if (!depth)
735 return;
736
737 depth--;
738
Johnny Chenee7a3592011-08-09 23:10:20 +0000739 if (log)
740 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000741
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000742 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000743 ui != ue;
744 ++ui)
745 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000746 if (log)
747 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000748 DebugUsers(log, *ui, depth);
749 }
750
Johnny Chenee7a3592011-08-09 23:10:20 +0000751 if (log)
752 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000753}
Johnny Chenee7a3592011-08-09 23:10:20 +0000754#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000755
756bool
Sean Callanan79763a42011-05-23 21:40:23 +0000757IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000758 llvm::GlobalVariable *cstr,
759 Instruction *FirstEntryInstruction)
Sean Callananafe16a72010-11-17 23:00:36 +0000760{
Greg Clayton5160ce52013-03-27 23:08:40 +0000761 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000762
Sean Callanancc427fa2011-07-30 02:42:06 +0000763 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000764
Sean Callanancc427fa2011-07-30 02:42:06 +0000765 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
766 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000767 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +0000768 == Module::Pointer64) ? 64 : 32);
Sean Callanancc427fa2011-07-30 02:42:06 +0000769 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
770 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000771
772 if (!m_CFStringCreateWithBytes)
773 {
774 lldb::addr_t CFStringCreateWithBytes_addr;
775
776 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
777
778 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
779 {
780 if (log)
781 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
782
Sean Callanan3989fb92011-01-27 01:07:04 +0000783 if (m_error_stream)
784 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
785
Sean Callananafe16a72010-11-17 23:00:36 +0000786 return false;
787 }
788
789 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000790 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000791
792 // Build the function type:
793 //
794 // CFStringRef CFStringCreateWithBytes (
795 // CFAllocatorRef alloc,
796 // const UInt8 *bytes,
797 // CFIndex numBytes,
798 // CFStringEncoding encoding,
799 // Boolean isExternalRepresentation
800 // );
801 //
802 // We make the following substitutions:
803 //
804 // CFStringRef -> i8*
805 // CFAllocatorRef -> i8*
806 // UInt8 * -> i8*
807 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
808 // CFStringEncoding -> i32
809 // Boolean -> i8
810
Sean Callanancc427fa2011-07-30 02:42:06 +0000811 Type *arg_type_array[5];
812
813 arg_type_array[0] = i8_ptr_ty;
814 arg_type_array[1] = i8_ptr_ty;
815 arg_type_array[2] = intptr_ty;
816 arg_type_array[3] = i32_ty;
817 arg_type_array[4] = i8_ty;
818
819 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
820
Sean Callanan79763a42011-05-23 21:40:23 +0000821 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000822
823 // Build the constant containing the pointer to the function
824 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
825 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
826 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
827 }
828
Sean Callanand2b465f2012-02-09 03:22:41 +0000829 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000830
831 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000832 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000833
Sean Callananafe16a72010-11-17 23:00:36 +0000834 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000835 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000836 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000837 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
838 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
839
Sean Callanancc427fa2011-07-30 02:42:06 +0000840 Value *argument_array[5];
841
842 argument_array[0] = alloc_arg;
843 argument_array[1] = bytes_arg;
844 argument_array[2] = numBytes_arg;
845 argument_array[3] = encoding_arg;
846 argument_array[4] = isExternal_arg;
847
848 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000849
850 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanancc427fa2011-07-30 02:42:06 +0000851 CFSCWB_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +0000852 "CFStringCreateWithBytes",
853 FirstEntryInstruction);
Sean Callanan7a55a322010-11-18 22:21:58 +0000854
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000855 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callananafe16a72010-11-17 23:00:36 +0000856 {
857 if (log)
858 log->PutCString("Couldn't replace the NSString with the result of the call");
859
Sean Callanan3989fb92011-01-27 01:07:04 +0000860 if (m_error_stream)
861 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
862
Sean Callananafe16a72010-11-17 23:00:36 +0000863 return false;
864 }
865
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000866 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000867
868 return true;
869}
870
871bool
Sean Callanan79763a42011-05-23 21:40:23 +0000872IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callananafe16a72010-11-17 23:00:36 +0000873{
Greg Clayton5160ce52013-03-27 23:08:40 +0000874 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000875
Sean Callanan79763a42011-05-23 21:40:23 +0000876 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000877
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000878 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +0000879 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
880
881 if (!FirstEntryInstruction)
882 {
883 if (log)
884 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
885
Sean Callanan3989fb92011-01-27 01:07:04 +0000886 if (m_error_stream)
887 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
888
Sean Callananafe16a72010-11-17 23:00:36 +0000889 return false;
890 }
891
892 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
893 vi != ve;
894 ++vi)
895 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000896 std::string value_name = vi->first().str();
897 const char *value_name_cstr = value_name.c_str();
898
899 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000900 {
901 Value *nsstring_value = vi->second;
902
903 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
904
905 if (!nsstring_global)
906 {
907 if (log)
908 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000909
910 if (m_error_stream)
911 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
912
Sean Callananafe16a72010-11-17 23:00:36 +0000913 return false;
914 }
915
916 if (!nsstring_global->hasInitializer())
917 {
918 if (log)
919 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000920
921 if (m_error_stream)
922 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
923
Sean Callananafe16a72010-11-17 23:00:36 +0000924 return false;
925 }
926
927 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
928
929 if (!nsstring_struct)
930 {
931 if (log)
932 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000933
934 if (m_error_stream)
935 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
936
Sean Callananafe16a72010-11-17 23:00:36 +0000937 return false;
938 }
939
940 // We expect the following structure:
941 //
942 // struct {
943 // int *isa;
944 // int flags;
945 // char *str;
946 // long length;
947 // };
948
949 if (nsstring_struct->getNumOperands() != 4)
950 {
951 if (log)
952 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 +0000953
954 if (m_error_stream)
955 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
956
Sean Callananafe16a72010-11-17 23:00:36 +0000957 return false;
958 }
959
960 Constant *nsstring_member = nsstring_struct->getOperand(2);
961
962 if (!nsstring_member)
963 {
964 if (log)
965 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000966
967 if (m_error_stream)
968 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
969
Sean Callananafe16a72010-11-17 23:00:36 +0000970 return false;
971 }
972
973 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
974
975 if (!nsstring_expr)
976 {
977 if (log)
978 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000979
980 if (m_error_stream)
981 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
982
Sean Callananafe16a72010-11-17 23:00:36 +0000983 return false;
984 }
985
986 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
987 {
988 if (log)
989 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 +0000990
991 if (m_error_stream)
992 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
993
Sean Callananafe16a72010-11-17 23:00:36 +0000994 return false;
995 }
996
997 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
998
999 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1000
1001 if (!cstr_global)
1002 {
1003 if (log)
1004 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001005
1006 if (m_error_stream)
1007 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 +00001008
Sean Callananafe16a72010-11-17 23:00:36 +00001009 return false;
1010 }
1011
1012 if (!cstr_global->hasInitializer())
1013 {
1014 if (log)
1015 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +00001016
1017 if (m_error_stream)
1018 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1019
Sean Callananafe16a72010-11-17 23:00:36 +00001020 return false;
1021 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001022
1023 /*
Sean Callananafe16a72010-11-17 23:00:36 +00001024 if (!cstr_array)
1025 {
1026 if (log)
1027 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +00001028
1029 if (m_error_stream)
1030 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1031
Sean Callananafe16a72010-11-17 23:00:36 +00001032 return false;
1033 }
1034
1035 if (!cstr_array->isCString())
1036 {
1037 if (log)
1038 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +00001039
1040 if (m_error_stream)
1041 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1042
Sean Callananafe16a72010-11-17 23:00:36 +00001043 return false;
1044 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001045 */
1046
Sean Callanand2b465f2012-02-09 03:22:41 +00001047 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +00001048
1049 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +00001050 {
1051 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +00001052 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 +00001053 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001054 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001055 }
1056
1057 if (!cstr_array)
1058 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001059
Sean Callanan79763a42011-05-23 21:40:23 +00001060 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan3989fb92011-01-27 01:07:04 +00001061 {
Sean Callananafe16a72010-11-17 23:00:36 +00001062 if (log)
1063 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001064
1065 // We don't print an error message here because RewriteObjCConstString has done so for us.
1066
Sean Callananafe16a72010-11-17 23:00:36 +00001067 return false;
1068 }
Sean Callananafe16a72010-11-17 23:00:36 +00001069 }
1070 }
1071
1072 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1073 vi != ve;
1074 ++vi)
1075 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001076 std::string value_name = vi->first().str();
1077 const char *value_name_cstr = value_name.c_str();
1078
1079 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001080 {
1081 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1082
1083 if (!gv)
1084 {
1085 if (log)
1086 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001087
1088 if (m_error_stream)
1089 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1090
Sean Callananafe16a72010-11-17 23:00:36 +00001091 return false;
1092 }
1093
1094 gv->eraseFromParent();
1095
1096 break;
1097 }
1098 }
1099
1100 return true;
1101}
1102
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001103static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001104{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001105 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001106
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001107 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001108 return false;
1109
1110 return true;
1111}
1112
Sean Callanan3989fb92011-01-27 01:07:04 +00001113// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001114bool
Sean Callanan79763a42011-05-23 21:40:23 +00001115IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001116{
Greg Clayton5160ce52013-03-27 23:08:40 +00001117 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001118
1119 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1120
1121 if (!load)
1122 return false;
1123
1124 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1125 //
1126 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1127 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1128 //
1129 // where %obj is the object pointer and %tmp is the selector.
1130 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001131 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1132 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001133
1134 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1135
1136 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1137
1138 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1139 return false;
1140
1141 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1142
1143 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1144
1145 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1146 return false;
1147
1148 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1149
1150 if (!osr_initializer_base)
1151 return false;
1152
1153 // Find the string's initializer (a ConstantArray) and get the string from it
1154
1155 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1156
1157 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1158 return false;
1159
1160 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1161
Sean Callanand2b465f2012-02-09 03:22:41 +00001162 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001163
1164 if (!omvn_initializer_array->isString())
1165 return false;
1166
1167 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1168
1169 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001170 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001171
1172 // Construct a call to sel_registerName
1173
1174 if (!m_sel_registerName)
1175 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001176 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001177
Greg Clayton7b462cc2010-10-15 22:48:33 +00001178 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001179 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001180 return false;
1181
Sean Callananbe3a1b12010-10-26 00:31:56 +00001182 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001183 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001184
Sean Callanan5300d372010-07-31 01:32:05 +00001185 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1186
1187 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001188 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001189 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001190 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001191
Sean Callanancc427fa2011-07-30 02:42:06 +00001192 Type *type_array[1];
1193
1194 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1195
1196 ArrayRef<Type *> srN_arg_types(type_array, 1);
1197
Sean Callanan5300d372010-07-31 01:32:05 +00001198 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1199
1200 // Build the constant containing the pointer to the function
Sean Callanancc427fa2011-07-30 02:42:06 +00001201 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001202 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan5300d372010-07-31 01:32:05 +00001203 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001204 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001205 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1206 }
1207
Sean Callanancc427fa2011-07-30 02:42:06 +00001208 Value *argument_array[1];
1209
Sean Callanan79763a42011-05-23 21:40:23 +00001210 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001211
Sean Callanancc427fa2011-07-30 02:42:06 +00001212 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001213
Sean Callanancc427fa2011-07-30 02:42:06 +00001214 ArrayRef<Value *> srN_arguments(argument_array, 1);
1215
Sean Callanan5300d372010-07-31 01:32:05 +00001216 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001217 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001218 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001219 selector_load);
1220
1221 // Replace the load with the call in all users
1222
1223 selector_load->replaceAllUsesWith(srN_call);
1224
1225 selector_load->eraseFromParent();
1226
1227 return true;
1228}
1229
1230bool
Sean Callanan79763a42011-05-23 21:40:23 +00001231IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001232{
Greg Clayton5160ce52013-03-27 23:08:40 +00001233 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001234
1235 BasicBlock::iterator ii;
1236
1237 typedef SmallVector <Instruction*, 2> InstrList;
1238 typedef InstrList::iterator InstrIterator;
1239
1240 InstrList selector_loads;
1241
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001242 for (ii = basic_block.begin();
1243 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001244 ++ii)
1245 {
1246 Instruction &inst = *ii;
1247
1248 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001249 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001250 selector_loads.push_back(&inst);
1251 }
1252
1253 InstrIterator iter;
1254
1255 for (iter = selector_loads.begin();
1256 iter != selector_loads.end();
1257 ++iter)
1258 {
Sean Callanan79763a42011-05-23 21:40:23 +00001259 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001260 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001261 if (m_error_stream)
1262 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1263
Enrico Granata20edcdb2011-07-19 18:03:25 +00001264 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001265 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001266
Sean Callanan5300d372010-07-31 01:32:05 +00001267 return false;
1268 }
1269 }
1270
1271 return true;
1272}
1273
Sean Callanan3989fb92011-01-27 01:07:04 +00001274// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001275bool
Sean Callanan79763a42011-05-23 21:40:23 +00001276IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001277{
Greg Clayton5160ce52013-03-27 23:08:40 +00001278 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001279
Sean Callanan2235f322010-08-11 03:57:18 +00001280 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1281
1282 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1283
1284 if (!alloc_md || !alloc_md->getNumOperands())
1285 return false;
1286
1287 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1288
1289 if (!constant_int)
1290 return false;
1291
1292 // We attempt to register this as a new persistent variable with the DeclMap.
1293
1294 uintptr_t ptr = constant_int->getZExtValue();
1295
Sean Callanand1e5b432010-08-12 01:56:52 +00001296 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001297
Sean Callanand1e5b432010-08-12 01:56:52 +00001298 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1299 &decl->getASTContext());
1300
Greg Clayton7b462cc2010-10-15 22:48:33 +00001301 StringRef decl_name (decl->getName());
1302 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001303 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001304 return false;
1305
Sean Callanan79763a42011-05-23 21:40:23 +00001306 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001307 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001308 false, /* not constant */
1309 GlobalValue::ExternalLinkage,
1310 NULL, /* no initializer */
1311 alloc->getName().str().c_str());
1312
1313 // What we're going to do here is make believe this was a regular old external
1314 // variable. That means we need to make the metadata valid.
1315
Sean Callanan585c0ec82012-07-04 01:26:26 +00001316 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001317
1318 llvm::Value* values[2];
1319 values[0] = persistent_global;
1320 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001321
1322 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001323
Sean Callanan79763a42011-05-23 21:40:23 +00001324 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001325 named_metadata->addOperand(persistent_global_md);
1326
Sean Callanane1175b72011-01-13 21:23:32 +00001327 // Now, since the variable is a pointer variable, we will drop in a load of that
1328 // pointer variable.
1329
1330 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1331
1332 if (log)
1333 log->Printf("Replacing \"%s\" with \"%s\"",
1334 PrintValue(alloc).c_str(),
1335 PrintValue(persistent_load).c_str());
1336
1337 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001338 alloc->eraseFromParent();
1339
1340 return true;
1341}
1342
1343bool
Sean Callanan79763a42011-05-23 21:40:23 +00001344IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001345{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001346 if (!m_resolve_vars)
1347 return true;
1348
Greg Clayton5160ce52013-03-27 23:08:40 +00001349 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001350
1351 BasicBlock::iterator ii;
1352
1353 typedef SmallVector <Instruction*, 2> InstrList;
1354 typedef InstrList::iterator InstrIterator;
1355
1356 InstrList pvar_allocs;
1357
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001358 for (ii = basic_block.begin();
1359 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001360 ++ii)
1361 {
1362 Instruction &inst = *ii;
1363
1364 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001365 {
1366 llvm::StringRef alloc_name = alloc->getName();
1367
1368 if (alloc_name.startswith("$") &&
1369 !alloc_name.startswith("$__lldb"))
1370 {
1371 if (alloc_name.find_first_of("0123456789") == 1)
1372 {
1373 if (log)
1374 log->Printf("Rejecting a numeric persistent variable.");
1375
Sean Callanan3989fb92011-01-27 01:07:04 +00001376 if (m_error_stream)
1377 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1378
Sean Callananf694a552011-01-21 22:30:25 +00001379 return false;
1380 }
1381
Sean Callanan2235f322010-08-11 03:57:18 +00001382 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001383 }
1384 }
Sean Callanan2235f322010-08-11 03:57:18 +00001385 }
1386
1387 InstrIterator iter;
1388
1389 for (iter = pvar_allocs.begin();
1390 iter != pvar_allocs.end();
1391 ++iter)
1392 {
Sean Callanan79763a42011-05-23 21:40:23 +00001393 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001394 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001395 if (m_error_stream)
1396 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1397
Enrico Granata20edcdb2011-07-19 18:03:25 +00001398 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001399 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001400
Sean Callanan2235f322010-08-11 03:57:18 +00001401 return false;
1402 }
1403 }
1404
1405 return true;
1406}
1407
Sean Callananc70ed462011-10-25 18:36:40 +00001408bool
1409IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1410{
1411 if (!initializer)
1412 return true;
1413
Greg Clayton5160ce52013-03-27 23:08:40 +00001414 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001415
1416 if (log && log->GetVerbose())
1417 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1418
1419 Type *initializer_type = initializer->getType();
1420
1421 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1422 {
1423 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1424 return true;
1425 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001426 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001427 {
1428 if (array_initializer->isString())
1429 {
1430 std::string array_initializer_string = array_initializer->getAsString();
1431 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1432 }
1433 else
1434 {
1435 ArrayType *array_initializer_type = array_initializer->getType();
1436 Type *array_element_type = array_initializer_type->getElementType();
1437
1438 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1439
1440 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1441 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001442 Value *operand_value = array_initializer->getOperand(i);
1443 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1444
1445 if (!operand_constant)
1446 return false;
1447
1448 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001449 return false;
1450 }
1451 }
1452 return true;
1453 }
1454 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1455 {
1456 StructType *struct_initializer_type = struct_initializer->getType();
1457 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1458
1459 for (int i = 0;
1460 i < struct_initializer->getNumOperands();
1461 ++i)
1462 {
1463 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1464 return false;
1465 }
1466 return true;
1467 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001468 else if (isa<ConstantAggregateZero>(initializer))
1469 {
1470 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1471 return true;
1472 }
Sean Callananc70ed462011-10-25 18:36:40 +00001473 return false;
1474}
1475
1476bool
1477IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1478{
1479 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1480 return false;
1481
Sean Callananfe5d1392011-11-15 19:13:54 +00001482 if (global_variable == m_reloc_placeholder)
1483 return true;
1484
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001485 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001486
1487 llvm::Type *variable_type = global_variable->getType();
1488
1489 Constant *initializer = global_variable->getInitializer();
1490
1491 llvm::Type *initializer_type = initializer->getType();
1492
1493 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001494 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1495
1496 const size_t mask = (align - 1);
1497 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001498 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001499 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001500
1501 lldb_private::DataBufferHeap data(size, '\0');
1502
1503 if (initializer)
1504 if (!MaterializeInitializer(data.GetBytes(), initializer))
1505 return false;
1506
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001507 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001508
1509 Constant *new_pointer = BuildRelocation(variable_type, offset);
1510
1511 global_variable->replaceAllUsesWith(new_pointer);
1512
1513 global_variable->eraseFromParent();
1514
1515 return true;
1516}
1517
Sean Callanan3989fb92011-01-27 01:07:04 +00001518// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001519bool
Sean Callanan79763a42011-05-23 21:40:23 +00001520IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001521{
Greg Clayton5160ce52013-03-27 23:08:40 +00001522 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001523
1524 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001525 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001526
Greg Clayton7b462cc2010-10-15 22:48:33 +00001527 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001528 {
Sean Callanan5666b672010-08-04 01:02:13 +00001529 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001530 {
Sean Callanan5666b672010-08-04 01:02:13 +00001531 default:
1532 break;
1533 case Instruction::GetElementPtr:
1534 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001535 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001536 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001537 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001538 }
1539 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001540 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001541 {
Sean Callananc70ed462011-10-25 18:36:40 +00001542 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1543 return MaterializeInternalVariable(global_variable);
1544
Sean Callanan79763a42011-05-23 21:40:23 +00001545 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001546
Sean Callanan5300d372010-07-31 01:32:05 +00001547 if (!named_decl)
1548 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001549 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001550 return true;
1551
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001552 if (!global_variable->hasExternalLinkage())
1553 return true;
1554
Sean Callanan5300d372010-07-31 01:32:05 +00001555 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001556 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001557
Sean Callanan5300d372010-07-31 01:32:05 +00001558 return false;
1559 }
1560
Greg Clayton7b462cc2010-10-15 22:48:33 +00001561 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001562
Sean Callanan038df5032010-09-30 21:18:25 +00001563 void *opaque_type = NULL;
Sean Callanan1d180662010-07-20 23:31:16 +00001564 clang::ASTContext *ast_context = NULL;
Sean Callananea22d422010-07-16 00:09:46 +00001565
1566 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callanan1d180662010-07-20 23:31:16 +00001567 {
Sean Callanan038df5032010-09-30 21:18:25 +00001568 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callanan1d180662010-07-20 23:31:16 +00001569 ast_context = &value_decl->getASTContext();
1570 }
Sean Callananea22d422010-07-16 00:09:46 +00001571 else
Sean Callanan1d180662010-07-20 23:31:16 +00001572 {
Sean Callananea22d422010-07-16 00:09:46 +00001573 return false;
Sean Callanan1d180662010-07-20 23:31:16 +00001574 }
Sean Callanan038df5032010-09-30 21:18:25 +00001575
Sean Callanan92adcac2011-01-13 08:53:35 +00001576 clang::QualType qual_type;
Sean Callanan77eaf442011-07-08 00:39:14 +00001577 const Type *value_type = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00001578
Sean Callanane1175b72011-01-13 21:23:32 +00001579 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001580 {
1581 // The $__lldb_expr_result name indicates the the return value has allocated as
1582 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1583 // accesses to this static variable need to be redirected to the result of dereferencing
1584 // a pointer that is passed in as one of the arguments.
1585 //
1586 // Consequently, when reporting the size of the type, we report a pointer type pointing
1587 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001588 //
1589 // We also do this for any user-declared persistent variables.
Sean Callanan1d180662010-07-20 23:31:16 +00001590
Sean Callanan92adcac2011-01-13 08:53:35 +00001591 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1592 value_type = PointerType::get(global_variable->getType(), 0);
1593 }
1594 else
1595 {
1596 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1597 value_type = global_variable->getType();
1598 }
Sean Callanan038df5032010-09-30 21:18:25 +00001599
Greg Claytonfaac1112013-03-14 18:31:44 +00001600 uint64_t value_size = (ast_context->getTypeSize(qual_type) + 7ull) / 8ull;
1601 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001602
Sean Callanan038df5032010-09-30 21:18:25 +00001603 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +00001604 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001605 name.c_str(),
1606 qual_type.getAsString().c_str(),
1607 PrintType(value_type).c_str(),
1608 value_size,
1609 value_alignment);
Sean Callanan17827832010-12-13 22:46:15 +00001610
Sean Callanan549c9f72010-07-13 21:41:46 +00001611
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001612 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001613 lldb_private::ConstString (name.c_str()),
1614 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001615 value_size,
1616 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001617 {
1618 if (!global_variable->hasExternalLinkage())
1619 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001620 else if (HandleSymbol (global_variable))
1621 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001622 else
1623 return false;
1624 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001625 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001626 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001627 {
1628 if (log)
1629 log->Printf("Function pointers aren't handled right now");
1630
1631 return false;
1632 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001633
1634 return true;
1635}
1636
Sean Callanan3989fb92011-01-27 01:07:04 +00001637// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001638bool
Sean Callanan79763a42011-05-23 21:40:23 +00001639IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001640{
Greg Clayton5160ce52013-03-27 23:08:40 +00001641 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001642
1643 lldb_private::ConstString name(symbol->getName().str().c_str());
1644
Sean Callanan947ccc72011-12-01 02:04:16 +00001645 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001646
Greg Clayton084db102011-06-23 04:25:29 +00001647 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001648 {
1649 if (log)
1650 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1651
1652 return false;
1653 }
1654
1655 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001656 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001657
Sean Callanancc427fa2011-07-30 02:42:06 +00001658 Type *symbol_type = symbol->getType();
Sean Callanancc427fa2011-07-30 02:42:06 +00001659 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001660 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc3a16002011-01-17 23:42:46 +00001661
1662 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1663
1664 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1665
1666 if (log)
1667 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1668
1669 symbol->replaceAllUsesWith(symbol_addr_ptr);
1670
1671 return true;
1672}
1673
1674bool
Sean Callanan79763a42011-05-23 21:40:23 +00001675IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001676{
Greg Clayton5160ce52013-03-27 23:08:40 +00001677 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001678
1679 if (log)
1680 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001681
Sean Callananafe16a72010-11-17 23:00:36 +00001682 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001683 op_index < num_ops;
1684 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001685 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001686 {
1687 if (m_error_stream)
1688 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1689
Sean Callanan85a0a832010-10-05 22:26:43 +00001690 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001691 }
1692
Sean Callanan85a0a832010-10-05 22:26:43 +00001693 return true;
1694}
1695
1696bool
Sean Callananfc89c142011-11-01 23:38:03 +00001697IRForTarget::HandleObjCClass(Value *classlist_reference)
1698{
Greg Clayton5160ce52013-03-27 23:08:40 +00001699 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001700
1701 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1702
1703 if (!global_variable)
1704 return false;
1705
1706 Constant *initializer = global_variable->getInitializer();
1707
1708 if (!initializer)
1709 return false;
1710
1711 if (!initializer->hasName())
1712 return false;
1713
1714 StringRef name(initializer->getName());
1715 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001716 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001717
1718 if (log)
1719 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1720
1721 if (class_ptr == LLDB_INVALID_ADDRESS)
1722 return false;
1723
1724 if (global_variable->use_begin() == global_variable->use_end())
1725 return false;
1726
Sean Callanan719a4d52013-03-23 01:01:16 +00001727 SmallVector<LoadInst *, 2> load_instructions;
1728
Sean Callananfc89c142011-11-01 23:38:03 +00001729 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1730 i != e;
1731 ++i)
1732 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001733 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1734 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001735 }
1736
Sean Callanan719a4d52013-03-23 01:01:16 +00001737 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001738 return false;
1739
1740 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001741 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +00001742 == Module::Pointer64) ? 64 : 32);
Sean Callananfc89c142011-11-01 23:38:03 +00001743
1744 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001745
Sean Callanan719a4d52013-03-23 01:01:16 +00001746 for (LoadInst *load_instruction : load_instructions)
1747 {
1748 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001749
Sean Callanan719a4d52013-03-23 01:01:16 +00001750 load_instruction->replaceAllUsesWith(class_bitcast);
1751
1752 load_instruction->eraseFromParent();
1753 }
Sean Callananfc89c142011-11-01 23:38:03 +00001754
1755 return true;
1756}
1757
1758bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001759IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1760{
1761 BasicBlock::iterator ii;
1762
1763 std::vector<CallInst *> calls_to_remove;
1764
1765 for (ii = basic_block.begin();
1766 ii != basic_block.end();
1767 ++ii)
1768 {
1769 Instruction &inst = *ii;
1770
1771 CallInst *call = dyn_cast<CallInst>(&inst);
1772
1773 // MaybeHandleCallArguments handles error reporting; we are silent here
1774 if (!call)
1775 continue;
1776
1777 bool remove = false;
1778
1779 llvm::Function *func = call->getCalledFunction();
1780
1781 if (func && func->getName() == "__cxa_atexit")
1782 remove = true;
1783
1784 llvm::Value *val = call->getCalledValue();
1785
1786 if (val && val->getName() == "__cxa_atexit")
1787 remove = true;
1788
1789 if (remove)
1790 calls_to_remove.push_back(call);
1791 }
1792
1793 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1794 ci != ce;
1795 ++ci)
1796 {
1797 (*ci)->eraseFromParent();
1798 }
1799
1800 return true;
1801}
1802
1803bool
Sean Callanan79763a42011-05-23 21:40:23 +00001804IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001805{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001806 /////////////////////////////////////////////////////////////////////////
1807 // Prepare the current basic block for execution in the remote process
1808 //
1809
Sean Callanan7ea35012010-07-27 21:39:39 +00001810 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001811
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001812 for (ii = basic_block.begin();
1813 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001814 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001815 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001816 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001817
Sean Callanana4e55172010-11-08 00:31:32 +00001818 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001819
Sean Callanan3989fb92011-01-27 01:07:04 +00001820 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001821 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001822 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001823 }
1824
1825 return true;
1826}
1827
Sean Callanana4e55172010-11-08 00:31:32 +00001828bool
Sean Callanan79763a42011-05-23 21:40:23 +00001829IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001830{
Greg Clayton5160ce52013-03-27 23:08:40 +00001831 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001832
Sean Callanan79763a42011-05-23 21:40:23 +00001833 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001834 global != end;
1835 ++global)
1836 {
Sean Callanan694e2442011-12-22 21:24:49 +00001837 if (!global)
1838 {
1839 if (m_error_stream)
1840 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1841
1842 return false;
1843 }
1844
1845 std::string global_name = (*global).getName().str();
1846
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001847 if (log)
1848 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001849 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001850 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001851
1852 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001853 {
Sean Callanan79763a42011-05-23 21:40:23 +00001854 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001855 {
1856 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001857 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 +00001858
Sean Callananc3a16002011-01-17 23:42:46 +00001859 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001860 }
Sean Callananc3a16002011-01-17 23:42:46 +00001861 }
Sean Callananfc89c142011-11-01 23:38:03 +00001862 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1863 {
1864 if (!HandleObjCClass(global))
1865 {
1866 if (m_error_stream)
1867 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1868
1869 return false;
1870 }
1871 }
Sean Callanan2ad66912013-04-24 21:25:20 +00001872 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1873 {
1874 if (!HandleObjCClass(global))
1875 {
1876 if (m_error_stream)
1877 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1878
1879 return false;
1880 }
1881 }
Sean Callanan79763a42011-05-23 21:40:23 +00001882 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001883 {
Sean Callanan79763a42011-05-23 21:40:23 +00001884 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001885 {
1886 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001887 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 +00001888
Sean Callananc3a16002011-01-17 23:42:46 +00001889 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001890 }
Sean Callananc3a16002011-01-17 23:42:46 +00001891 }
Sean Callanana4e55172010-11-08 00:31:32 +00001892 }
1893
1894 return true;
1895}
1896
Sean Callanan79763a42011-05-23 21:40:23 +00001897bool
1898IRForTarget::ReplaceStrings ()
1899{
Greg Clayton5160ce52013-03-27 23:08:40 +00001900 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001901
Sean Callanan79763a42011-05-23 21:40:23 +00001902 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1903
1904 OffsetsTy offsets;
1905
1906 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1907 gi != ge;
1908 ++gi)
1909 {
1910 GlobalVariable *gv = gi;
1911
1912 if (!gv->hasInitializer())
1913 continue;
1914
1915 Constant *gc = gv->getInitializer();
1916
Sean Callanan5207a342011-08-10 21:05:52 +00001917 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001918
Sean Callanan5207a342011-08-10 21:05:52 +00001919 if (gc->isNullValue())
1920 {
1921 Type *gc_type = gc->getType();
1922
1923 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1924
1925 if (!gc_array_type)
1926 continue;
1927
1928 Type *gc_element_type = gc_array_type->getElementType();
1929
1930 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1931
1932 if (gc_integer_type->getBitWidth() != 8)
1933 continue;
1934
1935 str = "";
1936 }
1937 else
1938 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001939 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001940
1941 if (!gc_array)
1942 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001943
Sean Callanan5207a342011-08-10 21:05:52 +00001944 if (!gc_array->isCString())
1945 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001946
Sean Callanan5207a342011-08-10 21:05:52 +00001947 if (log)
1948 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001949
Sean Callanan5207a342011-08-10 21:05:52 +00001950 str = gc_array->getAsString();
1951 }
1952
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001953 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001954
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001955 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001956 }
1957
Sean Callanancc427fa2011-07-30 02:42:06 +00001958 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001959
1960 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1961 oi != oe;
1962 ++oi)
1963 {
1964 GlobalVariable *gv = oi->first;
1965 size_t offset = oi->second;
1966
1967 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1968
1969 if (log)
1970 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1971
1972 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1973 ui != ue;
1974 ++ui)
1975 {
1976 if (log)
1977 log->Printf("Found use %s", PrintValue(*ui).c_str());
1978
1979 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1980 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1981
1982 if (const_expr)
1983 {
1984 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1985 {
1986 if (log)
1987 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1988
1989 return false;
1990 }
1991
Sean Callanan5207a342011-08-10 21:05:52 +00001992 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1993 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1994
1995 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001996 }
1997 else if (store_inst)
1998 {
1999 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
2000
2001 store_inst->setOperand(0, bit_cast);
2002 }
2003 else
2004 {
2005 if (log)
2006 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
2007
2008 return false;
2009 }
2010 }
2011
2012 gv->eraseFromParent();
2013 }
2014
2015 return true;
2016}
2017
2018bool
2019IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
2020{
Greg Clayton5160ce52013-03-27 23:08:40 +00002021 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002022
2023 typedef SmallVector <Value*, 2> ConstantList;
2024 typedef SmallVector <llvm::Instruction*, 2> UserList;
2025 typedef ConstantList::iterator ConstantIterator;
2026 typedef UserList::iterator UserIterator;
2027
2028 ConstantList static_constants;
2029 UserList static_users;
2030
2031 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2032 ii != ie;
2033 ++ii)
2034 {
2035 llvm::Instruction &inst = *ii;
2036
2037 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2038 oi != oe;
2039 ++oi)
2040 {
2041 Value *operand_val = oi->get();
2042
2043 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2044
Sean Callanan822944c2012-04-26 20:51:20 +00002045 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00002046 {
2047 static_constants.push_back(operand_val);
2048 static_users.push_back(ii);
2049 }
2050 }
2051 }
2052
2053 ConstantIterator constant_iter;
2054 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00002055
Sean Callanan79763a42011-05-23 21:40:23 +00002056 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2057 constant_iter != static_constants.end();
2058 ++constant_iter, ++user_iter)
2059 {
2060 Value *operand_val = *constant_iter;
2061 llvm::Instruction *inst = *user_iter;
2062
2063 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2064
2065 if (operand_constant_fp)
2066 {
Sean Callanan1582ee62013-04-18 22:06:33 +00002067 Type *operand_type = operand_constant_fp->getType();
2068
Sean Callanan79763a42011-05-23 21:40:23 +00002069 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2070 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2071
2072 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2073 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2074
2075 if (log)
2076 {
2077 std::string s;
2078 raw_string_ostream ss(s);
2079 for (size_t index = 0;
2080 index < operand_data_size;
2081 ++index)
2082 {
2083 ss << (uint32_t)operand_raw_data[index];
2084 ss << " ";
2085 }
2086 ss.flush();
2087
Jason Molendafd54b362011-09-20 21:44:10 +00002088 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002089 }
2090
2091 lldb_private::DataBufferHeap data(operand_data_size, 0);
2092
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002093 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002094 {
2095 uint8_t *data_bytes = data.GetBytes();
2096
2097 for (size_t index = 0;
2098 index < operand_data_size;
2099 ++index)
2100 {
2101 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2102 }
2103 }
2104 else
2105 {
2106 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2107 }
2108
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002109 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002110
Sean Callanane3333d62012-06-08 22:20:41 +00002111 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2112
2113 const size_t mask = (align - 1);
2114 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002115 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002116 offset = aligned_offset;
2117
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002118 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002119
Sean Callanancc427fa2011-07-30 02:42:06 +00002120 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002121
Sean Callanan1582ee62013-04-18 22:06:33 +00002122 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002123
2124 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2125
2126 operand_constant_fp->replaceAllUsesWith(fp_load);
2127 }
2128 }
2129
2130 return true;
2131}
2132
Sean Callanan7ea35012010-07-27 21:39:39 +00002133static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002134{
Sean Callanan77eaf442011-07-08 00:39:14 +00002135 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002136
Sean Callananafe16a72010-11-17 23:00:36 +00002137 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002138 return false;
2139
Sean Callanan77eaf442011-07-08 00:39:14 +00002140 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002141
2142 if ((CE = dyn_cast<ConstantExpr>(V)))
2143 {
2144 if (CE->getOpcode() != Instruction::BitCast)
2145 return false;
2146
Sean Callananafe16a72010-11-17 23:00:36 +00002147 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002148 }
2149
Sean Callananafe16a72010-11-17 23:00:36 +00002150 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002151
2152 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2153 return false;
2154
2155 return true;
2156}
2157
Sean Callanan79763a42011-05-23 21:40:23 +00002158void
2159IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002160{
Sean Callanan79763a42011-05-23 21:40:23 +00002161 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002162
2163 Value::use_iterator ui;
2164
2165 for (ui = guard_load->use_begin();
2166 ui != guard_load->use_end();
2167 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002168 {
Greg Claytone6371122010-07-30 20:30:44 +00002169 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002170 {
2171 // do nothing for the moment
2172 }
2173 else
2174 {
2175 ui->replaceUsesOfWith(guard_load, zero);
2176 }
2177 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002178
2179 guard_load->eraseFromParent();
2180}
2181
2182static void ExciseGuardStore(Instruction* guard_store)
2183{
2184 guard_store->eraseFromParent();
2185}
2186
2187bool
Sean Callanan79763a42011-05-23 21:40:23 +00002188IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002189{
2190 ///////////////////////////////////////////////////////
2191 // Eliminate any reference to guard variables found.
2192 //
2193
Sean Callanan7ea35012010-07-27 21:39:39 +00002194 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002195
Sean Callanan7ea35012010-07-27 21:39:39 +00002196 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002197 typedef InstrList::iterator InstrIterator;
2198
2199 InstrList guard_loads;
2200 InstrList guard_stores;
2201
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002202 for (ii = basic_block.begin();
2203 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002204 ++ii)
2205 {
2206 Instruction &inst = *ii;
2207
2208 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2209 if (isGuardVariableRef(load->getPointerOperand()))
2210 guard_loads.push_back(&inst);
2211
2212 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2213 if (isGuardVariableRef(store->getPointerOperand()))
2214 guard_stores.push_back(&inst);
2215 }
2216
2217 InstrIterator iter;
2218
2219 for (iter = guard_loads.begin();
2220 iter != guard_loads.end();
2221 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002222 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002223
2224 for (iter = guard_stores.begin();
2225 iter != guard_stores.end();
2226 ++iter)
2227 ExciseGuardStore(*iter);
2228
2229 return true;
2230}
2231
Sean Callanan3989fb92011-01-27 01:07:04 +00002232// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002233bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002234IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002235{
Greg Clayton5160ce52013-03-27 23:08:40 +00002236 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002237
2238 Value::use_iterator ui;
2239
Sean Callanan2235f322010-08-11 03:57:18 +00002240 SmallVector<User*, 16> users;
2241
2242 // We do this because the use list might change, invalidating our iterator.
2243 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002244 for (ui = old_constant->use_begin();
2245 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002246 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002247 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002248
Johnny Chen44805302011-07-19 19:48:13 +00002249 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002250 i < users.size();
2251 ++i)
2252 {
2253 User *user = users[i];
2254
Sean Callanan7618f4e2010-07-14 23:40:29 +00002255 if (Constant *constant = dyn_cast<Constant>(user))
2256 {
2257 // synthesize a new non-constant equivalent of the constant
2258
2259 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2260 {
2261 switch (constant_expr->getOpcode())
2262 {
2263 default:
2264 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002265 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002266 return false;
2267 case Instruction::BitCast:
2268 {
2269 // UnaryExpr
2270 // OperandList[0] is value
2271
2272 Value *s = constant_expr->getOperand(0);
2273
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002274 if (s == old_constant)
2275 s = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002276
Sean Callanan79763a42011-05-23 21:40:23 +00002277 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002278
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002279 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002280 }
2281 break;
2282 case Instruction::GetElementPtr:
2283 {
2284 // GetElementPtrConstantExpr
2285 // OperandList[0] is base
2286 // OperandList[1]... are indices
2287
2288 Value *ptr = constant_expr->getOperand(0);
2289
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002290 if (ptr == old_constant)
2291 ptr = new_constant;
Sean Callanancc427fa2011-07-30 02:42:06 +00002292
2293 std::vector<Value*> index_vector;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002294
2295 unsigned operand_index;
2296 unsigned num_operands = constant_expr->getNumOperands();
2297
2298 for (operand_index = 1;
2299 operand_index < num_operands;
2300 ++operand_index)
2301 {
2302 Value *operand = constant_expr->getOperand(operand_index);
2303
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002304 if (operand == old_constant)
2305 operand = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002306
Sean Callanancc427fa2011-07-30 02:42:06 +00002307 index_vector.push_back(operand);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002308 }
2309
Sean Callanancc427fa2011-07-30 02:42:06 +00002310 ArrayRef <Value*> indices(index_vector);
2311
2312 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002313
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002314 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002315 }
2316 break;
2317 }
2318 }
2319 else
2320 {
2321 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002322 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002323 return false;
2324 }
2325 }
2326 else
2327 {
2328 // simple fall-through case for non-constants
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002329 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002330 }
2331 }
2332
2333 return true;
2334}
2335
Sean Callanan549c9f72010-07-13 21:41:46 +00002336bool
Sean Callanan79763a42011-05-23 21:40:23 +00002337IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002338{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002339 if (!m_resolve_vars)
2340 return true;
2341
Greg Clayton5160ce52013-03-27 23:08:40 +00002342 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002343
2344 m_decl_map->DoStructLayout();
2345
2346 if (log)
2347 log->Printf("Element arrangement:");
2348
2349 uint32_t num_elements;
2350 uint32_t element_index;
2351
2352 size_t size;
2353 off_t alignment;
2354
2355 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2356 return false;
2357
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002358 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002359
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002360 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002361 {
2362 if (m_error_stream)
2363 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2364
Sean Callanan549c9f72010-07-13 21:41:46 +00002365 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002366 }
2367
Sean Callanan7ea35012010-07-27 21:39:39 +00002368 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002369
Sean Callananfc55f5d2010-09-21 00:44:12 +00002370 if (argument->getName().equals("this"))
2371 {
2372 ++iter;
2373
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002374 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002375 {
2376 if (m_error_stream)
2377 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2378
Sean Callananfc55f5d2010-09-21 00:44:12 +00002379 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002380 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002381
2382 argument = iter;
2383 }
Sean Callanan17827832010-12-13 22:46:15 +00002384 else if (argument->getName().equals("self"))
2385 {
2386 ++iter;
2387
2388 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002389 {
2390 if (m_error_stream)
2391 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2392
Sean Callanan17827832010-12-13 22:46:15 +00002393 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002394 }
Sean Callanan17827832010-12-13 22:46:15 +00002395
2396 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002397 {
2398 if (m_error_stream)
2399 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2400
Sean Callanan17827832010-12-13 22:46:15 +00002401 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002402 }
Sean Callanan17827832010-12-13 22:46:15 +00002403
2404 ++iter;
2405
2406 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002407 {
2408 if (m_error_stream)
2409 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2410
Sean Callanan17827832010-12-13 22:46:15 +00002411 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002412 }
Sean Callanan17827832010-12-13 22:46:15 +00002413
2414 argument = iter;
2415 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002416
Greg Clayton7b462cc2010-10-15 22:48:33 +00002417 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002418 {
2419 if (m_error_stream)
2420 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2421
Sean Callanan549c9f72010-07-13 21:41:46 +00002422 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002423 }
2424
Sean Callanan549c9f72010-07-13 21:41:46 +00002425 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002426 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002427
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002428 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002429 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002430
Sean Callananafe16a72010-11-17 23:00:36 +00002431 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002432 {
2433 if (m_error_stream)
2434 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2435
Sean Callanan549c9f72010-07-13 21:41:46 +00002436 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002437 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002438
Sean Callanan79763a42011-05-23 21:40:23 +00002439 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002440 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002441
2442 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002443 {
2444 if (m_error_stream)
2445 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2446
Sean Callanan549c9f72010-07-13 21:41:46 +00002447 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002448 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002449
2450 for (element_index = 0; element_index < num_elements; ++element_index)
2451 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002452 const clang::NamedDecl *decl = NULL;
2453 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002454 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002455 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002456
Sean Callanan823bb4c2010-08-30 22:17:16 +00002457 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002458 {
2459 if (m_error_stream)
2460 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2461
Sean Callanan549c9f72010-07-13 21:41:46 +00002462 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002463 }
2464
Sean Callanan549c9f72010-07-13 21:41:46 +00002465 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002466 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002467 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002468 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002469 offset);
2470
Sean Callanancc427fa2011-07-30 02:42:06 +00002471 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callananafe16a72010-11-17 23:00:36 +00002472 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan92adcac2011-01-13 08:53:35 +00002473
Sean Callananc70ed462011-10-25 18:36:40 +00002474 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002475 {
Sean Callananc70ed462011-10-25 18:36:40 +00002476 Value *replacement = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00002477
Sean Callananc70ed462011-10-25 18:36:40 +00002478 if (log)
2479 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002480
Sean Callananc70ed462011-10-25 18:36:40 +00002481 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2482 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2483 // entry in order to produce the static variable that the AST thinks it is accessing.
2484 if (name == m_result_name && !m_result_is_pointer)
2485 {
2486 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2487
2488 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2489
2490 replacement = load;
2491 }
2492 else
2493 {
2494 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2495
2496 replacement = bit_cast;
2497 }
2498
2499 if (Constant *constant = dyn_cast<Constant>(value))
2500 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2501 else
2502 value->replaceAllUsesWith(replacement);
2503
2504 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2505 var->eraseFromParent();
2506 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002507 }
2508
2509 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002510 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002511
2512 return true;
2513}
2514
Sean Callanan79763a42011-05-23 21:40:23 +00002515llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002516IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002517{
Sean Callanancc427fa2011-07-30 02:42:06 +00002518 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002519 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002520
2521 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002522
2523 llvm::Constant *offset_array[1];
2524
2525 offset_array[0] = offset_int;
2526
2527 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2528
2529 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002530 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2531
2532 return reloc_getbitcast;
2533}
2534
2535bool
2536IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002537{
Greg Clayton5160ce52013-03-27 23:08:40 +00002538 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002539
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002540 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002541 return true;
2542
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002543 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002544
2545 if (log)
2546 {
2547 if (allocation)
2548 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2549 else
2550 log->Printf("Failed to allocate static data");
2551 }
2552
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002553 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002554 return false;
2555
Sean Callanancc427fa2011-07-30 02:42:06 +00002556 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002557 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002558
2559 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2560 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2561
2562 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2563
2564 m_reloc_placeholder->eraseFromParent();
2565
2566 return true;
2567}
2568
Sean Callanan2ab712f22010-07-03 01:35:46 +00002569bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002570IRForTarget::StripAllGVs (Module &llvm_module)
2571{
Greg Clayton5160ce52013-03-27 23:08:40 +00002572 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002573 std::vector<GlobalVariable *> global_vars;
2574 std::set<GlobalVariable *>erased_vars;
2575
2576 bool erased = true;
2577
2578 while (erased)
2579 {
2580 erased = false;
2581
2582 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2583 gi != ge;
2584 ++gi)
2585 {
2586 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2587
2588 global_var->removeDeadConstantUsers();
2589
2590 if (global_var->use_empty())
2591 {
2592 if (log)
2593 log->Printf("Did remove %s",
2594 PrintValue(global_var).c_str());
2595 global_var->eraseFromParent();
2596 erased = true;
2597 break;
2598 }
2599 }
2600 }
2601
2602 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2603 gi != ge;
2604 ++gi)
2605 {
2606 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2607
2608 GlobalValue::use_iterator ui = global_var->use_begin();
2609
Jim Inghamd77557d2012-11-26 19:54:04 +00002610 if (log)
2611 log->Printf("Couldn't remove %s because of %s",
2612 PrintValue(global_var).c_str(),
2613 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002614 }
2615
2616 return true;
2617}
2618
2619bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002620IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002621{
Greg Clayton5160ce52013-03-27 23:08:40 +00002622 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002623
Sean Callanan79763a42011-05-23 21:40:23 +00002624 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002625 m_target_data.reset(new DataLayout(m_module));
Sean Callanan79763a42011-05-23 21:40:23 +00002626
2627 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002628
2629 if (!function)
2630 {
2631 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002632 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00002633
2634 if (m_error_stream)
Sean Callanan79763a42011-05-23 21:40:23 +00002635 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 +00002636
Sean Callanan2ab712f22010-07-03 01:35:46 +00002637 return false;
2638 }
Sean Callanan79763a42011-05-23 21:40:23 +00002639
2640 if (!FixFunctionLinkage (*function))
2641 {
2642 if (log)
2643 log->Printf("Couldn't fix the linkage for the function");
2644
2645 return false;
2646 }
2647
Sean Callananc70ed462011-10-25 18:36:40 +00002648 if (log)
2649 {
2650 std::string s;
2651 raw_string_ostream oss(s);
2652
2653 m_module->print(oss, NULL);
2654
2655 oss.flush();
2656
2657 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2658 }
2659
Sean Callanancc427fa2011-07-30 02:42:06 +00002660 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002661
2662 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2663 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002664 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002665 GlobalVariable::InternalLinkage,
2666 Constant::getNullValue(intptr_ty),
2667 "reloc_placeholder",
2668 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002669 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002670 0 /* AddressSpace */);
Sean Callanan2ab712f22010-07-03 01:35:46 +00002671
Sean Callanan7ea35012010-07-27 21:39:39 +00002672 Function::iterator bbi;
Sean Callanan2ab712f22010-07-03 01:35:46 +00002673
Sean Callanan79763a42011-05-23 21:40:23 +00002674 m_has_side_effects = HasSideEffects(*function);
Sean Callanane4ec90e2010-12-16 03:17:46 +00002675
Sean Callanand1e5b432010-08-12 01:56:52 +00002676 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002677 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002678 //
2679
Sean Callanan79763a42011-05-23 21:40:23 +00002680 if (!CreateResultVariable(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002681 {
2682 if (log)
2683 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002684
2685 // CreateResultVariable() reports its own errors, so we don't do so here
2686
Sean Callanand1e5b432010-08-12 01:56:52 +00002687 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002688 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002689
2690 for (bbi = function->begin();
2691 bbi != function->end();
2692 ++bbi)
2693 {
2694 if (!RemoveGuards(*bbi))
2695 {
2696 if (log)
2697 log->Printf("RemoveGuards() failed");
2698
2699 // RemoveGuards() reports its own errors, so we don't do so here
2700
2701 return false;
2702 }
2703
2704 if (!RewritePersistentAllocs(*bbi))
2705 {
2706 if (log)
2707 log->Printf("RewritePersistentAllocs() failed");
2708
2709 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2710
2711 return false;
2712 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002713
2714 if (!RemoveCXAAtExit(*bbi))
2715 {
2716 if (log)
2717 log->Printf("RemoveCXAAtExit() failed");
2718
2719 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2720
2721 return false;
2722 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002723 }
2724
Sean Callananea685ae2011-11-01 17:33:54 +00002725 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002726 {
2727 std::string s;
2728 raw_string_ostream oss(s);
2729
2730 m_module->print(oss, NULL);
2731
2732 oss.flush();
2733
2734 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2735 }
2736
Sean Callananafe16a72010-11-17 23:00:36 +00002737 ///////////////////////////////////////////////////////////////////////////////
2738 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2739 //
Sean Callananafe16a72010-11-17 23:00:36 +00002740
Sean Callanan79763a42011-05-23 21:40:23 +00002741 if (!RewriteObjCConstStrings(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002742 {
2743 if (log)
2744 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002745
2746 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2747
Sean Callananafe16a72010-11-17 23:00:36 +00002748 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002749 }
Sean Callananafe16a72010-11-17 23:00:36 +00002750
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002751 ///////////////////////////////
2752 // Resolve function pointers
2753 //
2754
2755 if (!ResolveFunctionPointers(llvm_module, *function))
2756 {
2757 if (log)
2758 log->Printf("ResolveFunctionPointers() failed");
2759
2760 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2761
2762 return false;
2763 }
2764
Sean Callanan2ab712f22010-07-03 01:35:46 +00002765 for (bbi = function->begin();
2766 bbi != function->end();
2767 ++bbi)
2768 {
Sean Callanan79763a42011-05-23 21:40:23 +00002769 if (!RewriteObjCSelectors(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002770 {
2771 if (log)
2772 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002773
2774 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2775
Sean Callanan2235f322010-08-11 03:57:18 +00002776 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002777 }
Sean Callananbad134f2012-07-27 19:25:24 +00002778 }
Sean Callanan2235f322010-08-11 03:57:18 +00002779
Sean Callananbad134f2012-07-27 19:25:24 +00002780 for (bbi = function->begin();
2781 bbi != function->end();
2782 ++bbi)
2783 {
Sean Callanan79763a42011-05-23 21:40:23 +00002784 if (!ResolveCalls(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002785 {
2786 if (log)
2787 log->Printf("ResolveCalls() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002788
2789 // ResolveCalls() reports its own errors, so we don't do so here
2790
Sean Callanan549c9f72010-07-13 21:41:46 +00002791 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002792 }
Sean Callanan79763a42011-05-23 21:40:23 +00002793
2794 if (!ReplaceStaticLiterals(*bbi))
2795 {
2796 if (log)
2797 log->Printf("ReplaceStaticLiterals() failed");
2798
2799 return false;
2800 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002801 }
2802
Sean Callanan038df5032010-09-30 21:18:25 +00002803 ///////////////////////////////
2804 // Run function-level passes
2805 //
2806
Sean Callanan79763a42011-05-23 21:40:23 +00002807 if (!ResolveExternals(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002808 {
2809 if (log)
2810 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002811
2812 // ResolveExternals() reports its own errors, so we don't do so here
2813
Sean Callanana4e55172010-11-08 00:31:32 +00002814 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002815 }
Sean Callanana4e55172010-11-08 00:31:32 +00002816
Sean Callanan79763a42011-05-23 21:40:23 +00002817 if (!ReplaceVariables(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002818 {
2819 if (log)
2820 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002821
2822 // ReplaceVariables() reports its own errors, so we don't do so here
2823
Sean Callanan038df5032010-09-30 21:18:25 +00002824 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002825 }
Sean Callanan038df5032010-09-30 21:18:25 +00002826
Sean Callanan79763a42011-05-23 21:40:23 +00002827 if (!ReplaceStrings())
2828 {
2829 if (log)
2830 log->Printf("ReplaceStrings() failed");
2831
2832 return false;
2833 }
2834
2835 if (!CompleteDataAllocation())
2836 {
2837 if (log)
2838 log->Printf("CompleteDataAllocation() failed");
2839
2840 return false;
2841 }
2842
Sean Callanan3d654b32012-09-24 22:25:51 +00002843 if (!StripAllGVs(llvm_module))
2844 {
2845 if (log)
2846 log->Printf("StripAllGVs() failed");
2847 }
2848
Sean Callananea685ae2011-11-01 17:33:54 +00002849 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002850 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002851 std::string s;
2852 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002853
Sean Callanan79763a42011-05-23 21:40:23 +00002854 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002855
2856 oss.flush();
2857
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002858 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002859 }
2860
2861 return true;
2862}
2863
2864void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002865IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002866{
2867}
2868
2869PassManagerType
2870IRForTarget::getPotentialPassManagerType() const
2871{
2872 return PMT_ModulePassManager;
2873}