blob: 14cb237f5a68870deba8188ef0ec4f038781b858 [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"
Greg Clayton57ee3062013-07-11 22:46:58 +000036#include "lldb/Symbol/ClangASTType.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000037
38#include <map>
39
40using namespace llvm;
41
Sean Callananeaacbc92010-08-18 18:50:51 +000042static char ID;
43
Sean Callanan8dfb68e2013-03-19 00:10:07 +000044IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45 m_execution_unit(execution_unit),
Sean Callanan1582ee62013-04-18 22:06:33 +000046 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000047 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000048{
49}
50
Sean Callanan1f9db3e2013-06-28 21:44:15 +000051IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
52 m_maker(maker),
53 m_values()
54{
55}
56
57IRForTarget::FunctionValueCache::~FunctionValueCache()
58{
59}
60
61llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
62{
63 if (!m_values.count(function))
64 {
65 llvm::Value *ret = m_maker(function);
66 m_values[function] = ret;
67 return ret;
68 }
69 return m_values[function];
70}
71
Sean Callanan8dfb68e2013-03-19 00:10:07 +000072lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000073{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000074 lldb_private::Error err;
75
76 if (m_allocation != LLDB_INVALID_ADDRESS)
77 {
78 m_execution_unit.FreeNow(m_allocation);
79 m_allocation = LLDB_INVALID_ADDRESS;
80 }
81
82 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
83
84 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000085}
86
Sean Callanan1f9db3e2013-06-28 21:44:15 +000087static llvm::Value *FindEntryInstruction (llvm::Function *function)
88{
89 if (function->empty())
90 return NULL;
91
92 return function->getEntryBlock().getFirstNonPHIOrDbg();
93}
94
Greg Clayton1b95a6f2010-11-19 01:05:25 +000095IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
96 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000097 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000098 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000099 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +0000100 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000101 m_resolve_vars(resolve_vars),
102 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +0000103 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +0000104 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000105 m_data_allocator(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +0000106 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +0000107 m_sel_registerName(NULL),
Sean Callanan439dcae2013-12-20 19:55:02 +0000108 m_intptr_ty(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000109 m_error_stream(error_stream),
Sean Callanan63697e52011-05-07 01:06:41 +0000110 m_result_store(NULL),
111 m_result_is_pointer(false),
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000112 m_reloc_placeholder(NULL),
113 m_entry_instruction_finder (FindEntryInstruction)
Sean Callanan2ab712f22010-07-03 01:35:46 +0000114{
115}
116
Sean Callanan038df5032010-09-30 21:18:25 +0000117/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +0000118
119static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000120PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +0000121{
122 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +0000123 if (value)
124 {
125 raw_string_ostream rso(s);
126 value->print(rso);
127 rso.flush();
128 if (truncate)
129 s.resize(s.length() - 1);
130 }
Sean Callanan2235f322010-08-11 03:57:18 +0000131 return s;
132}
133
Sean Callanan038df5032010-09-30 21:18:25 +0000134static std::string
Greg Clayton57ee3062013-07-11 22:46:58 +0000135PrintType(const llvm::Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000136{
137 std::string s;
138 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000139 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000140 rso.flush();
141 if (truncate)
142 s.resize(s.length() - 1);
143 return s;
144}
145
Sean Callanan2ab712f22010-07-03 01:35:46 +0000146IRForTarget::~IRForTarget()
147{
148}
149
Sean Callanan79763a42011-05-23 21:40:23 +0000150bool
151IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
152{
Sean Callanan79763a42011-05-23 21:40:23 +0000153 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
154
Sean Callanan7f27d602011-11-19 02:54:21 +0000155 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000156
157 return true;
158}
159
Sean Callanand1e5b432010-08-12 01:56:52 +0000160bool
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000161IRForTarget::GetFunctionAddress (llvm::Function *fun,
162 uint64_t &fun_addr,
163 lldb_private::ConstString &name,
164 Constant **&value_ptr)
165{
Greg Clayton5160ce52013-03-27 23:08:40 +0000166 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000167
168 fun_addr = LLDB_INVALID_ADDRESS;
169 name.Clear();
170 value_ptr = NULL;
171
172 if (fun->isIntrinsic())
173 {
174 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
175
176 switch (intrinsic_id)
177 {
178 default:
179 if (log)
180 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
181
182 if (m_error_stream)
183 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
184
185 return false;
186 case Intrinsic::memcpy:
187 {
188 static lldb_private::ConstString g_memcpy_str ("memcpy");
189 name = g_memcpy_str;
190 }
191 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000192 case Intrinsic::memset:
193 {
194 static lldb_private::ConstString g_memset_str ("memset");
195 name = g_memset_str;
196 }
197 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000198 }
199
200 if (log && name)
201 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
202 }
203 else
204 {
205 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
206 }
207
208 // Find the address of the function.
209
210 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000211
212 if (fun_decl)
213 {
Sean Callananc70ed462011-10-25 18:36:40 +0000214 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000215 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000216 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000217 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
218 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000219 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000220 // Check for an alternate mangling for "std::basic_string<char>"
221 // that is part of the itanium C++ name mangling scheme
222 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000223 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000224 {
225 std::string alternate_mangling("_ZNKSs");
226 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000227 altnernate_name.SetCString(alternate_mangling.c_str());
228 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000229 }
230 }
231
232 if (!found_it)
233 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000234 lldb_private::Mangled mangled_name(name);
235 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000236 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000237 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000238 if (alt_mangled_name)
239 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
240 mangled_name.GetName().GetCString(),
241 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000242 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000243 log->Printf("Function \"%s\" had no address",
244 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000245 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000246
247 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000248 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000249 if (alt_mangled_name)
250 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
251 mangled_name.GetName().GetCString(),
252 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000253 else if (mangled_name.GetMangledName())
254 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
255 mangled_name.GetName().GetCString(),
256 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000257 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000258 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
259 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000260 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000261 return false;
262 }
263 }
264 }
265 else
266 {
267 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
268 {
269 if (log)
270 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
271
272 if (m_error_stream)
273 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
274
275 return false;
276 }
277 }
278
279 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000280 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000281
282 return true;
283}
284
285llvm::Constant *
286IRForTarget::BuildFunctionPointer (llvm::Type *type,
287 uint64_t ptr)
288{
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
Sean Callanan439dcae2013-12-20 19:55:02 +0000290 Constant *fun_addr_int = ConstantInt::get(m_intptr_ty, ptr, false);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
292}
293
Sean Callananfc8feb82011-10-31 22:11:40 +0000294void
295IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
297 const char *name)
298{
Ed Mastea8553092014-03-10 17:24:16 +0000299 for (llvm::User *user : function_ptr->users())
Sean Callananfc8feb82011-10-31 22:11:40 +0000300 {
Sean Callananfc8feb82011-10-31 22:11:40 +0000301 if (Instruction *user_inst = dyn_cast<Instruction>(user))
302 {
Daniel Maleaf051dbc2013-06-03 20:45:54 +0000303 MDString* md_name = MDString::get(context, StringRef(name));
304
305 MDNode *metadata = MDNode::get(context, md_name);
306
Sean Callananfc8feb82011-10-31 22:11:40 +0000307 user_inst->setMetadata("lldb.call.realName", metadata);
308 }
309 else
310 {
311 RegisterFunctionMetadata (context, user, name);
312 }
313 }
314}
315
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000316bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000317IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000318{
Greg Clayton5160ce52013-03-27 23:08:40 +0000319 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000320
321 for (llvm::Module::iterator fi = llvm_module.begin();
322 fi != llvm_module.end();
323 ++fi)
324 {
325 Function *fun = fi;
326
327 bool is_decl = fun->isDeclaration();
328
329 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000330 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000331
332 if (!is_decl)
333 continue;
334
Sean Callanan339f6152014-03-11 19:19:16 +0000335 if (fun->use_empty())
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000336 continue; // ignore
337
338 uint64_t addr = LLDB_INVALID_ADDRESS;
339 lldb_private::ConstString name;
340 Constant **value_ptr = NULL;
341
342 if (!GetFunctionAddress(fun,
343 addr,
344 name,
345 value_ptr))
346 return false; // GetFunctionAddress reports its own errors
347
348 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
349
Sean Callananfc8feb82011-10-31 22:11:40 +0000350 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
351
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000352 if (value_ptr)
353 *value_ptr = value;
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000354
355 // If we are replacing a function with the nobuiltin attribute, it may
356 // be called with the builtin attribute on call sites. Remove any such
357 // attributes since it's illegal to have a builtin call to something
358 // other than a nobuiltin function.
Jason Molenda12075f72013-10-22 03:11:55 +0000359 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
360 llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000361
Ed Mastea8553092014-03-10 17:24:16 +0000362 for (auto u : fun->users()) {
363 if (auto call = dyn_cast<CallInst>(u)) {
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000364 call->removeAttribute(AttributeSet::FunctionIndex, builtin);
365 }
366 }
367 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000368
369 fun->replaceAllUsesWith(value);
370 }
371
372 return true;
373}
374
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000375
Sean Callanan63697e52011-05-07 01:06:41 +0000376clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000377IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000378{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000379 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000380
381 if (!named_metadata)
382 return NULL;
383
384 unsigned num_nodes = named_metadata->getNumOperands();
385 unsigned node_index;
386
387 for (node_index = 0;
388 node_index < num_nodes;
389 ++node_index)
390 {
391 MDNode *metadata_node = named_metadata->getOperand(node_index);
392
393 if (!metadata_node)
394 return NULL;
395
396 if (metadata_node->getNumOperands() != 2)
397 continue;
398
399 if (metadata_node->getOperand(0) != global_val)
400 continue;
401
402 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
403
404 if (!constant_int)
405 return NULL;
406
407 uintptr_t ptr = constant_int->getZExtValue();
408
409 return reinterpret_cast<clang::NamedDecl *>(ptr);
410 }
411
412 return NULL;
413}
414
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000415clang::NamedDecl *
416IRForTarget::DeclForGlobal (GlobalValue *global_val)
417{
418 return DeclForGlobal(global_val, m_module);
419}
420
Sean Callanane4ec90e2010-12-16 03:17:46 +0000421bool
Sean Callanan79763a42011-05-23 21:40:23 +0000422IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000423{
Greg Clayton5160ce52013-03-27 23:08:40 +0000424 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000425
Sean Callanan9e6ed532010-09-13 21:34:21 +0000426 if (!m_resolve_vars)
427 return true;
428
429 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000430
Sean Callanan79763a42011-05-23 21:40:23 +0000431 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000432
Sean Callanancc427fa2011-07-30 02:42:06 +0000433 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000434 const char *result_name = NULL;
435
436 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
437 vi != ve;
438 ++vi)
439 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000440 result_name_str = vi->first().str();
441 const char *value_name = result_name_str.c_str();
442
443 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000444 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000445 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000446 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000447 m_result_is_pointer = true;
448 break;
449 }
450
Sean Callanancc427fa2011-07-30 02:42:06 +0000451 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000452 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000453 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000454 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000455 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000456 break;
457 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000458 }
459
460 if (!result_name)
461 {
462 if (log)
463 log->PutCString("Couldn't find result variable");
464
Richard Mitton00dec202013-10-11 19:44:23 +0000465 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000466 }
467
Sean Callanan46ae9e52010-09-28 21:13:03 +0000468 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000469 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000470
Sean Callanan79763a42011-05-23 21:40:23 +0000471 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000472
473 if (!result_value)
474 {
475 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000476 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000477
Sean Callanan3989fb92011-01-27 01:07:04 +0000478 if (m_error_stream)
479 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
480
Sean Callananfc55f5d2010-09-21 00:44:12 +0000481 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000482 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000483
Sean Callanand1e5b432010-08-12 01:56:52 +0000484 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000485 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000486
487 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
488
489 if (!result_global)
490 {
491 if (log)
492 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000493
494 if (m_error_stream)
495 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
496
Sean Callanand1e5b432010-08-12 01:56:52 +0000497 return false;
498 }
499
Sean Callanan79763a42011-05-23 21:40:23 +0000500 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000501 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000502 {
503 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000504 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000505
Sean Callanan3989fb92011-01-27 01:07:04 +0000506 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000507 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 +0000508
Sean Callanand1e5b432010-08-12 01:56:52 +0000509 return false;
510 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000511
Sean Callanan63697e52011-05-07 01:06:41 +0000512 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000513 {
Sean Callanan63697e52011-05-07 01:06:41 +0000514 std::string decl_desc_str;
515 raw_string_ostream decl_desc_stream(decl_desc_str);
516 result_decl->print(decl_desc_stream);
517 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000518
Sean Callanan63697e52011-05-07 01:06:41 +0000519 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000520 }
521
Sean Callanan63697e52011-05-07 01:06:41 +0000522 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
523 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000524 {
525 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000526 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000527
528 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000529 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 +0000530
Sean Callanand1e5b432010-08-12 01:56:52 +0000531 return false;
532 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000533
Sean Callanand1e5b432010-08-12 01:56:52 +0000534 // Get the next available result name from m_decl_map and create the persistent
535 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000536
Sean Callanan63697e52011-05-07 01:06:41 +0000537 // If the result is an Lvalue, it is emitted as a pointer; see
538 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000539 if (m_result_is_pointer)
540 {
Sean Callanan63697e52011-05-07 01:06:41 +0000541 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000542 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000543
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000544 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
545 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000546
547 if (pointer_pointertype)
548 {
549 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
550
551 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
552 &result_decl->getASTContext());
553 }
554 else if (pointer_objcobjpointertype)
555 {
556 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
557
558 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
559 &result_decl->getASTContext());
560 }
561 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000562 {
563 if (log)
564 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000565
566 if (m_error_stream)
567 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
568
Sean Callanan92adcac2011-01-13 08:53:35 +0000569 return false;
570 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000571 }
572 else
573 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000574 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000575 &result_decl->getASTContext());
576 }
577
Greg Clayton57ee3062013-07-11 22:46:58 +0000578 if (m_result_type.GetBitSize() == 0)
Sean Callanan00f43622011-11-18 03:28:09 +0000579 {
580 lldb_private::StreamString type_desc_stream;
581 m_result_type.DumpTypeDescription(&type_desc_stream);
582
583 if (log)
584 log->Printf("Result type has size 0");
585
586 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000587 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000588 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000589 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000590 }
591
Sean Callanan63697e52011-05-07 01:06:41 +0000592 if (log)
593 {
594 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000595 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000596
Sean Callanan00f43622011-11-18 03:28:09 +0000597 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000598 }
599
Sean Callanan1582ee62013-04-18 22:06:33 +0000600 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000601
602 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000603 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000604 m_result_name.GetCString(),
Greg Clayton57ee3062013-07-11 22:46:58 +0000605 m_result_type.GetByteSize());
Sean Callanand1e5b432010-08-12 01:56:52 +0000606
607 // Construct a new result global and set up its metadata
608
Sean Callanan79763a42011-05-23 21:40:23 +0000609 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000610 result_global->getType()->getElementType(),
611 false, /* not constant */
612 GlobalValue::ExternalLinkage,
613 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000614 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000615
616 // It's too late in compilation to create a new VarDecl for this, but we don't
617 // need to. We point the metadata at the old VarDecl. This creates an odd
618 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000619 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000620 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
621 // fixed up.
622
Sean Callanan79763a42011-05-23 21:40:23 +0000623 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000624 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000625 false);
626
627 llvm::Value* values[2];
628 values[0] = new_result_global;
629 values[1] = new_constant_int;
630
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000631 ArrayRef<Value*> value_ref(values, 2);
632
Sean Callanan79763a42011-05-23 21:40:23 +0000633 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
634 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000635 named_metadata->addOperand(persistent_global_md);
636
637 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000638 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000639 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000640 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000641
Sean Callanan339f6152014-03-11 19:19:16 +0000642 if (result_global->use_empty())
Sean Callanan1e87fff2010-09-07 22:43:19 +0000643 {
644 // We need to synthesize a store for this variable, because otherwise
645 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000646
Greg Clayton7b462cc2010-10-15 22:48:33 +0000647 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000648 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
649
650 if (!first_entry_instruction)
651 return false;
652
653 if (!result_global->hasInitializer())
654 {
655 if (log)
656 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000657
658 if (m_error_stream)
659 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
660
Sean Callanan1e87fff2010-09-07 22:43:19 +0000661 return false;
662 }
663
664 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000665
Greg Clayton9c139312011-02-05 02:28:58 +0000666 StoreInst *synthesized_store = new StoreInst(initializer,
667 new_result_global,
668 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000669
670 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000671 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000672 }
673 else
674 {
675 result_global->replaceAllUsesWith(new_result_global);
676 }
677
Sean Callanan1582ee62013-04-18 22:06:33 +0000678 if (!m_decl_map->AddPersistentVariable(result_decl,
679 m_result_name,
680 m_result_type,
681 true,
682 m_result_is_pointer))
683 return false;
684
Sean Callanand1e5b432010-08-12 01:56:52 +0000685 result_global->eraseFromParent();
686
687 return true;
688}
689
Ed Mastebde27d22014-03-10 20:49:37 +0000690static void DebugUsers(lldb_private::Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000691{
692 if (!depth)
693 return;
694
695 depth--;
696
Johnny Chenee7a3592011-08-09 23:10:20 +0000697 if (log)
698 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000699
Ed Mastebde27d22014-03-10 20:49:37 +0000700 for (llvm::User *u : value->users())
Sean Callananafe16a72010-11-17 23:00:36 +0000701 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000702 if (log)
Ed Mastea8553092014-03-10 17:24:16 +0000703 log->Printf(" <Use %p> %s", u, PrintValue(u).c_str());
704 DebugUsers(log, u, depth);
Sean Callananafe16a72010-11-17 23:00:36 +0000705 }
706
Johnny Chenee7a3592011-08-09 23:10:20 +0000707 if (log)
708 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000709}
710
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000711bool
Sean Callanan79763a42011-05-23 21:40:23 +0000712IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000713 llvm::GlobalVariable *cstr)
Sean Callananafe16a72010-11-17 23:00:36 +0000714{
Greg Clayton5160ce52013-03-27 23:08:40 +0000715 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000716
Sean Callanancc427fa2011-07-30 02:42:06 +0000717 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000718
Sean Callanancc427fa2011-07-30 02:42:06 +0000719 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +0000720 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
721 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000722
723 if (!m_CFStringCreateWithBytes)
724 {
725 lldb::addr_t CFStringCreateWithBytes_addr;
726
727 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
728
729 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
730 {
731 if (log)
732 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
733
Sean Callanan3989fb92011-01-27 01:07:04 +0000734 if (m_error_stream)
735 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
736
Sean Callananafe16a72010-11-17 23:00:36 +0000737 return false;
738 }
739
740 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000741 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000742
743 // Build the function type:
744 //
745 // CFStringRef CFStringCreateWithBytes (
746 // CFAllocatorRef alloc,
747 // const UInt8 *bytes,
748 // CFIndex numBytes,
749 // CFStringEncoding encoding,
750 // Boolean isExternalRepresentation
751 // );
752 //
753 // We make the following substitutions:
754 //
755 // CFStringRef -> i8*
756 // CFAllocatorRef -> i8*
757 // UInt8 * -> i8*
758 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
759 // CFStringEncoding -> i32
760 // Boolean -> i8
761
Sean Callanancc427fa2011-07-30 02:42:06 +0000762 Type *arg_type_array[5];
763
764 arg_type_array[0] = i8_ptr_ty;
765 arg_type_array[1] = i8_ptr_ty;
Sean Callanan439dcae2013-12-20 19:55:02 +0000766 arg_type_array[2] = m_intptr_ty;
Sean Callanancc427fa2011-07-30 02:42:06 +0000767 arg_type_array[3] = i32_ty;
768 arg_type_array[4] = i8_ty;
769
770 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
771
Sean Callanan79763a42011-05-23 21:40:23 +0000772 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000773
774 // Build the constant containing the pointer to the function
775 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
Sean Callanan439dcae2013-12-20 19:55:02 +0000776 Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000777 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
778 }
779
Sean Callanand2b465f2012-02-09 03:22:41 +0000780 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000781
782 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000783 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000784
Sean Callananafe16a72010-11-17 23:00:36 +0000785 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000786 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanan439dcae2013-12-20 19:55:02 +0000787 Constant *numBytes_arg = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000788 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
789 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
790
Sean Callanancc427fa2011-07-30 02:42:06 +0000791 Value *argument_array[5];
792
793 argument_array[0] = alloc_arg;
794 argument_array[1] = bytes_arg;
795 argument_array[2] = numBytes_arg;
796 argument_array[3] = encoding_arg;
797 argument_array[4] = isExternal_arg;
798
799 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000800
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000801 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
802 return CallInst::Create(m_CFStringCreateWithBytes,
803 CFSCWB_arguments,
804 "CFStringCreateWithBytes",
805 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
806 });
Sean Callanan7a55a322010-11-18 22:21:58 +0000807
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000808 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
Sean Callananafe16a72010-11-17 23:00:36 +0000809 {
810 if (log)
811 log->PutCString("Couldn't replace the NSString with the result of the call");
812
Sean Callanan3989fb92011-01-27 01:07:04 +0000813 if (m_error_stream)
814 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
815
Sean Callananafe16a72010-11-17 23:00:36 +0000816 return false;
817 }
818
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000819 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000820
821 return true;
822}
823
824bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000825IRForTarget::RewriteObjCConstStrings()
Sean Callananafe16a72010-11-17 23:00:36 +0000826{
Greg Clayton5160ce52013-03-27 23:08:40 +0000827 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000828
Sean Callanan79763a42011-05-23 21:40:23 +0000829 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000830
Sean Callananafe16a72010-11-17 23:00:36 +0000831 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
832 vi != ve;
833 ++vi)
834 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000835 std::string value_name = vi->first().str();
836 const char *value_name_cstr = value_name.c_str();
837
838 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000839 {
840 Value *nsstring_value = vi->second;
841
842 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
843
844 if (!nsstring_global)
845 {
846 if (log)
847 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000848
849 if (m_error_stream)
850 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
851
Sean Callananafe16a72010-11-17 23:00:36 +0000852 return false;
853 }
854
855 if (!nsstring_global->hasInitializer())
856 {
857 if (log)
858 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000859
860 if (m_error_stream)
861 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
862
Sean Callananafe16a72010-11-17 23:00:36 +0000863 return false;
864 }
865
866 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
867
868 if (!nsstring_struct)
869 {
870 if (log)
871 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000872
873 if (m_error_stream)
874 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
875
Sean Callananafe16a72010-11-17 23:00:36 +0000876 return false;
877 }
878
879 // We expect the following structure:
880 //
881 // struct {
882 // int *isa;
883 // int flags;
884 // char *str;
885 // long length;
886 // };
887
888 if (nsstring_struct->getNumOperands() != 4)
889 {
890 if (log)
891 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 +0000892
893 if (m_error_stream)
894 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
895
Sean Callananafe16a72010-11-17 23:00:36 +0000896 return false;
897 }
898
899 Constant *nsstring_member = nsstring_struct->getOperand(2);
900
901 if (!nsstring_member)
902 {
903 if (log)
904 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000905
906 if (m_error_stream)
907 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
908
Sean Callananafe16a72010-11-17 23:00:36 +0000909 return false;
910 }
911
912 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
913
914 if (!nsstring_expr)
915 {
916 if (log)
917 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000918
919 if (m_error_stream)
920 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
921
Sean Callananafe16a72010-11-17 23:00:36 +0000922 return false;
923 }
924
925 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
926 {
927 if (log)
928 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 +0000929
930 if (m_error_stream)
931 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
932
Sean Callananafe16a72010-11-17 23:00:36 +0000933 return false;
934 }
935
936 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
937
938 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
939
940 if (!cstr_global)
941 {
942 if (log)
943 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000944
945 if (m_error_stream)
946 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 +0000947
Sean Callananafe16a72010-11-17 23:00:36 +0000948 return false;
949 }
950
951 if (!cstr_global->hasInitializer())
952 {
953 if (log)
954 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000955
956 if (m_error_stream)
957 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
958
Sean Callananafe16a72010-11-17 23:00:36 +0000959 return false;
960 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000961
962 /*
Sean Callananafe16a72010-11-17 23:00:36 +0000963 if (!cstr_array)
964 {
965 if (log)
966 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +0000967
968 if (m_error_stream)
969 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
970
Sean Callananafe16a72010-11-17 23:00:36 +0000971 return false;
972 }
973
974 if (!cstr_array->isCString())
975 {
976 if (log)
977 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +0000978
979 if (m_error_stream)
980 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
981
Sean Callananafe16a72010-11-17 23:00:36 +0000982 return false;
983 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000984 */
985
Sean Callanand2b465f2012-02-09 03:22:41 +0000986 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +0000987
988 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +0000989 {
990 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +0000991 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 +0000992 else
Sean Callanancc427fa2011-07-30 02:42:06 +0000993 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000994 }
995
996 if (!cstr_array)
997 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +0000998
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000999 if (!RewriteObjCConstString(nsstring_global, cstr_global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001000 {
Sean Callananafe16a72010-11-17 23:00:36 +00001001 if (log)
1002 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001003
1004 // We don't print an error message here because RewriteObjCConstString has done so for us.
1005
Sean Callananafe16a72010-11-17 23:00:36 +00001006 return false;
1007 }
Sean Callananafe16a72010-11-17 23:00:36 +00001008 }
1009 }
1010
1011 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1012 vi != ve;
1013 ++vi)
1014 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001015 std::string value_name = vi->first().str();
1016 const char *value_name_cstr = value_name.c_str();
1017
1018 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001019 {
1020 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1021
1022 if (!gv)
1023 {
1024 if (log)
1025 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001026
1027 if (m_error_stream)
1028 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1029
Sean Callananafe16a72010-11-17 23:00:36 +00001030 return false;
1031 }
1032
1033 gv->eraseFromParent();
1034
1035 break;
1036 }
1037 }
1038
1039 return true;
1040}
1041
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001042static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001043{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001044 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001045
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001046 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001047 return false;
1048
1049 return true;
1050}
1051
Sean Callanan3989fb92011-01-27 01:07:04 +00001052// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001053bool
Sean Callanan79763a42011-05-23 21:40:23 +00001054IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001055{
Greg Clayton5160ce52013-03-27 23:08:40 +00001056 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001057
1058 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1059
1060 if (!load)
1061 return false;
1062
1063 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1064 //
1065 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1066 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1067 //
1068 // where %obj is the object pointer and %tmp is the selector.
1069 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001070 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1071 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001072
1073 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1074
1075 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1076
1077 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1078 return false;
1079
1080 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1081
1082 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1083
1084 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1085 return false;
1086
1087 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1088
1089 if (!osr_initializer_base)
1090 return false;
1091
1092 // Find the string's initializer (a ConstantArray) and get the string from it
1093
1094 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1095
1096 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1097 return false;
1098
1099 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1100
Sean Callanand2b465f2012-02-09 03:22:41 +00001101 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001102
1103 if (!omvn_initializer_array->isString())
1104 return false;
1105
1106 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1107
1108 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001109 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001110
1111 // Construct a call to sel_registerName
1112
1113 if (!m_sel_registerName)
1114 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001115 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001116
Greg Clayton7b462cc2010-10-15 22:48:33 +00001117 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001118 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001119 return false;
1120
Sean Callananbe3a1b12010-10-26 00:31:56 +00001121 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001122 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001123
Sean Callanan5300d372010-07-31 01:32:05 +00001124 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1125
1126 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001127 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001128 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001129 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001130
Sean Callanancc427fa2011-07-30 02:42:06 +00001131 Type *type_array[1];
1132
1133 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1134
1135 ArrayRef<Type *> srN_arg_types(type_array, 1);
1136
Sean Callanan5300d372010-07-31 01:32:05 +00001137 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1138
1139 // Build the constant containing the pointer to the function
Sean Callanan5300d372010-07-31 01:32:05 +00001140 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Sean Callanan439dcae2013-12-20 19:55:02 +00001141 Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001142 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1143 }
1144
Sean Callanancc427fa2011-07-30 02:42:06 +00001145 Value *argument_array[1];
1146
Sean Callanan79763a42011-05-23 21:40:23 +00001147 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001148
Sean Callanancc427fa2011-07-30 02:42:06 +00001149 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001150
Sean Callanancc427fa2011-07-30 02:42:06 +00001151 ArrayRef<Value *> srN_arguments(argument_array, 1);
1152
Sean Callanan5300d372010-07-31 01:32:05 +00001153 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001154 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001155 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001156 selector_load);
1157
1158 // Replace the load with the call in all users
1159
1160 selector_load->replaceAllUsesWith(srN_call);
1161
1162 selector_load->eraseFromParent();
1163
1164 return true;
1165}
1166
1167bool
Sean Callanan79763a42011-05-23 21:40:23 +00001168IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001169{
Greg Clayton5160ce52013-03-27 23:08:40 +00001170 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001171
1172 BasicBlock::iterator ii;
1173
1174 typedef SmallVector <Instruction*, 2> InstrList;
1175 typedef InstrList::iterator InstrIterator;
1176
1177 InstrList selector_loads;
1178
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001179 for (ii = basic_block.begin();
1180 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001181 ++ii)
1182 {
1183 Instruction &inst = *ii;
1184
1185 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001186 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001187 selector_loads.push_back(&inst);
1188 }
1189
1190 InstrIterator iter;
1191
1192 for (iter = selector_loads.begin();
1193 iter != selector_loads.end();
1194 ++iter)
1195 {
Sean Callanan79763a42011-05-23 21:40:23 +00001196 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001197 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001198 if (m_error_stream)
1199 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1200
Enrico Granata20edcdb2011-07-19 18:03:25 +00001201 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001202 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001203
Sean Callanan5300d372010-07-31 01:32:05 +00001204 return false;
1205 }
1206 }
1207
1208 return true;
1209}
1210
Sean Callanan3989fb92011-01-27 01:07:04 +00001211// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001212bool
Sean Callanan79763a42011-05-23 21:40:23 +00001213IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001214{
Greg Clayton5160ce52013-03-27 23:08:40 +00001215 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001216
Sean Callanan2235f322010-08-11 03:57:18 +00001217 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1218
1219 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1220
1221 if (!alloc_md || !alloc_md->getNumOperands())
1222 return false;
1223
1224 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1225
1226 if (!constant_int)
1227 return false;
1228
1229 // We attempt to register this as a new persistent variable with the DeclMap.
1230
1231 uintptr_t ptr = constant_int->getZExtValue();
1232
Sean Callanand1e5b432010-08-12 01:56:52 +00001233 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001234
Sean Callanand1e5b432010-08-12 01:56:52 +00001235 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1236 &decl->getASTContext());
1237
Greg Clayton7b462cc2010-10-15 22:48:33 +00001238 StringRef decl_name (decl->getName());
1239 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001240 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001241 return false;
1242
Sean Callanan79763a42011-05-23 21:40:23 +00001243 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001244 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001245 false, /* not constant */
1246 GlobalValue::ExternalLinkage,
1247 NULL, /* no initializer */
1248 alloc->getName().str().c_str());
1249
1250 // What we're going to do here is make believe this was a regular old external
1251 // variable. That means we need to make the metadata valid.
1252
Sean Callanan585c0ec82012-07-04 01:26:26 +00001253 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001254
1255 llvm::Value* values[2];
1256 values[0] = persistent_global;
1257 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001258
1259 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001260
Sean Callanan79763a42011-05-23 21:40:23 +00001261 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001262 named_metadata->addOperand(persistent_global_md);
1263
Sean Callanane1175b72011-01-13 21:23:32 +00001264 // Now, since the variable is a pointer variable, we will drop in a load of that
1265 // pointer variable.
1266
1267 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1268
1269 if (log)
1270 log->Printf("Replacing \"%s\" with \"%s\"",
1271 PrintValue(alloc).c_str(),
1272 PrintValue(persistent_load).c_str());
1273
1274 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001275 alloc->eraseFromParent();
1276
1277 return true;
1278}
1279
1280bool
Sean Callanan79763a42011-05-23 21:40:23 +00001281IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001282{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001283 if (!m_resolve_vars)
1284 return true;
1285
Greg Clayton5160ce52013-03-27 23:08:40 +00001286 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001287
1288 BasicBlock::iterator ii;
1289
1290 typedef SmallVector <Instruction*, 2> InstrList;
1291 typedef InstrList::iterator InstrIterator;
1292
1293 InstrList pvar_allocs;
1294
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001295 for (ii = basic_block.begin();
1296 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001297 ++ii)
1298 {
1299 Instruction &inst = *ii;
1300
1301 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001302 {
1303 llvm::StringRef alloc_name = alloc->getName();
1304
1305 if (alloc_name.startswith("$") &&
1306 !alloc_name.startswith("$__lldb"))
1307 {
1308 if (alloc_name.find_first_of("0123456789") == 1)
1309 {
1310 if (log)
1311 log->Printf("Rejecting a numeric persistent variable.");
1312
Sean Callanan3989fb92011-01-27 01:07:04 +00001313 if (m_error_stream)
1314 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1315
Sean Callananf694a552011-01-21 22:30:25 +00001316 return false;
1317 }
1318
Sean Callanan2235f322010-08-11 03:57:18 +00001319 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001320 }
1321 }
Sean Callanan2235f322010-08-11 03:57:18 +00001322 }
1323
1324 InstrIterator iter;
1325
1326 for (iter = pvar_allocs.begin();
1327 iter != pvar_allocs.end();
1328 ++iter)
1329 {
Sean Callanan79763a42011-05-23 21:40:23 +00001330 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001331 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001332 if (m_error_stream)
1333 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1334
Enrico Granata20edcdb2011-07-19 18:03:25 +00001335 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001336 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001337
Sean Callanan2235f322010-08-11 03:57:18 +00001338 return false;
1339 }
1340 }
1341
1342 return true;
1343}
1344
Sean Callananc70ed462011-10-25 18:36:40 +00001345bool
1346IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1347{
1348 if (!initializer)
1349 return true;
1350
Greg Clayton5160ce52013-03-27 23:08:40 +00001351 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001352
1353 if (log && log->GetVerbose())
1354 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1355
1356 Type *initializer_type = initializer->getType();
1357
1358 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1359 {
1360 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1361 return true;
1362 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001363 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001364 {
1365 if (array_initializer->isString())
1366 {
1367 std::string array_initializer_string = array_initializer->getAsString();
1368 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1369 }
1370 else
1371 {
1372 ArrayType *array_initializer_type = array_initializer->getType();
1373 Type *array_element_type = array_initializer_type->getElementType();
1374
1375 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1376
Andy Gibbsa297a972013-06-19 19:04:53 +00001377 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
Sean Callananc70ed462011-10-25 18:36:40 +00001378 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001379 Value *operand_value = array_initializer->getOperand(i);
1380 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1381
1382 if (!operand_constant)
1383 return false;
1384
1385 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001386 return false;
1387 }
1388 }
1389 return true;
1390 }
1391 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1392 {
1393 StructType *struct_initializer_type = struct_initializer->getType();
1394 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1395
Andy Gibbsa297a972013-06-19 19:04:53 +00001396 for (unsigned i = 0;
Sean Callananc70ed462011-10-25 18:36:40 +00001397 i < struct_initializer->getNumOperands();
1398 ++i)
1399 {
1400 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1401 return false;
1402 }
1403 return true;
1404 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001405 else if (isa<ConstantAggregateZero>(initializer))
1406 {
1407 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1408 return true;
1409 }
Sean Callananc70ed462011-10-25 18:36:40 +00001410 return false;
1411}
1412
1413bool
1414IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1415{
1416 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1417 return false;
1418
Sean Callananfe5d1392011-11-15 19:13:54 +00001419 if (global_variable == m_reloc_placeholder)
1420 return true;
1421
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001422 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001423
1424 llvm::Type *variable_type = global_variable->getType();
1425
1426 Constant *initializer = global_variable->getInitializer();
1427
1428 llvm::Type *initializer_type = initializer->getType();
1429
1430 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001431 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1432
1433 const size_t mask = (align - 1);
1434 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001435 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001436 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001437
1438 lldb_private::DataBufferHeap data(size, '\0');
1439
1440 if (initializer)
1441 if (!MaterializeInitializer(data.GetBytes(), initializer))
1442 return false;
1443
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001444 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001445
1446 Constant *new_pointer = BuildRelocation(variable_type, offset);
1447
1448 global_variable->replaceAllUsesWith(new_pointer);
1449
1450 global_variable->eraseFromParent();
1451
1452 return true;
1453}
1454
Sean Callanan3989fb92011-01-27 01:07:04 +00001455// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001456bool
Sean Callanan79763a42011-05-23 21:40:23 +00001457IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001458{
Greg Clayton5160ce52013-03-27 23:08:40 +00001459 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001460
1461 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001462 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001463
Greg Clayton7b462cc2010-10-15 22:48:33 +00001464 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001465 {
Sean Callanan5666b672010-08-04 01:02:13 +00001466 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001467 {
Sean Callanan5666b672010-08-04 01:02:13 +00001468 default:
1469 break;
1470 case Instruction::GetElementPtr:
1471 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001472 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001473 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001474 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001475 }
1476 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001477 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001478 {
Sean Callananc70ed462011-10-25 18:36:40 +00001479 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1480 return MaterializeInternalVariable(global_variable);
1481
Sean Callanan79763a42011-05-23 21:40:23 +00001482 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001483
Sean Callanan5300d372010-07-31 01:32:05 +00001484 if (!named_decl)
1485 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001486 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001487 return true;
1488
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001489 if (!global_variable->hasExternalLinkage())
1490 return true;
1491
Sean Callanan5300d372010-07-31 01:32:05 +00001492 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001493 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001494
Sean Callanan5300d372010-07-31 01:32:05 +00001495 return false;
1496 }
1497
Greg Clayton7b462cc2010-10-15 22:48:33 +00001498 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001499
Greg Clayton57ee3062013-07-11 22:46:58 +00001500 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1501 if (value_decl == NULL)
Sean Callananea22d422010-07-16 00:09:46 +00001502 return false;
Greg Clayton57ee3062013-07-11 22:46:58 +00001503
1504 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
Sean Callanan038df5032010-09-30 21:18:25 +00001505
Sean Callanan77eaf442011-07-08 00:39:14 +00001506 const Type *value_type = NULL;
Greg Clayton57ee3062013-07-11 22:46:58 +00001507
Sean Callanane1175b72011-01-13 21:23:32 +00001508 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001509 {
1510 // The $__lldb_expr_result name indicates the the return value has allocated as
1511 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1512 // accesses to this static variable need to be redirected to the result of dereferencing
1513 // a pointer that is passed in as one of the arguments.
1514 //
1515 // Consequently, when reporting the size of the type, we report a pointer type pointing
1516 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001517 //
1518 // We also do this for any user-declared persistent variables.
Greg Clayton57ee3062013-07-11 22:46:58 +00001519 clang_type = clang_type.GetPointerType();
Sean Callanan92adcac2011-01-13 08:53:35 +00001520 value_type = PointerType::get(global_variable->getType(), 0);
1521 }
1522 else
1523 {
Sean Callanan92adcac2011-01-13 08:53:35 +00001524 value_type = global_variable->getType();
1525 }
Greg Clayton57ee3062013-07-11 22:46:58 +00001526
1527 const uint64_t value_size = clang_type.GetByteSize();
1528 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001529
Sean Callanan038df5032010-09-30 21:18:25 +00001530 if (log)
Greg Clayton57ee3062013-07-11 22:46:58 +00001531 {
Greg Claytonfaac1112013-03-14 18:31:44 +00001532 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001533 name.c_str(),
Greg Clayton57ee3062013-07-11 22:46:58 +00001534 clang_type.GetQualType().getAsString().c_str(),
1535 PrintType(value_type).c_str(),
Sean Callanan038df5032010-09-30 21:18:25 +00001536 value_size,
1537 value_alignment);
Greg Clayton57ee3062013-07-11 22:46:58 +00001538 }
Sean Callanan17827832010-12-13 22:46:15 +00001539
Sean Callanan549c9f72010-07-13 21:41:46 +00001540
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001541 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001542 lldb_private::ConstString (name.c_str()),
1543 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001544 value_size,
1545 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001546 {
1547 if (!global_variable->hasExternalLinkage())
1548 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001549 else if (HandleSymbol (global_variable))
1550 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001551 else
1552 return false;
1553 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001554 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001555 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001556 {
1557 if (log)
1558 log->Printf("Function pointers aren't handled right now");
1559
1560 return false;
1561 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001562
1563 return true;
1564}
1565
Sean Callanan3989fb92011-01-27 01:07:04 +00001566// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001567bool
Sean Callanan79763a42011-05-23 21:40:23 +00001568IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001569{
Greg Clayton5160ce52013-03-27 23:08:40 +00001570 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001571
1572 lldb_private::ConstString name(symbol->getName().str().c_str());
1573
Sean Callanan947ccc72011-12-01 02:04:16 +00001574 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001575
Greg Clayton084db102011-06-23 04:25:29 +00001576 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001577 {
1578 if (log)
1579 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1580
1581 return false;
1582 }
1583
1584 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001585 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001586
Sean Callanancc427fa2011-07-30 02:42:06 +00001587 Type *symbol_type = symbol->getType();
Sean Callananc3a16002011-01-17 23:42:46 +00001588
Sean Callanan439dcae2013-12-20 19:55:02 +00001589 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
Sean Callananc3a16002011-01-17 23:42:46 +00001590
1591 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1592
1593 if (log)
1594 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1595
1596 symbol->replaceAllUsesWith(symbol_addr_ptr);
1597
1598 return true;
1599}
1600
1601bool
Sean Callanan79763a42011-05-23 21:40:23 +00001602IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001603{
Greg Clayton5160ce52013-03-27 23:08:40 +00001604 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001605
1606 if (log)
1607 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001608
Sean Callananafe16a72010-11-17 23:00:36 +00001609 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001610 op_index < num_ops;
1611 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001612 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001613 {
1614 if (m_error_stream)
1615 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1616
Sean Callanan85a0a832010-10-05 22:26:43 +00001617 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001618 }
1619
Sean Callanan85a0a832010-10-05 22:26:43 +00001620 return true;
1621}
1622
1623bool
Sean Callananfc89c142011-11-01 23:38:03 +00001624IRForTarget::HandleObjCClass(Value *classlist_reference)
1625{
Greg Clayton5160ce52013-03-27 23:08:40 +00001626 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001627
1628 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1629
1630 if (!global_variable)
1631 return false;
1632
1633 Constant *initializer = global_variable->getInitializer();
1634
1635 if (!initializer)
1636 return false;
1637
1638 if (!initializer->hasName())
1639 return false;
1640
1641 StringRef name(initializer->getName());
1642 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001643 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001644
1645 if (log)
1646 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1647
1648 if (class_ptr == LLDB_INVALID_ADDRESS)
1649 return false;
1650
Ed Mastea8553092014-03-10 17:24:16 +00001651 if (global_variable->use_empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001652 return false;
1653
Sean Callanan719a4d52013-03-23 01:01:16 +00001654 SmallVector<LoadInst *, 2> load_instructions;
1655
Ed Mastea8553092014-03-10 17:24:16 +00001656 for (llvm::User *u : global_variable->users())
Sean Callananfc89c142011-11-01 23:38:03 +00001657 {
Ed Mastea8553092014-03-10 17:24:16 +00001658 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
Sean Callanan719a4d52013-03-23 01:01:16 +00001659 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001660 }
1661
Sean Callanan719a4d52013-03-23 01:01:16 +00001662 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001663 return false;
1664
Sean Callanan439dcae2013-12-20 19:55:02 +00001665 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001666
Sean Callanan719a4d52013-03-23 01:01:16 +00001667 for (LoadInst *load_instruction : load_instructions)
1668 {
1669 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001670
Sean Callanan719a4d52013-03-23 01:01:16 +00001671 load_instruction->replaceAllUsesWith(class_bitcast);
1672
1673 load_instruction->eraseFromParent();
1674 }
Sean Callananfc89c142011-11-01 23:38:03 +00001675
1676 return true;
1677}
1678
1679bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001680IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1681{
1682 BasicBlock::iterator ii;
1683
1684 std::vector<CallInst *> calls_to_remove;
1685
1686 for (ii = basic_block.begin();
1687 ii != basic_block.end();
1688 ++ii)
1689 {
1690 Instruction &inst = *ii;
1691
1692 CallInst *call = dyn_cast<CallInst>(&inst);
1693
1694 // MaybeHandleCallArguments handles error reporting; we are silent here
1695 if (!call)
1696 continue;
1697
1698 bool remove = false;
1699
1700 llvm::Function *func = call->getCalledFunction();
1701
1702 if (func && func->getName() == "__cxa_atexit")
1703 remove = true;
1704
1705 llvm::Value *val = call->getCalledValue();
1706
1707 if (val && val->getName() == "__cxa_atexit")
1708 remove = true;
1709
1710 if (remove)
1711 calls_to_remove.push_back(call);
1712 }
1713
1714 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1715 ci != ce;
1716 ++ci)
1717 {
1718 (*ci)->eraseFromParent();
1719 }
1720
1721 return true;
1722}
1723
1724bool
Sean Callanan79763a42011-05-23 21:40:23 +00001725IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001726{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001727 /////////////////////////////////////////////////////////////////////////
1728 // Prepare the current basic block for execution in the remote process
1729 //
1730
Sean Callanan7ea35012010-07-27 21:39:39 +00001731 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001732
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001733 for (ii = basic_block.begin();
1734 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001735 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001736 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001737 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001738
Sean Callanana4e55172010-11-08 00:31:32 +00001739 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001740
Sean Callanan3989fb92011-01-27 01:07:04 +00001741 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001742 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001743 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001744 }
1745
1746 return true;
1747}
1748
Sean Callanana4e55172010-11-08 00:31:32 +00001749bool
Sean Callanan79763a42011-05-23 21:40:23 +00001750IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001751{
Greg Clayton5160ce52013-03-27 23:08:40 +00001752 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001753
Sean Callanan339f6152014-03-11 19:19:16 +00001754 for (GlobalVariable &global_var : m_module->globals())
Sean Callanana4e55172010-11-08 00:31:32 +00001755 {
Sean Callanan339f6152014-03-11 19:19:16 +00001756 std::string global_name = global_var.getName().str();
Sean Callanan694e2442011-12-22 21:24:49 +00001757
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001758 if (log)
1759 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001760 global_name.c_str(),
Sean Callanan339f6152014-03-11 19:19:16 +00001761 DeclForGlobal(&global_var));
Sean Callananfc89c142011-11-01 23:38:03 +00001762
1763 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001764 {
Sean Callanan339f6152014-03-11 19:19:16 +00001765 if (!HandleSymbol(&global_var))
Sean Callanan3989fb92011-01-27 01:07:04 +00001766 {
1767 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001768 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 +00001769
Sean Callananc3a16002011-01-17 23:42:46 +00001770 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001771 }
Sean Callananc3a16002011-01-17 23:42:46 +00001772 }
Sean Callananfc89c142011-11-01 23:38:03 +00001773 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1774 {
Sean Callanan339f6152014-03-11 19:19:16 +00001775 if (!HandleObjCClass(&global_var))
Sean Callananfc89c142011-11-01 23:38:03 +00001776 {
1777 if (m_error_stream)
1778 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1779
1780 return false;
1781 }
1782 }
Sean Callanan2ad66912013-04-24 21:25:20 +00001783 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1784 {
Sean Callanan339f6152014-03-11 19:19:16 +00001785 if (!HandleObjCClass(&global_var))
Sean Callanan2ad66912013-04-24 21:25:20 +00001786 {
1787 if (m_error_stream)
1788 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1789
1790 return false;
1791 }
1792 }
Sean Callanan339f6152014-03-11 19:19:16 +00001793 else if (DeclForGlobal(&global_var))
Sean Callananc3a16002011-01-17 23:42:46 +00001794 {
Sean Callanan339f6152014-03-11 19:19:16 +00001795 if (!MaybeHandleVariable (&global_var))
Sean Callanan3989fb92011-01-27 01:07:04 +00001796 {
1797 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001798 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 +00001799
Sean Callananc3a16002011-01-17 23:42:46 +00001800 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001801 }
Sean Callananc3a16002011-01-17 23:42:46 +00001802 }
Sean Callanana4e55172010-11-08 00:31:32 +00001803 }
1804
1805 return true;
1806}
1807
Sean Callanan79763a42011-05-23 21:40:23 +00001808bool
1809IRForTarget::ReplaceStrings ()
1810{
Greg Clayton5160ce52013-03-27 23:08:40 +00001811 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001812
Sean Callanan79763a42011-05-23 21:40:23 +00001813 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1814
1815 OffsetsTy offsets;
1816
Sean Callanan339f6152014-03-11 19:19:16 +00001817 for (GlobalVariable &gv : m_module->globals())
Sean Callanan79763a42011-05-23 21:40:23 +00001818 {
Sean Callanan339f6152014-03-11 19:19:16 +00001819 if (!gv.hasInitializer())
Sean Callanan79763a42011-05-23 21:40:23 +00001820 continue;
1821
Sean Callanan339f6152014-03-11 19:19:16 +00001822 Constant *gc = gv.getInitializer();
Sean Callanan79763a42011-05-23 21:40:23 +00001823
Sean Callanan5207a342011-08-10 21:05:52 +00001824 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001825
Sean Callanan5207a342011-08-10 21:05:52 +00001826 if (gc->isNullValue())
1827 {
1828 Type *gc_type = gc->getType();
1829
1830 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1831
1832 if (!gc_array_type)
1833 continue;
1834
1835 Type *gc_element_type = gc_array_type->getElementType();
1836
1837 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1838
1839 if (gc_integer_type->getBitWidth() != 8)
1840 continue;
1841
1842 str = "";
1843 }
1844 else
1845 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001846 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001847
1848 if (!gc_array)
1849 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001850
Sean Callanan5207a342011-08-10 21:05:52 +00001851 if (!gc_array->isCString())
1852 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001853
Sean Callanan5207a342011-08-10 21:05:52 +00001854 if (log)
1855 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001856
Sean Callanan5207a342011-08-10 21:05:52 +00001857 str = gc_array->getAsString();
1858 }
1859
Sean Callanan339f6152014-03-11 19:19:16 +00001860 offsets[&gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001861
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001862 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001863 }
1864
Sean Callanancc427fa2011-07-30 02:42:06 +00001865 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001866
1867 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1868 oi != oe;
1869 ++oi)
1870 {
1871 GlobalVariable *gv = oi->first;
1872 size_t offset = oi->second;
1873
1874 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1875
1876 if (log)
1877 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1878
Ed Mastea8553092014-03-10 17:24:16 +00001879 for (llvm::User *u : gv->users())
Sean Callanan79763a42011-05-23 21:40:23 +00001880 {
1881 if (log)
Ed Mastea8553092014-03-10 17:24:16 +00001882 log->Printf("Found use %s", PrintValue(u).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001883
Ed Mastea8553092014-03-10 17:24:16 +00001884 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(u);
1885 StoreInst *store_inst = dyn_cast<StoreInst>(u);
Sean Callanan79763a42011-05-23 21:40:23 +00001886
1887 if (const_expr)
1888 {
1889 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1890 {
1891 if (log)
1892 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1893
1894 return false;
1895 }
1896
Sean Callanan5207a342011-08-10 21:05:52 +00001897 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1898 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1899
1900 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001901 }
1902 else if (store_inst)
1903 {
1904 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1905
1906 store_inst->setOperand(0, bit_cast);
1907 }
1908 else
1909 {
1910 if (log)
1911 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1912
1913 return false;
1914 }
1915 }
1916
1917 gv->eraseFromParent();
1918 }
1919
1920 return true;
1921}
1922
1923bool
1924IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1925{
Greg Clayton5160ce52013-03-27 23:08:40 +00001926 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001927
1928 typedef SmallVector <Value*, 2> ConstantList;
1929 typedef SmallVector <llvm::Instruction*, 2> UserList;
1930 typedef ConstantList::iterator ConstantIterator;
1931 typedef UserList::iterator UserIterator;
1932
1933 ConstantList static_constants;
1934 UserList static_users;
1935
1936 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1937 ii != ie;
1938 ++ii)
1939 {
1940 llvm::Instruction &inst = *ii;
1941
Sean Callanan339f6152014-03-11 19:19:16 +00001942 for (Value *operand_val : inst.operand_values())
Sean Callanan79763a42011-05-23 21:40:23 +00001943 {
Sean Callanan79763a42011-05-23 21:40:23 +00001944 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1945
Sean Callanan822944c2012-04-26 20:51:20 +00001946 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00001947 {
1948 static_constants.push_back(operand_val);
1949 static_users.push_back(ii);
1950 }
1951 }
1952 }
1953
1954 ConstantIterator constant_iter;
1955 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00001956
Sean Callanan79763a42011-05-23 21:40:23 +00001957 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1958 constant_iter != static_constants.end();
1959 ++constant_iter, ++user_iter)
1960 {
1961 Value *operand_val = *constant_iter;
1962 llvm::Instruction *inst = *user_iter;
1963
1964 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1965
1966 if (operand_constant_fp)
1967 {
Sean Callanan1582ee62013-04-18 22:06:33 +00001968 Type *operand_type = operand_constant_fp->getType();
1969
Sean Callanan79763a42011-05-23 21:40:23 +00001970 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1971 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1972
1973 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1974 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1975
1976 if (log)
1977 {
1978 std::string s;
1979 raw_string_ostream ss(s);
1980 for (size_t index = 0;
1981 index < operand_data_size;
1982 ++index)
1983 {
1984 ss << (uint32_t)operand_raw_data[index];
1985 ss << " ";
1986 }
1987 ss.flush();
1988
Greg Clayton6fea17e2014-03-03 19:15:20 +00001989 log->Printf("Found ConstantFP with size %" PRIu64 " and raw data %s", (uint64_t)operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001990 }
1991
1992 lldb_private::DataBufferHeap data(operand_data_size, 0);
1993
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001994 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00001995 {
1996 uint8_t *data_bytes = data.GetBytes();
1997
1998 for (size_t index = 0;
1999 index < operand_data_size;
2000 ++index)
2001 {
2002 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2003 }
2004 }
2005 else
2006 {
2007 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2008 }
2009
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002010 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002011
Sean Callanane3333d62012-06-08 22:20:41 +00002012 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2013
2014 const size_t mask = (align - 1);
2015 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002016 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002017 offset = aligned_offset;
2018
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002019 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002020
Sean Callanancc427fa2011-07-30 02:42:06 +00002021 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002022
Sean Callanan1582ee62013-04-18 22:06:33 +00002023 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002024
2025 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2026
2027 operand_constant_fp->replaceAllUsesWith(fp_load);
2028 }
2029 }
2030
2031 return true;
2032}
2033
Sean Callanan7ea35012010-07-27 21:39:39 +00002034static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002035{
Sean Callanan77eaf442011-07-08 00:39:14 +00002036 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002037
Sean Callananafe16a72010-11-17 23:00:36 +00002038 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002039 return false;
2040
Sean Callanan77eaf442011-07-08 00:39:14 +00002041 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002042
2043 if ((CE = dyn_cast<ConstantExpr>(V)))
2044 {
2045 if (CE->getOpcode() != Instruction::BitCast)
2046 return false;
2047
Sean Callananafe16a72010-11-17 23:00:36 +00002048 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002049 }
2050
Sean Callananafe16a72010-11-17 23:00:36 +00002051 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002052
2053 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2054 return false;
2055
2056 return true;
2057}
2058
Sean Callanan79763a42011-05-23 21:40:23 +00002059void
2060IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002061{
Sean Callanan79763a42011-05-23 21:40:23 +00002062 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002063
Ed Maste80e8cc62014-03-10 14:23:10 +00002064 for (llvm::User *u : guard_load->users())
Sean Callananb27a62f2010-07-27 01:17:28 +00002065 {
Ed Maste80e8cc62014-03-10 14:23:10 +00002066 if (isa<Constant>(u))
Sean Callananb27a62f2010-07-27 01:17:28 +00002067 {
2068 // do nothing for the moment
2069 }
2070 else
2071 {
Ed Maste80e8cc62014-03-10 14:23:10 +00002072 u->replaceUsesOfWith(guard_load, zero);
Sean Callananb27a62f2010-07-27 01:17:28 +00002073 }
2074 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002075
2076 guard_load->eraseFromParent();
2077}
2078
2079static void ExciseGuardStore(Instruction* guard_store)
2080{
2081 guard_store->eraseFromParent();
2082}
2083
2084bool
Sean Callanan79763a42011-05-23 21:40:23 +00002085IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002086{
2087 ///////////////////////////////////////////////////////
2088 // Eliminate any reference to guard variables found.
2089 //
2090
Sean Callanan7ea35012010-07-27 21:39:39 +00002091 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002092
Sean Callanan7ea35012010-07-27 21:39:39 +00002093 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002094 typedef InstrList::iterator InstrIterator;
2095
2096 InstrList guard_loads;
2097 InstrList guard_stores;
2098
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002099 for (ii = basic_block.begin();
2100 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002101 ++ii)
2102 {
2103 Instruction &inst = *ii;
2104
2105 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2106 if (isGuardVariableRef(load->getPointerOperand()))
2107 guard_loads.push_back(&inst);
2108
2109 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2110 if (isGuardVariableRef(store->getPointerOperand()))
2111 guard_stores.push_back(&inst);
2112 }
2113
2114 InstrIterator iter;
2115
2116 for (iter = guard_loads.begin();
2117 iter != guard_loads.end();
2118 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002119 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002120
2121 for (iter = guard_stores.begin();
2122 iter != guard_stores.end();
2123 ++iter)
2124 ExciseGuardStore(*iter);
2125
2126 return true;
2127}
2128
Sean Callanan3989fb92011-01-27 01:07:04 +00002129// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002130bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002131IRForTarget::UnfoldConstant(Constant *old_constant,
2132 FunctionValueCache &value_maker,
2133 FunctionValueCache &entry_instruction_finder)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002134{
Greg Clayton5160ce52013-03-27 23:08:40 +00002135 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002136
Sean Callanan2235f322010-08-11 03:57:18 +00002137 SmallVector<User*, 16> users;
2138
2139 // We do this because the use list might change, invalidating our iterator.
2140 // Much better to keep a work list ourselves.
Ed Maste80e8cc62014-03-10 14:23:10 +00002141 for (llvm::User *u : old_constant->users())
2142 users.push_back(u);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002143
Johnny Chen44805302011-07-19 19:48:13 +00002144 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002145 i < users.size();
2146 ++i)
2147 {
2148 User *user = users[i];
2149
Sean Callanan7618f4e2010-07-14 23:40:29 +00002150 if (Constant *constant = dyn_cast<Constant>(user))
2151 {
2152 // synthesize a new non-constant equivalent of the constant
2153
2154 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2155 {
2156 switch (constant_expr->getOpcode())
2157 {
2158 default:
2159 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002160 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002161 return false;
2162 case Instruction::BitCast:
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002163 {
2164 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2165 // UnaryExpr
2166 // OperandList[0] is value
2167
2168 if (constant_expr->getOperand(0) != old_constant)
2169 return constant_expr;
2170
2171 return new BitCastInst(value_maker.GetValue(function),
2172 constant_expr->getType(),
2173 "",
2174 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2175 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002176
Sean Callanan0e016fe2013-07-15 23:31:47 +00002177 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2178 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002179 }
2180 break;
2181 case Instruction::GetElementPtr:
2182 {
2183 // GetElementPtrConstantExpr
2184 // OperandList[0] is base
2185 // OperandList[1]... are indices
2186
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002187 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2188 Value *ptr = constant_expr->getOperand(0);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002189
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002190 if (ptr == old_constant)
2191 ptr = value_maker.GetValue(function);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002192
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002193 std::vector<Value*> index_vector;
2194
2195 unsigned operand_index;
2196 unsigned num_operands = constant_expr->getNumOperands();
2197
2198 for (operand_index = 1;
2199 operand_index < num_operands;
2200 ++operand_index)
2201 {
2202 Value *operand = constant_expr->getOperand(operand_index);
2203
2204 if (operand == old_constant)
2205 operand = value_maker.GetValue(function);
2206
2207 index_vector.push_back(operand);
2208 }
2209
2210 ArrayRef <Value*> indices(index_vector);
2211
2212 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2213 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002214
Sean Callanan0e016fe2013-07-15 23:31:47 +00002215 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2216 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002217 }
2218 break;
2219 }
2220 }
2221 else
2222 {
2223 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002224 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002225 return false;
2226 }
2227 }
2228 else
2229 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002230 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2231 {
2232 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2233 }
2234 else
2235 {
2236 if (log)
2237 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2238 return false;
2239 }
Sean Callanan7618f4e2010-07-14 23:40:29 +00002240 }
2241 }
2242
Sean Callanan0e016fe2013-07-15 23:31:47 +00002243 if (!isa<GlobalValue>(old_constant))
2244 {
2245 old_constant->destroyConstant();
2246 }
2247
Sean Callanan7618f4e2010-07-14 23:40:29 +00002248 return true;
2249}
2250
Sean Callanan549c9f72010-07-13 21:41:46 +00002251bool
Sean Callanan79763a42011-05-23 21:40:23 +00002252IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002253{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002254 if (!m_resolve_vars)
2255 return true;
2256
Greg Clayton5160ce52013-03-27 23:08:40 +00002257 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002258
2259 m_decl_map->DoStructLayout();
2260
2261 if (log)
2262 log->Printf("Element arrangement:");
2263
2264 uint32_t num_elements;
2265 uint32_t element_index;
2266
2267 size_t size;
2268 off_t alignment;
2269
2270 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2271 return false;
2272
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002273 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002274
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002275 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002276 {
2277 if (m_error_stream)
2278 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2279
Sean Callanan549c9f72010-07-13 21:41:46 +00002280 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002281 }
2282
Sean Callanan7ea35012010-07-27 21:39:39 +00002283 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002284
Sean Callananfc55f5d2010-09-21 00:44:12 +00002285 if (argument->getName().equals("this"))
2286 {
2287 ++iter;
2288
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002289 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002290 {
2291 if (m_error_stream)
2292 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2293
Sean Callananfc55f5d2010-09-21 00:44:12 +00002294 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002295 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002296
2297 argument = iter;
2298 }
Sean Callanan17827832010-12-13 22:46:15 +00002299 else if (argument->getName().equals("self"))
2300 {
2301 ++iter;
2302
2303 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002304 {
2305 if (m_error_stream)
2306 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2307
Sean Callanan17827832010-12-13 22:46:15 +00002308 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002309 }
Sean Callanan17827832010-12-13 22:46:15 +00002310
2311 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002312 {
2313 if (m_error_stream)
2314 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2315
Sean Callanan17827832010-12-13 22:46:15 +00002316 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002317 }
Sean Callanan17827832010-12-13 22:46:15 +00002318
2319 ++iter;
2320
2321 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002322 {
2323 if (m_error_stream)
2324 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2325
Sean Callanan17827832010-12-13 22:46:15 +00002326 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002327 }
Sean Callanan17827832010-12-13 22:46:15 +00002328
2329 argument = iter;
2330 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002331
Greg Clayton7b462cc2010-10-15 22:48:33 +00002332 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002333 {
2334 if (m_error_stream)
2335 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2336
Sean Callanan549c9f72010-07-13 21:41:46 +00002337 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002338 }
2339
Sean Callanan549c9f72010-07-13 21:41:46 +00002340 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002341 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002342
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002343 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002344 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002345
Sean Callananafe16a72010-11-17 23:00:36 +00002346 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002347 {
2348 if (m_error_stream)
2349 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2350
Sean Callanan549c9f72010-07-13 21:41:46 +00002351 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002352 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002353
Sean Callanan79763a42011-05-23 21:40:23 +00002354 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002355 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002356
2357 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002358 {
2359 if (m_error_stream)
2360 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2361
Sean Callanan549c9f72010-07-13 21:41:46 +00002362 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002363 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002364
2365 for (element_index = 0; element_index < num_elements; ++element_index)
2366 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002367 const clang::NamedDecl *decl = NULL;
2368 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002369 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002370 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002371
Sean Callanan823bb4c2010-08-30 22:17:16 +00002372 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002373 {
2374 if (m_error_stream)
2375 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2376
Sean Callanan549c9f72010-07-13 21:41:46 +00002377 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002378 }
2379
Sean Callanan549c9f72010-07-13 21:41:46 +00002380 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002381 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002382 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002383 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002384 offset);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002385
Sean Callananc70ed462011-10-25 18:36:40 +00002386 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002387 {
Sean Callananc70ed462011-10-25 18:36:40 +00002388 if (log)
2389 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002390
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002391 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2392 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2393 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2394 // entry in order to produce the static variable that the AST thinks it is accessing.
Sean Callananc70ed462011-10-25 18:36:40 +00002395
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002396 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
Sean Callananc70ed462011-10-25 18:36:40 +00002397
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002398 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2399 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2400 offset_int,
2401 "",
2402 entry_instruction);
2403
2404 if (name == m_result_name && !m_result_is_pointer)
2405 {
2406 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2407 value->getType()->getPointerTo(),
2408 "",
2409 entry_instruction);
2410
2411 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2412
2413 return load;
2414 }
2415 else
2416 {
2417 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2418
2419 return bit_cast;
2420 }
2421 });
Sean Callananc70ed462011-10-25 18:36:40 +00002422
2423 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002424 {
2425 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2426 }
2427 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2428 {
2429 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2430 }
Sean Callananc70ed462011-10-25 18:36:40 +00002431 else
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002432 {
2433 if (log)
2434 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2435 return false;
2436 }
Sean Callananc70ed462011-10-25 18:36:40 +00002437
2438 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2439 var->eraseFromParent();
2440 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002441 }
2442
2443 if (log)
Greg Clayton6fea17e2014-03-03 19:15:20 +00002444 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002445
2446 return true;
2447}
2448
Sean Callanan79763a42011-05-23 21:40:23 +00002449llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002450IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002451{
Sean Callanan439dcae2013-12-20 19:55:02 +00002452 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002453
2454 llvm::Constant *offset_array[1];
2455
2456 offset_array[0] = offset_int;
2457
2458 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2459
2460 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002461 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2462
2463 return reloc_getbitcast;
2464}
2465
2466bool
2467IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002468{
Greg Clayton5160ce52013-03-27 23:08:40 +00002469 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002470
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002471 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002472 return true;
2473
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002474 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002475
2476 if (log)
2477 {
2478 if (allocation)
2479 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2480 else
2481 log->Printf("Failed to allocate static data");
2482 }
2483
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002484 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002485 return false;
2486
Sean Callanan439dcae2013-12-20 19:55:02 +00002487 Constant *relocated_addr = ConstantInt::get(m_intptr_ty, (uint64_t)allocation);
Sean Callanan79763a42011-05-23 21:40:23 +00002488 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2489
2490 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2491
2492 m_reloc_placeholder->eraseFromParent();
2493
2494 return true;
2495}
2496
Sean Callanan2ab712f22010-07-03 01:35:46 +00002497bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002498IRForTarget::StripAllGVs (Module &llvm_module)
2499{
Greg Clayton5160ce52013-03-27 23:08:40 +00002500 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002501 std::vector<GlobalVariable *> global_vars;
2502 std::set<GlobalVariable *>erased_vars;
2503
2504 bool erased = true;
2505
2506 while (erased)
2507 {
2508 erased = false;
2509
Sean Callanan339f6152014-03-11 19:19:16 +00002510 for (GlobalVariable &global_var : llvm_module.globals())
Sean Callanan3d654b32012-09-24 22:25:51 +00002511 {
Sean Callanan339f6152014-03-11 19:19:16 +00002512 global_var.removeDeadConstantUsers();
Sean Callanan3d654b32012-09-24 22:25:51 +00002513
Sean Callanan339f6152014-03-11 19:19:16 +00002514 if (global_var.use_empty())
Sean Callanan3d654b32012-09-24 22:25:51 +00002515 {
2516 if (log)
2517 log->Printf("Did remove %s",
Sean Callanan339f6152014-03-11 19:19:16 +00002518 PrintValue(&global_var).c_str());
2519 global_var.eraseFromParent();
Sean Callanan3d654b32012-09-24 22:25:51 +00002520 erased = true;
2521 break;
2522 }
2523 }
2524 }
2525
Sean Callanan339f6152014-03-11 19:19:16 +00002526 for (GlobalVariable &global_var : llvm_module.globals())
Sean Callanan3d654b32012-09-24 22:25:51 +00002527 {
Sean Callanan339f6152014-03-11 19:19:16 +00002528 GlobalValue::user_iterator ui = global_var.user_begin();
Sean Callanan3d654b32012-09-24 22:25:51 +00002529
Jim Inghamd77557d2012-11-26 19:54:04 +00002530 if (log)
2531 log->Printf("Couldn't remove %s because of %s",
Sean Callanan339f6152014-03-11 19:19:16 +00002532 PrintValue(&global_var).c_str(),
Jim Inghamd77557d2012-11-26 19:54:04 +00002533 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002534 }
2535
2536 return true;
2537}
2538
2539bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002540IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002541{
Greg Clayton5160ce52013-03-27 23:08:40 +00002542 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002543
Sean Callanan79763a42011-05-23 21:40:23 +00002544 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002545 m_target_data.reset(new DataLayout(m_module));
Sean Callanan439dcae2013-12-20 19:55:02 +00002546 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits());
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002547
Sean Callananc70ed462011-10-25 18:36:40 +00002548 if (log)
2549 {
2550 std::string s;
2551 raw_string_ostream oss(s);
2552
2553 m_module->print(oss, NULL);
2554
2555 oss.flush();
2556
2557 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2558 }
2559
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002560 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2561
2562 if (!main_function)
2563 {
2564 if (log)
2565 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2566
2567 if (m_error_stream)
2568 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2569
2570 return false;
2571 }
2572
2573 if (!FixFunctionLinkage (*main_function))
2574 {
2575 if (log)
2576 log->Printf("Couldn't fix the linkage for the function");
2577
2578 return false;
2579 }
2580
Sean Callanan439dcae2013-12-20 19:55:02 +00002581 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002582
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002583 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
Sean Callanan439dcae2013-12-20 19:55:02 +00002584 int8_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002585 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002586 GlobalVariable::InternalLinkage,
Sean Callanan439dcae2013-12-20 19:55:02 +00002587 Constant::getNullValue(int8_ty),
Sean Callanan79763a42011-05-23 21:40:23 +00002588 "reloc_placeholder",
2589 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002590 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002591 0 /* AddressSpace */);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002592
Sean Callanand1e5b432010-08-12 01:56:52 +00002593 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002594 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002595 //
2596
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002597 if (!CreateResultVariable(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002598 {
2599 if (log)
2600 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002601
2602 // CreateResultVariable() reports its own errors, so we don't do so here
2603
Sean Callanand1e5b432010-08-12 01:56:52 +00002604 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002605 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002606
Sean Callananea685ae2011-11-01 17:33:54 +00002607 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002608 {
2609 std::string s;
2610 raw_string_ostream oss(s);
2611
2612 m_module->print(oss, NULL);
2613
2614 oss.flush();
2615
2616 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2617 }
2618
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002619 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2620 fi != fe;
2621 ++fi)
2622 {
2623 llvm::Function *function = fi;
2624
2625 if (function->begin() == function->end())
2626 continue;
2627
2628 Function::iterator bbi;
2629
2630 for (bbi = function->begin();
2631 bbi != function->end();
2632 ++bbi)
2633 {
2634 if (!RemoveGuards(*bbi))
2635 {
2636 if (log)
2637 log->Printf("RemoveGuards() failed");
2638
2639 // RemoveGuards() reports its own errors, so we don't do so here
2640
2641 return false;
2642 }
2643
2644 if (!RewritePersistentAllocs(*bbi))
2645 {
2646 if (log)
2647 log->Printf("RewritePersistentAllocs() failed");
2648
2649 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2650
2651 return false;
2652 }
2653
2654 if (!RemoveCXAAtExit(*bbi))
2655 {
2656 if (log)
2657 log->Printf("RemoveCXAAtExit() failed");
2658
2659 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2660
2661 return false;
2662 }
2663 }
2664 }
2665
Sean Callananafe16a72010-11-17 23:00:36 +00002666 ///////////////////////////////////////////////////////////////////////////////
2667 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2668 //
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002669
2670 if (!RewriteObjCConstStrings())
Sean Callanan17827832010-12-13 22:46:15 +00002671 {
2672 if (log)
2673 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002674
2675 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2676
Sean Callananafe16a72010-11-17 23:00:36 +00002677 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002678 }
Sean Callananafe16a72010-11-17 23:00:36 +00002679
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002680 ///////////////////////////////
2681 // Resolve function pointers
2682 //
2683
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002684 if (!ResolveFunctionPointers(llvm_module))
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002685 {
2686 if (log)
2687 log->Printf("ResolveFunctionPointers() failed");
2688
2689 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2690
2691 return false;
2692 }
2693
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002694 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2695 fi != fe;
2696 ++fi)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002697 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002698 llvm::Function *function = fi;
2699
2700 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2701 bbi != bbe;
2702 ++bbi)
Sean Callanan17827832010-12-13 22:46:15 +00002703 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002704 if (!RewriteObjCSelectors(*bbi))
2705 {
2706 if (log)
2707 log->Printf("RewriteObjCSelectors() failed");
2708
2709 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2710
2711 return false;
2712 }
Sean Callanan17827832010-12-13 22:46:15 +00002713 }
Sean Callananbad134f2012-07-27 19:25:24 +00002714 }
Sean Callanan2235f322010-08-11 03:57:18 +00002715
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002716 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2717 fi != fe;
2718 ++fi)
Sean Callananbad134f2012-07-27 19:25:24 +00002719 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002720 llvm::Function *function = fi;
Sean Callanan79763a42011-05-23 21:40:23 +00002721
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002722 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2723 bbi != bbe;
2724 ++bbi)
Sean Callanan79763a42011-05-23 21:40:23 +00002725 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002726 if (!ResolveCalls(*bbi))
2727 {
2728 if (log)
2729 log->Printf("ResolveCalls() failed");
2730
2731 // ResolveCalls() reports its own errors, so we don't do so here
2732
2733 return false;
2734 }
Sean Callanan79763a42011-05-23 21:40:23 +00002735
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002736 if (!ReplaceStaticLiterals(*bbi))
2737 {
2738 if (log)
2739 log->Printf("ReplaceStaticLiterals() failed");
2740
2741 return false;
2742 }
Sean Callanan79763a42011-05-23 21:40:23 +00002743 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002744 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002745
2746 ////////////////////////////////////////////////////////////////////////
2747 // Run function-level passes that only make sense on the main function
Sean Callanan038df5032010-09-30 21:18:25 +00002748 //
2749
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002750 if (!ResolveExternals(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002751 {
2752 if (log)
2753 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002754
2755 // ResolveExternals() reports its own errors, so we don't do so here
2756
Sean Callanana4e55172010-11-08 00:31:32 +00002757 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002758 }
Sean Callanana4e55172010-11-08 00:31:32 +00002759
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002760 if (!ReplaceVariables(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002761 {
2762 if (log)
2763 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002764
2765 // ReplaceVariables() reports its own errors, so we don't do so here
2766
Sean Callanan038df5032010-09-30 21:18:25 +00002767 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002768 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002769
Sean Callanan79763a42011-05-23 21:40:23 +00002770 if (!ReplaceStrings())
2771 {
2772 if (log)
2773 log->Printf("ReplaceStrings() failed");
2774
2775 return false;
2776 }
2777
2778 if (!CompleteDataAllocation())
2779 {
2780 if (log)
2781 log->Printf("CompleteDataAllocation() failed");
2782
2783 return false;
2784 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002785
Sean Callanan3d654b32012-09-24 22:25:51 +00002786 if (!StripAllGVs(llvm_module))
2787 {
2788 if (log)
2789 log->Printf("StripAllGVs() failed");
2790 }
2791
Sean Callananea685ae2011-11-01 17:33:54 +00002792 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002793 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002794 std::string s;
2795 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002796
Sean Callanan79763a42011-05-23 21:40:23 +00002797 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002798
2799 oss.flush();
2800
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002801 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002802 }
2803
2804 return true;
2805}
2806
2807void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002808IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002809{
2810}
2811
2812PassManagerType
2813IRForTarget::getPotentialPassManagerType() const
2814{
2815 return PMT_ModulePassManager;
2816}