blob: e9101d6f74a88189fe7191f614eb9e249d280f35 [file] [log] [blame]
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan2ab712f22010-07-03 01:35:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000013#include "llvm/IR/Constants.h"
14#include "llvm/IR/DataLayout.h"
15#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/Module.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000019#include "llvm/PassManager.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000020#include "llvm/Transforms/IPO.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000021#include "llvm/IR/ValueSymbolTable.h"
Sean Callanan549c9f72010-07-13 21:41:46 +000022
23#include "clang/AST/ASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000024
25#include "lldb/Core/dwarf.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000026#include "lldb/Core/ConstString.h"
27#include "lldb/Core/DataBufferHeap.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/Scalar.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000032#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000033#include "lldb/Expression/IRInterpreter.h"
Sean Callanan79763a42011-05-23 21:40:23 +000034#include "lldb/Host/Endian.h"
Sean Callanan63697e52011-05-07 01:06:41 +000035#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000036
37#include <map>
38
39using namespace llvm;
40
Sean Callananeaacbc92010-08-18 18:50:51 +000041static char ID;
42
Sean Callanan8dfb68e2013-03-19 00:10:07 +000043IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
44 m_execution_unit(execution_unit),
Sean Callanan1582ee62013-04-18 22:06:33 +000045 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000046 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000047{
48}
49
Sean Callanan8dfb68e2013-03-19 00:10:07 +000050lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000051{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000052 lldb_private::Error err;
53
54 if (m_allocation != LLDB_INVALID_ADDRESS)
55 {
56 m_execution_unit.FreeNow(m_allocation);
57 m_allocation = LLDB_INVALID_ADDRESS;
58 }
59
60 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
61
62 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000063}
64
Greg Clayton1b95a6f2010-11-19 01:05:25 +000065IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
66 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000067 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000068 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000069 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +000070 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +000071 m_resolve_vars(resolve_vars),
72 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +000073 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +000074 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000075 m_data_allocator(execution_unit),
Sean Callanan179b5482013-04-16 23:49:09 +000076 m_memory_map(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +000077 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +000078 m_sel_registerName(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +000079 m_error_stream(error_stream),
Sean Callanan92adcac2011-01-13 08:53:35 +000080 m_has_side_effects(false),
Sean Callanan63697e52011-05-07 01:06:41 +000081 m_result_store(NULL),
82 m_result_is_pointer(false),
Sean Callanan79763a42011-05-23 21:40:23 +000083 m_reloc_placeholder(NULL)
Sean Callanan2ab712f22010-07-03 01:35:46 +000084{
85}
86
Sean Callanan038df5032010-09-30 21:18:25 +000087/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +000088
89static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +000090PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +000091{
92 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +000093 if (value)
94 {
95 raw_string_ostream rso(s);
96 value->print(rso);
97 rso.flush();
98 if (truncate)
99 s.resize(s.length() - 1);
100 }
Sean Callanan2235f322010-08-11 03:57:18 +0000101 return s;
102}
103
Sean Callanan038df5032010-09-30 21:18:25 +0000104static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000105PrintType(const Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000106{
107 std::string s;
108 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000109 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000110 rso.flush();
111 if (truncate)
112 s.resize(s.length() - 1);
113 return s;
114}
115
Sean Callanan2ab712f22010-07-03 01:35:46 +0000116IRForTarget::~IRForTarget()
117{
118}
119
Sean Callanan79763a42011-05-23 21:40:23 +0000120bool
121IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
122{
Sean Callanan79763a42011-05-23 21:40:23 +0000123 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
124
Sean Callanan7f27d602011-11-19 02:54:21 +0000125 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000126
127 return true;
128}
129
Sean Callanand1e5b432010-08-12 01:56:52 +0000130bool
Sean Callanan79763a42011-05-23 21:40:23 +0000131IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000132{
133 llvm::Function::iterator bbi;
134 BasicBlock::iterator ii;
Sean Callanan63697e52011-05-07 01:06:41 +0000135
Sean Callanane4ec90e2010-12-16 03:17:46 +0000136 for (bbi = llvm_function.begin();
137 bbi != llvm_function.end();
138 ++bbi)
139 {
140 BasicBlock &basic_block = *bbi;
141
142 for (ii = basic_block.begin();
143 ii != basic_block.end();
144 ++ii)
145 {
146 switch (ii->getOpcode())
147 {
148 default:
149 return true;
150 case Instruction::Store:
151 {
152 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
153
154 Value *store_ptr = store_inst->getPointerOperand();
155
Sean Callanan63697e52011-05-07 01:06:41 +0000156 std::string ptr_name;
157
158 if (store_ptr->hasName())
Sean Callanan7f27d602011-11-19 02:54:21 +0000159 ptr_name = store_ptr->getName().str();
Sean Callanan63697e52011-05-07 01:06:41 +0000160
161 if (isa <AllocaInst> (store_ptr))
Sean Callanane4ec90e2010-12-16 03:17:46 +0000162 break;
Sean Callanan63697e52011-05-07 01:06:41 +0000163
164 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
165 {
166 if (ptr_name.find("GV") == std::string::npos)
167 m_result_store = store_inst;
168 }
169 else
170 {
171 return true;
172 }
173
174 break;
Sean Callanane4ec90e2010-12-16 03:17:46 +0000175 }
176 case Instruction::Load:
177 case Instruction::Alloca:
178 case Instruction::GetElementPtr:
Sean Callanan63697e52011-05-07 01:06:41 +0000179 case Instruction::BitCast:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000180 case Instruction::Ret:
Sean Callanan63697e52011-05-07 01:06:41 +0000181 case Instruction::ICmp:
182 case Instruction::Br:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000183 break;
184 }
185 }
186 }
187
188 return false;
189}
190
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000191bool
192IRForTarget::GetFunctionAddress (llvm::Function *fun,
193 uint64_t &fun_addr,
194 lldb_private::ConstString &name,
195 Constant **&value_ptr)
196{
Greg Clayton5160ce52013-03-27 23:08:40 +0000197 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000198
199 fun_addr = LLDB_INVALID_ADDRESS;
200 name.Clear();
201 value_ptr = NULL;
202
203 if (fun->isIntrinsic())
204 {
205 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
206
207 switch (intrinsic_id)
208 {
209 default:
210 if (log)
211 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
212
213 if (m_error_stream)
214 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
215
216 return false;
217 case Intrinsic::memcpy:
218 {
219 static lldb_private::ConstString g_memcpy_str ("memcpy");
220 name = g_memcpy_str;
221 }
222 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000223 case Intrinsic::memset:
224 {
225 static lldb_private::ConstString g_memset_str ("memset");
226 name = g_memset_str;
227 }
228 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000229 }
230
231 if (log && name)
232 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
233 }
234 else
235 {
236 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
237 }
238
239 // Find the address of the function.
240
241 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000242
243 if (fun_decl)
244 {
Sean Callananc70ed462011-10-25 18:36:40 +0000245 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000246 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000247 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000248 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
249 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000250 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000251 // Check for an alternate mangling for "std::basic_string<char>"
252 // that is part of the itanium C++ name mangling scheme
253 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000254 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000255 {
256 std::string alternate_mangling("_ZNKSs");
257 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000258 altnernate_name.SetCString(alternate_mangling.c_str());
259 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000260 }
261 }
262
263 if (!found_it)
264 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000265 lldb_private::Mangled mangled_name(name);
266 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000267 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000268 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000269 if (alt_mangled_name)
270 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
271 mangled_name.GetName().GetCString(),
272 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000273 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000274 log->Printf("Function \"%s\" had no address",
275 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000276 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000277
278 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000279 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000280 if (alt_mangled_name)
281 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
282 mangled_name.GetName().GetCString(),
283 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000284 else if (mangled_name.GetMangledName())
285 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
286 mangled_name.GetName().GetCString(),
287 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000288 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000289 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
290 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000291 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000292 return false;
293 }
294 }
295 }
296 else
297 {
298 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
299 {
300 if (log)
301 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
302
303 if (m_error_stream)
304 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
305
306 return false;
307 }
308 }
309
310 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000311 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000312
313 return true;
314}
315
316llvm::Constant *
317IRForTarget::BuildFunctionPointer (llvm::Type *type,
318 uint64_t ptr)
319{
320 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000321 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000322 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
323 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
324 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
325}
326
Sean Callananfc8feb82011-10-31 22:11:40 +0000327void
328IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
329 llvm::Value *function_ptr,
330 const char *name)
331{
Sean Callananfc8feb82011-10-31 22:11:40 +0000332 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
333 i != e;
334 ++i)
335 {
336 Value *user = *i;
337
338 if (Instruction *user_inst = dyn_cast<Instruction>(user))
339 {
Sean Callanand2b465f2012-02-09 03:22:41 +0000340 Constant *name_array = ConstantDataArray::getString(context, StringRef(name));
Sean Callananfc8feb82011-10-31 22:11:40 +0000341
342 ArrayRef<Value *> md_values(name_array);
343
344 MDNode *metadata = MDNode::get(context, md_values);
345
346 user_inst->setMetadata("lldb.call.realName", metadata);
347 }
348 else
349 {
350 RegisterFunctionMetadata (context, user, name);
351 }
352 }
353}
354
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000355bool
356IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
357 llvm::Function &llvm_function)
358{
Greg Clayton5160ce52013-03-27 23:08:40 +0000359 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000360
361 for (llvm::Module::iterator fi = llvm_module.begin();
362 fi != llvm_module.end();
363 ++fi)
364 {
365 Function *fun = fi;
366
367 bool is_decl = fun->isDeclaration();
368
369 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000370 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000371
372 if (!is_decl)
373 continue;
374
375 if (fun->hasNUses(0))
376 continue; // ignore
377
378 uint64_t addr = LLDB_INVALID_ADDRESS;
379 lldb_private::ConstString name;
380 Constant **value_ptr = NULL;
381
382 if (!GetFunctionAddress(fun,
383 addr,
384 name,
385 value_ptr))
386 return false; // GetFunctionAddress reports its own errors
387
388 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
389
Sean Callananfc8feb82011-10-31 22:11:40 +0000390 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
391
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000392 if (value_ptr)
393 *value_ptr = value;
394
395 fun->replaceAllUsesWith(value);
396 }
397
398 return true;
399}
400
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000401
Sean Callanan63697e52011-05-07 01:06:41 +0000402clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000403IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000404{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000405 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000406
407 if (!named_metadata)
408 return NULL;
409
410 unsigned num_nodes = named_metadata->getNumOperands();
411 unsigned node_index;
412
413 for (node_index = 0;
414 node_index < num_nodes;
415 ++node_index)
416 {
417 MDNode *metadata_node = named_metadata->getOperand(node_index);
418
419 if (!metadata_node)
420 return NULL;
421
422 if (metadata_node->getNumOperands() != 2)
423 continue;
424
425 if (metadata_node->getOperand(0) != global_val)
426 continue;
427
428 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
429
430 if (!constant_int)
431 return NULL;
432
433 uintptr_t ptr = constant_int->getZExtValue();
434
435 return reinterpret_cast<clang::NamedDecl *>(ptr);
436 }
437
438 return NULL;
439}
440
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000441clang::NamedDecl *
442IRForTarget::DeclForGlobal (GlobalValue *global_val)
443{
444 return DeclForGlobal(global_val, m_module);
445}
446
Sean Callanane4ec90e2010-12-16 03:17:46 +0000447bool
Sean Callanan79763a42011-05-23 21:40:23 +0000448IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000449{
Greg Clayton5160ce52013-03-27 23:08:40 +0000450 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000451
Sean Callanan9e6ed532010-09-13 21:34:21 +0000452 if (!m_resolve_vars)
453 return true;
454
455 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000456
Sean Callanan79763a42011-05-23 21:40:23 +0000457 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000458
Sean Callanancc427fa2011-07-30 02:42:06 +0000459 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000460 const char *result_name = NULL;
461
462 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
463 vi != ve;
464 ++vi)
465 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000466 result_name_str = vi->first().str();
467 const char *value_name = result_name_str.c_str();
468
469 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000470 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000471 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000472 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000473 m_result_is_pointer = true;
474 break;
475 }
476
Sean Callanancc427fa2011-07-30 02:42:06 +0000477 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000478 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000479 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000480 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000481 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000482 break;
483 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000484 }
485
486 if (!result_name)
487 {
488 if (log)
489 log->PutCString("Couldn't find result variable");
490
491 return true;
492 }
493
Sean Callanan46ae9e52010-09-28 21:13:03 +0000494 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000495 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000496
Sean Callanan79763a42011-05-23 21:40:23 +0000497 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000498
499 if (!result_value)
500 {
501 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000502 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000503
Sean Callanan3989fb92011-01-27 01:07:04 +0000504 if (m_error_stream)
505 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
506
Sean Callananfc55f5d2010-09-21 00:44:12 +0000507 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000508 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000509
Sean Callanand1e5b432010-08-12 01:56:52 +0000510 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000511 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000512
513 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
514
515 if (!result_global)
516 {
517 if (log)
518 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000519
520 if (m_error_stream)
521 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
522
Sean Callanand1e5b432010-08-12 01:56:52 +0000523 return false;
524 }
525
Sean Callanan79763a42011-05-23 21:40:23 +0000526 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000527 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000528 {
529 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000530 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000531
Sean Callanan3989fb92011-01-27 01:07:04 +0000532 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000533 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
Sean Callanan3989fb92011-01-27 01:07:04 +0000534
Sean Callanand1e5b432010-08-12 01:56:52 +0000535 return false;
536 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000537
Sean Callanan63697e52011-05-07 01:06:41 +0000538 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000539 {
Sean Callanan63697e52011-05-07 01:06:41 +0000540 std::string decl_desc_str;
541 raw_string_ostream decl_desc_stream(decl_desc_str);
542 result_decl->print(decl_desc_stream);
543 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000544
Sean Callanan63697e52011-05-07 01:06:41 +0000545 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000546 }
547
Sean Callanan63697e52011-05-07 01:06:41 +0000548 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
549 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000550 {
551 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000552 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000553
554 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000555 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
Sean Callanan3989fb92011-01-27 01:07:04 +0000556
Sean Callanand1e5b432010-08-12 01:56:52 +0000557 return false;
558 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000559
Sean Callanand1e5b432010-08-12 01:56:52 +0000560 // Get the next available result name from m_decl_map and create the persistent
561 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000562
Sean Callanan63697e52011-05-07 01:06:41 +0000563 // If the result is an Lvalue, it is emitted as a pointer; see
564 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000565 if (m_result_is_pointer)
566 {
Sean Callanan63697e52011-05-07 01:06:41 +0000567 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000568 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000569
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000570 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
571 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000572
573 if (pointer_pointertype)
574 {
575 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
576
577 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
578 &result_decl->getASTContext());
579 }
580 else if (pointer_objcobjpointertype)
581 {
582 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
583
584 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
585 &result_decl->getASTContext());
586 }
587 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000588 {
589 if (log)
590 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000591
592 if (m_error_stream)
593 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
594
Sean Callanan92adcac2011-01-13 08:53:35 +0000595 return false;
596 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000597 }
598 else
599 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000600 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000601 &result_decl->getASTContext());
602 }
603
604 if (m_result_type.GetClangTypeBitWidth() == 0)
605 {
606 lldb_private::StreamString type_desc_stream;
607 m_result_type.DumpTypeDescription(&type_desc_stream);
608
609 if (log)
610 log->Printf("Result type has size 0");
611
612 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000613 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000614 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000615 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000616 }
617
Sean Callanan63697e52011-05-07 01:06:41 +0000618 if (log)
619 {
620 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000621 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000622
Sean Callanan00f43622011-11-18 03:28:09 +0000623 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000624 }
625
Sean Callanan1582ee62013-04-18 22:06:33 +0000626 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000627
628 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000629 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000630 m_result_name.GetCString(),
631 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanand1e5b432010-08-12 01:56:52 +0000632
633 // Construct a new result global and set up its metadata
634
Sean Callanan79763a42011-05-23 21:40:23 +0000635 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000636 result_global->getType()->getElementType(),
637 false, /* not constant */
638 GlobalValue::ExternalLinkage,
639 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000640 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000641
642 // It's too late in compilation to create a new VarDecl for this, but we don't
643 // need to. We point the metadata at the old VarDecl. This creates an odd
644 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000645 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000646 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
647 // fixed up.
648
Sean Callanan79763a42011-05-23 21:40:23 +0000649 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000650 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000651 false);
652
653 llvm::Value* values[2];
654 values[0] = new_result_global;
655 values[1] = new_constant_int;
656
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000657 ArrayRef<Value*> value_ref(values, 2);
658
Sean Callanan79763a42011-05-23 21:40:23 +0000659 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
660 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000661 named_metadata->addOperand(persistent_global_md);
662
663 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000664 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000665 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000666 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000667
668 if (result_global->hasNUses(0))
669 {
670 // We need to synthesize a store for this variable, because otherwise
671 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000672
Greg Clayton7b462cc2010-10-15 22:48:33 +0000673 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000674 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
675
676 if (!first_entry_instruction)
677 return false;
678
679 if (!result_global->hasInitializer())
680 {
681 if (log)
682 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000683
684 if (m_error_stream)
685 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
686
Sean Callanan1e87fff2010-09-07 22:43:19 +0000687 return false;
688 }
689
690 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000691
692 // Here we write the initializer into a result variable assuming it
693 // can be computed statically.
694
695 if (!m_has_side_effects)
696 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000697 //MaybeSetConstantResult (initializer,
698 // m_result_name,
699 // m_result_type);
Sean Callanane4ec90e2010-12-16 03:17:46 +0000700 }
Sean Callanan1e87fff2010-09-07 22:43:19 +0000701
Greg Clayton9c139312011-02-05 02:28:58 +0000702 StoreInst *synthesized_store = new StoreInst(initializer,
703 new_result_global,
704 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000705
706 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000707 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000708 }
709 else
710 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000711 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan63697e52011-05-07 01:06:41 +0000712 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000713 //MaybeSetCastResult (m_result_type);
Sean Callanan63697e52011-05-07 01:06:41 +0000714 }
715
Sean Callanan1e87fff2010-09-07 22:43:19 +0000716 result_global->replaceAllUsesWith(new_result_global);
717 }
718
Sean Callanan1582ee62013-04-18 22:06:33 +0000719 if (!m_decl_map->AddPersistentVariable(result_decl,
720 m_result_name,
721 m_result_type,
722 true,
723 m_result_is_pointer))
724 return false;
725
Sean Callanand1e5b432010-08-12 01:56:52 +0000726 result_global->eraseFromParent();
727
728 return true;
729}
730
Johnny Chenee7a3592011-08-09 23:10:20 +0000731#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000732static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000733{
734 if (!depth)
735 return;
736
737 depth--;
738
Johnny Chenee7a3592011-08-09 23:10:20 +0000739 if (log)
740 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000741
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000742 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000743 ui != ue;
744 ++ui)
745 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000746 if (log)
747 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000748 DebugUsers(log, *ui, depth);
749 }
750
Johnny Chenee7a3592011-08-09 23:10:20 +0000751 if (log)
752 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000753}
Johnny Chenee7a3592011-08-09 23:10:20 +0000754#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000755
756bool
Sean Callanan79763a42011-05-23 21:40:23 +0000757IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000758 llvm::GlobalVariable *cstr,
759 Instruction *FirstEntryInstruction)
Sean Callananafe16a72010-11-17 23:00:36 +0000760{
Greg Clayton5160ce52013-03-27 23:08:40 +0000761 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000762
Sean Callanancc427fa2011-07-30 02:42:06 +0000763 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000764
Sean Callanancc427fa2011-07-30 02:42:06 +0000765 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
766 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000767 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +0000768 == Module::Pointer64) ? 64 : 32);
Sean Callanancc427fa2011-07-30 02:42:06 +0000769 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
770 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000771
772 if (!m_CFStringCreateWithBytes)
773 {
774 lldb::addr_t CFStringCreateWithBytes_addr;
775
776 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
777
778 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
779 {
780 if (log)
781 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
782
Sean Callanan3989fb92011-01-27 01:07:04 +0000783 if (m_error_stream)
784 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
785
Sean Callananafe16a72010-11-17 23:00:36 +0000786 return false;
787 }
788
789 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000790 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000791
792 // Build the function type:
793 //
794 // CFStringRef CFStringCreateWithBytes (
795 // CFAllocatorRef alloc,
796 // const UInt8 *bytes,
797 // CFIndex numBytes,
798 // CFStringEncoding encoding,
799 // Boolean isExternalRepresentation
800 // );
801 //
802 // We make the following substitutions:
803 //
804 // CFStringRef -> i8*
805 // CFAllocatorRef -> i8*
806 // UInt8 * -> i8*
807 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
808 // CFStringEncoding -> i32
809 // Boolean -> i8
810
Sean Callanancc427fa2011-07-30 02:42:06 +0000811 Type *arg_type_array[5];
812
813 arg_type_array[0] = i8_ptr_ty;
814 arg_type_array[1] = i8_ptr_ty;
815 arg_type_array[2] = intptr_ty;
816 arg_type_array[3] = i32_ty;
817 arg_type_array[4] = i8_ty;
818
819 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
820
Sean Callanan79763a42011-05-23 21:40:23 +0000821 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000822
823 // Build the constant containing the pointer to the function
824 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
825 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
826 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
827 }
828
Sean Callanand2b465f2012-02-09 03:22:41 +0000829 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000830
831 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000832 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000833
Sean Callananafe16a72010-11-17 23:00:36 +0000834 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000835 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000836 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000837 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
838 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
839
Sean Callanancc427fa2011-07-30 02:42:06 +0000840 Value *argument_array[5];
841
842 argument_array[0] = alloc_arg;
843 argument_array[1] = bytes_arg;
844 argument_array[2] = numBytes_arg;
845 argument_array[3] = encoding_arg;
846 argument_array[4] = isExternal_arg;
847
848 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000849
850 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanancc427fa2011-07-30 02:42:06 +0000851 CFSCWB_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +0000852 "CFStringCreateWithBytes",
853 FirstEntryInstruction);
Sean Callanan7a55a322010-11-18 22:21:58 +0000854
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000855 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callananafe16a72010-11-17 23:00:36 +0000856 {
857 if (log)
858 log->PutCString("Couldn't replace the NSString with the result of the call");
859
Sean Callanan3989fb92011-01-27 01:07:04 +0000860 if (m_error_stream)
861 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
862
Sean Callananafe16a72010-11-17 23:00:36 +0000863 return false;
864 }
865
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000866 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000867
868 return true;
869}
870
871bool
Sean Callanan79763a42011-05-23 21:40:23 +0000872IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callananafe16a72010-11-17 23:00:36 +0000873{
Greg Clayton5160ce52013-03-27 23:08:40 +0000874 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000875
Sean Callanan79763a42011-05-23 21:40:23 +0000876 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000877
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000878 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +0000879 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
880
881 if (!FirstEntryInstruction)
882 {
883 if (log)
884 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
885
Sean Callanan3989fb92011-01-27 01:07:04 +0000886 if (m_error_stream)
887 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
888
Sean Callananafe16a72010-11-17 23:00:36 +0000889 return false;
890 }
891
892 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
893 vi != ve;
894 ++vi)
895 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000896 std::string value_name = vi->first().str();
897 const char *value_name_cstr = value_name.c_str();
898
899 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000900 {
901 Value *nsstring_value = vi->second;
902
903 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
904
905 if (!nsstring_global)
906 {
907 if (log)
908 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000909
910 if (m_error_stream)
911 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
912
Sean Callananafe16a72010-11-17 23:00:36 +0000913 return false;
914 }
915
916 if (!nsstring_global->hasInitializer())
917 {
918 if (log)
919 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000920
921 if (m_error_stream)
922 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
923
Sean Callananafe16a72010-11-17 23:00:36 +0000924 return false;
925 }
926
927 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
928
929 if (!nsstring_struct)
930 {
931 if (log)
932 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000933
934 if (m_error_stream)
935 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
936
Sean Callananafe16a72010-11-17 23:00:36 +0000937 return false;
938 }
939
940 // We expect the following structure:
941 //
942 // struct {
943 // int *isa;
944 // int flags;
945 // char *str;
946 // long length;
947 // };
948
949 if (nsstring_struct->getNumOperands() != 4)
950 {
951 if (log)
952 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
Sean Callanan3989fb92011-01-27 01:07:04 +0000953
954 if (m_error_stream)
955 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
956
Sean Callananafe16a72010-11-17 23:00:36 +0000957 return false;
958 }
959
960 Constant *nsstring_member = nsstring_struct->getOperand(2);
961
962 if (!nsstring_member)
963 {
964 if (log)
965 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000966
967 if (m_error_stream)
968 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
969
Sean Callananafe16a72010-11-17 23:00:36 +0000970 return false;
971 }
972
973 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
974
975 if (!nsstring_expr)
976 {
977 if (log)
978 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000979
980 if (m_error_stream)
981 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
982
Sean Callananafe16a72010-11-17 23:00:36 +0000983 return false;
984 }
985
986 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
987 {
988 if (log)
989 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
Sean Callanan3989fb92011-01-27 01:07:04 +0000990
991 if (m_error_stream)
992 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
993
Sean Callananafe16a72010-11-17 23:00:36 +0000994 return false;
995 }
996
997 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
998
999 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1000
1001 if (!cstr_global)
1002 {
1003 if (log)
1004 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001005
1006 if (m_error_stream)
1007 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan80eee3a2010-11-20 02:06:01 +00001008
Sean Callananafe16a72010-11-17 23:00:36 +00001009 return false;
1010 }
1011
1012 if (!cstr_global->hasInitializer())
1013 {
1014 if (log)
1015 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +00001016
1017 if (m_error_stream)
1018 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1019
Sean Callananafe16a72010-11-17 23:00:36 +00001020 return false;
1021 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001022
1023 /*
Sean Callananafe16a72010-11-17 23:00:36 +00001024 if (!cstr_array)
1025 {
1026 if (log)
1027 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +00001028
1029 if (m_error_stream)
1030 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1031
Sean Callananafe16a72010-11-17 23:00:36 +00001032 return false;
1033 }
1034
1035 if (!cstr_array->isCString())
1036 {
1037 if (log)
1038 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +00001039
1040 if (m_error_stream)
1041 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1042
Sean Callananafe16a72010-11-17 23:00:36 +00001043 return false;
1044 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001045 */
1046
Sean Callanand2b465f2012-02-09 03:22:41 +00001047 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +00001048
1049 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +00001050 {
1051 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +00001052 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
Sean Callanan229ce2d2011-02-10 22:17:53 +00001053 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001054 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001055 }
1056
1057 if (!cstr_array)
1058 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001059
Sean Callanan79763a42011-05-23 21:40:23 +00001060 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan3989fb92011-01-27 01:07:04 +00001061 {
Sean Callananafe16a72010-11-17 23:00:36 +00001062 if (log)
1063 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001064
1065 // We don't print an error message here because RewriteObjCConstString has done so for us.
1066
Sean Callananafe16a72010-11-17 23:00:36 +00001067 return false;
1068 }
Sean Callananafe16a72010-11-17 23:00:36 +00001069 }
1070 }
1071
1072 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1073 vi != ve;
1074 ++vi)
1075 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001076 std::string value_name = vi->first().str();
1077 const char *value_name_cstr = value_name.c_str();
1078
1079 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001080 {
1081 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1082
1083 if (!gv)
1084 {
1085 if (log)
1086 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001087
1088 if (m_error_stream)
1089 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1090
Sean Callananafe16a72010-11-17 23:00:36 +00001091 return false;
1092 }
1093
1094 gv->eraseFromParent();
1095
1096 break;
1097 }
1098 }
1099
1100 return true;
1101}
1102
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001103static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001104{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001105 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001106
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001107 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001108 return false;
1109
1110 return true;
1111}
1112
Sean Callanan3989fb92011-01-27 01:07:04 +00001113// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001114bool
Sean Callanan79763a42011-05-23 21:40:23 +00001115IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001116{
Greg Clayton5160ce52013-03-27 23:08:40 +00001117 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001118
1119 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1120
1121 if (!load)
1122 return false;
1123
1124 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1125 //
1126 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1127 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1128 //
1129 // where %obj is the object pointer and %tmp is the selector.
1130 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001131 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1132 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001133
1134 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1135
1136 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1137
1138 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1139 return false;
1140
1141 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1142
1143 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1144
1145 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1146 return false;
1147
1148 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1149
1150 if (!osr_initializer_base)
1151 return false;
1152
1153 // Find the string's initializer (a ConstantArray) and get the string from it
1154
1155 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1156
1157 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1158 return false;
1159
1160 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1161
Sean Callanand2b465f2012-02-09 03:22:41 +00001162 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001163
1164 if (!omvn_initializer_array->isString())
1165 return false;
1166
1167 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1168
1169 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001170 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001171
1172 // Construct a call to sel_registerName
1173
1174 if (!m_sel_registerName)
1175 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001176 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001177
Greg Clayton7b462cc2010-10-15 22:48:33 +00001178 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001179 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001180 return false;
1181
Sean Callananbe3a1b12010-10-26 00:31:56 +00001182 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001183 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001184
Sean Callanan5300d372010-07-31 01:32:05 +00001185 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1186
1187 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001188 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001189 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001190 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001191
Sean Callanancc427fa2011-07-30 02:42:06 +00001192 Type *type_array[1];
1193
1194 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1195
1196 ArrayRef<Type *> srN_arg_types(type_array, 1);
1197
Sean Callanan5300d372010-07-31 01:32:05 +00001198 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1199
1200 // Build the constant containing the pointer to the function
Sean Callanancc427fa2011-07-30 02:42:06 +00001201 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001202 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan5300d372010-07-31 01:32:05 +00001203 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001204 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001205 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1206 }
1207
Sean Callanancc427fa2011-07-30 02:42:06 +00001208 Value *argument_array[1];
1209
Sean Callanan79763a42011-05-23 21:40:23 +00001210 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001211
Sean Callanancc427fa2011-07-30 02:42:06 +00001212 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001213
Sean Callanancc427fa2011-07-30 02:42:06 +00001214 ArrayRef<Value *> srN_arguments(argument_array, 1);
1215
Sean Callanan5300d372010-07-31 01:32:05 +00001216 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001217 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001218 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001219 selector_load);
1220
1221 // Replace the load with the call in all users
1222
1223 selector_load->replaceAllUsesWith(srN_call);
1224
1225 selector_load->eraseFromParent();
1226
1227 return true;
1228}
1229
1230bool
Sean Callanan79763a42011-05-23 21:40:23 +00001231IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001232{
Greg Clayton5160ce52013-03-27 23:08:40 +00001233 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001234
1235 BasicBlock::iterator ii;
1236
1237 typedef SmallVector <Instruction*, 2> InstrList;
1238 typedef InstrList::iterator InstrIterator;
1239
1240 InstrList selector_loads;
1241
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001242 for (ii = basic_block.begin();
1243 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001244 ++ii)
1245 {
1246 Instruction &inst = *ii;
1247
1248 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001249 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001250 selector_loads.push_back(&inst);
1251 }
1252
1253 InstrIterator iter;
1254
1255 for (iter = selector_loads.begin();
1256 iter != selector_loads.end();
1257 ++iter)
1258 {
Sean Callanan79763a42011-05-23 21:40:23 +00001259 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001260 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001261 if (m_error_stream)
1262 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1263
Enrico Granata20edcdb2011-07-19 18:03:25 +00001264 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001265 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001266
Sean Callanan5300d372010-07-31 01:32:05 +00001267 return false;
1268 }
1269 }
1270
1271 return true;
1272}
1273
Sean Callanan3989fb92011-01-27 01:07:04 +00001274// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001275bool
Sean Callanan79763a42011-05-23 21:40:23 +00001276IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001277{
Greg Clayton5160ce52013-03-27 23:08:40 +00001278 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001279
Sean Callanan2235f322010-08-11 03:57:18 +00001280 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1281
1282 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1283
1284 if (!alloc_md || !alloc_md->getNumOperands())
1285 return false;
1286
1287 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1288
1289 if (!constant_int)
1290 return false;
1291
1292 // We attempt to register this as a new persistent variable with the DeclMap.
1293
1294 uintptr_t ptr = constant_int->getZExtValue();
1295
Sean Callanand1e5b432010-08-12 01:56:52 +00001296 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001297
Sean Callanand1e5b432010-08-12 01:56:52 +00001298 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1299 &decl->getASTContext());
1300
Greg Clayton7b462cc2010-10-15 22:48:33 +00001301 StringRef decl_name (decl->getName());
1302 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001303 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001304 return false;
1305
Sean Callanan79763a42011-05-23 21:40:23 +00001306 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001307 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001308 false, /* not constant */
1309 GlobalValue::ExternalLinkage,
1310 NULL, /* no initializer */
1311 alloc->getName().str().c_str());
1312
1313 // What we're going to do here is make believe this was a regular old external
1314 // variable. That means we need to make the metadata valid.
1315
Sean Callanan585c0ec82012-07-04 01:26:26 +00001316 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001317
1318 llvm::Value* values[2];
1319 values[0] = persistent_global;
1320 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001321
1322 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001323
Sean Callanan79763a42011-05-23 21:40:23 +00001324 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001325 named_metadata->addOperand(persistent_global_md);
1326
Sean Callanane1175b72011-01-13 21:23:32 +00001327 // Now, since the variable is a pointer variable, we will drop in a load of that
1328 // pointer variable.
1329
1330 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1331
1332 if (log)
1333 log->Printf("Replacing \"%s\" with \"%s\"",
1334 PrintValue(alloc).c_str(),
1335 PrintValue(persistent_load).c_str());
1336
1337 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001338 alloc->eraseFromParent();
1339
1340 return true;
1341}
1342
1343bool
Sean Callanan79763a42011-05-23 21:40:23 +00001344IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001345{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001346 if (!m_resolve_vars)
1347 return true;
1348
Greg Clayton5160ce52013-03-27 23:08:40 +00001349 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001350
1351 BasicBlock::iterator ii;
1352
1353 typedef SmallVector <Instruction*, 2> InstrList;
1354 typedef InstrList::iterator InstrIterator;
1355
1356 InstrList pvar_allocs;
1357
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001358 for (ii = basic_block.begin();
1359 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001360 ++ii)
1361 {
1362 Instruction &inst = *ii;
1363
1364 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001365 {
1366 llvm::StringRef alloc_name = alloc->getName();
1367
1368 if (alloc_name.startswith("$") &&
1369 !alloc_name.startswith("$__lldb"))
1370 {
1371 if (alloc_name.find_first_of("0123456789") == 1)
1372 {
1373 if (log)
1374 log->Printf("Rejecting a numeric persistent variable.");
1375
Sean Callanan3989fb92011-01-27 01:07:04 +00001376 if (m_error_stream)
1377 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1378
Sean Callananf694a552011-01-21 22:30:25 +00001379 return false;
1380 }
1381
Sean Callanan2235f322010-08-11 03:57:18 +00001382 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001383 }
1384 }
Sean Callanan2235f322010-08-11 03:57:18 +00001385 }
1386
1387 InstrIterator iter;
1388
1389 for (iter = pvar_allocs.begin();
1390 iter != pvar_allocs.end();
1391 ++iter)
1392 {
Sean Callanan79763a42011-05-23 21:40:23 +00001393 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001394 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001395 if (m_error_stream)
1396 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1397
Enrico Granata20edcdb2011-07-19 18:03:25 +00001398 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001399 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001400
Sean Callanan2235f322010-08-11 03:57:18 +00001401 return false;
1402 }
1403 }
1404
1405 return true;
1406}
1407
Sean Callananc70ed462011-10-25 18:36:40 +00001408bool
1409IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1410{
1411 if (!initializer)
1412 return true;
1413
Greg Clayton5160ce52013-03-27 23:08:40 +00001414 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001415
1416 if (log && log->GetVerbose())
1417 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1418
1419 Type *initializer_type = initializer->getType();
1420
1421 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1422 {
1423 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1424 return true;
1425 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001426 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001427 {
1428 if (array_initializer->isString())
1429 {
1430 std::string array_initializer_string = array_initializer->getAsString();
1431 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1432 }
1433 else
1434 {
1435 ArrayType *array_initializer_type = array_initializer->getType();
1436 Type *array_element_type = array_initializer_type->getElementType();
1437
1438 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1439
1440 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1441 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001442 Value *operand_value = array_initializer->getOperand(i);
1443 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1444
1445 if (!operand_constant)
1446 return false;
1447
1448 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001449 return false;
1450 }
1451 }
1452 return true;
1453 }
1454 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1455 {
1456 StructType *struct_initializer_type = struct_initializer->getType();
1457 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1458
1459 for (int i = 0;
1460 i < struct_initializer->getNumOperands();
1461 ++i)
1462 {
1463 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1464 return false;
1465 }
1466 return true;
1467 }
1468 return false;
1469}
1470
1471bool
1472IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1473{
1474 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1475 return false;
1476
Sean Callananfe5d1392011-11-15 19:13:54 +00001477 if (global_variable == m_reloc_placeholder)
1478 return true;
1479
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001480 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001481
1482 llvm::Type *variable_type = global_variable->getType();
1483
1484 Constant *initializer = global_variable->getInitializer();
1485
1486 llvm::Type *initializer_type = initializer->getType();
1487
1488 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001489 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1490
1491 const size_t mask = (align - 1);
1492 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001493 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001494 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001495
1496 lldb_private::DataBufferHeap data(size, '\0');
1497
1498 if (initializer)
1499 if (!MaterializeInitializer(data.GetBytes(), initializer))
1500 return false;
1501
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001502 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001503
1504 Constant *new_pointer = BuildRelocation(variable_type, offset);
1505
1506 global_variable->replaceAllUsesWith(new_pointer);
1507
1508 global_variable->eraseFromParent();
1509
1510 return true;
1511}
1512
Sean Callanan3989fb92011-01-27 01:07:04 +00001513// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001514bool
Sean Callanan79763a42011-05-23 21:40:23 +00001515IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001516{
Greg Clayton5160ce52013-03-27 23:08:40 +00001517 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001518
1519 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001520 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001521
Greg Clayton7b462cc2010-10-15 22:48:33 +00001522 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001523 {
Sean Callanan5666b672010-08-04 01:02:13 +00001524 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001525 {
Sean Callanan5666b672010-08-04 01:02:13 +00001526 default:
1527 break;
1528 case Instruction::GetElementPtr:
1529 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001530 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001531 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001532 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001533 }
1534 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001535 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001536 {
Sean Callananc70ed462011-10-25 18:36:40 +00001537 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1538 return MaterializeInternalVariable(global_variable);
1539
Sean Callanan79763a42011-05-23 21:40:23 +00001540 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001541
Sean Callanan5300d372010-07-31 01:32:05 +00001542 if (!named_decl)
1543 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001544 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001545 return true;
1546
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001547 if (!global_variable->hasExternalLinkage())
1548 return true;
1549
Sean Callanan5300d372010-07-31 01:32:05 +00001550 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001551 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001552
Sean Callanan5300d372010-07-31 01:32:05 +00001553 return false;
1554 }
1555
Greg Clayton7b462cc2010-10-15 22:48:33 +00001556 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001557
Sean Callanan038df5032010-09-30 21:18:25 +00001558 void *opaque_type = NULL;
Sean Callanan1d180662010-07-20 23:31:16 +00001559 clang::ASTContext *ast_context = NULL;
Sean Callananea22d422010-07-16 00:09:46 +00001560
1561 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callanan1d180662010-07-20 23:31:16 +00001562 {
Sean Callanan038df5032010-09-30 21:18:25 +00001563 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callanan1d180662010-07-20 23:31:16 +00001564 ast_context = &value_decl->getASTContext();
1565 }
Sean Callananea22d422010-07-16 00:09:46 +00001566 else
Sean Callanan1d180662010-07-20 23:31:16 +00001567 {
Sean Callananea22d422010-07-16 00:09:46 +00001568 return false;
Sean Callanan1d180662010-07-20 23:31:16 +00001569 }
Sean Callanan038df5032010-09-30 21:18:25 +00001570
Sean Callanan92adcac2011-01-13 08:53:35 +00001571 clang::QualType qual_type;
Sean Callanan77eaf442011-07-08 00:39:14 +00001572 const Type *value_type = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00001573
Sean Callanane1175b72011-01-13 21:23:32 +00001574 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001575 {
1576 // The $__lldb_expr_result name indicates the the return value has allocated as
1577 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1578 // accesses to this static variable need to be redirected to the result of dereferencing
1579 // a pointer that is passed in as one of the arguments.
1580 //
1581 // Consequently, when reporting the size of the type, we report a pointer type pointing
1582 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001583 //
1584 // We also do this for any user-declared persistent variables.
Sean Callanan1d180662010-07-20 23:31:16 +00001585
Sean Callanan92adcac2011-01-13 08:53:35 +00001586 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1587 value_type = PointerType::get(global_variable->getType(), 0);
1588 }
1589 else
1590 {
1591 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1592 value_type = global_variable->getType();
1593 }
Sean Callanan038df5032010-09-30 21:18:25 +00001594
Greg Claytonfaac1112013-03-14 18:31:44 +00001595 uint64_t value_size = (ast_context->getTypeSize(qual_type) + 7ull) / 8ull;
1596 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001597
Sean Callanan038df5032010-09-30 21:18:25 +00001598 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +00001599 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001600 name.c_str(),
1601 qual_type.getAsString().c_str(),
1602 PrintType(value_type).c_str(),
1603 value_size,
1604 value_alignment);
Sean Callanan17827832010-12-13 22:46:15 +00001605
Sean Callanan549c9f72010-07-13 21:41:46 +00001606
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001607 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001608 lldb_private::ConstString (name.c_str()),
1609 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001610 value_size,
1611 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001612 {
1613 if (!global_variable->hasExternalLinkage())
1614 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001615 else if (HandleSymbol (global_variable))
1616 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001617 else
1618 return false;
1619 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001620 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001621 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001622 {
1623 if (log)
1624 log->Printf("Function pointers aren't handled right now");
1625
1626 return false;
1627 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001628
1629 return true;
1630}
1631
Sean Callanan3989fb92011-01-27 01:07:04 +00001632// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001633bool
Sean Callanan79763a42011-05-23 21:40:23 +00001634IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001635{
Greg Clayton5160ce52013-03-27 23:08:40 +00001636 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001637
1638 lldb_private::ConstString name(symbol->getName().str().c_str());
1639
Sean Callanan947ccc72011-12-01 02:04:16 +00001640 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001641
Greg Clayton084db102011-06-23 04:25:29 +00001642 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001643 {
1644 if (log)
1645 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1646
1647 return false;
1648 }
1649
1650 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001651 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001652
Sean Callanancc427fa2011-07-30 02:42:06 +00001653 Type *symbol_type = symbol->getType();
Sean Callanancc427fa2011-07-30 02:42:06 +00001654 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001655 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc3a16002011-01-17 23:42:46 +00001656
1657 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1658
1659 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1660
1661 if (log)
1662 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1663
1664 symbol->replaceAllUsesWith(symbol_addr_ptr);
1665
1666 return true;
1667}
1668
1669bool
Sean Callanan79763a42011-05-23 21:40:23 +00001670IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001671{
Greg Clayton5160ce52013-03-27 23:08:40 +00001672 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001673
1674 if (log)
1675 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001676
Sean Callananafe16a72010-11-17 23:00:36 +00001677 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001678 op_index < num_ops;
1679 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001680 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001681 {
1682 if (m_error_stream)
1683 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1684
Sean Callanan85a0a832010-10-05 22:26:43 +00001685 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001686 }
1687
Sean Callanan85a0a832010-10-05 22:26:43 +00001688 return true;
1689}
1690
1691bool
Sean Callananfc89c142011-11-01 23:38:03 +00001692IRForTarget::HandleObjCClass(Value *classlist_reference)
1693{
Greg Clayton5160ce52013-03-27 23:08:40 +00001694 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001695
1696 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1697
1698 if (!global_variable)
1699 return false;
1700
1701 Constant *initializer = global_variable->getInitializer();
1702
1703 if (!initializer)
1704 return false;
1705
1706 if (!initializer->hasName())
1707 return false;
1708
1709 StringRef name(initializer->getName());
1710 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001711 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001712
1713 if (log)
1714 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1715
1716 if (class_ptr == LLDB_INVALID_ADDRESS)
1717 return false;
1718
1719 if (global_variable->use_begin() == global_variable->use_end())
1720 return false;
1721
Sean Callanan719a4d52013-03-23 01:01:16 +00001722 SmallVector<LoadInst *, 2> load_instructions;
1723
Sean Callananfc89c142011-11-01 23:38:03 +00001724 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1725 i != e;
1726 ++i)
1727 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001728 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1729 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001730 }
1731
Sean Callanan719a4d52013-03-23 01:01:16 +00001732 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001733 return false;
1734
1735 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001736 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +00001737 == Module::Pointer64) ? 64 : 32);
Sean Callananfc89c142011-11-01 23:38:03 +00001738
1739 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001740
Sean Callanan719a4d52013-03-23 01:01:16 +00001741 for (LoadInst *load_instruction : load_instructions)
1742 {
1743 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001744
Sean Callanan719a4d52013-03-23 01:01:16 +00001745 load_instruction->replaceAllUsesWith(class_bitcast);
1746
1747 load_instruction->eraseFromParent();
1748 }
Sean Callananfc89c142011-11-01 23:38:03 +00001749
1750 return true;
1751}
1752
1753bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001754IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1755{
1756 BasicBlock::iterator ii;
1757
1758 std::vector<CallInst *> calls_to_remove;
1759
1760 for (ii = basic_block.begin();
1761 ii != basic_block.end();
1762 ++ii)
1763 {
1764 Instruction &inst = *ii;
1765
1766 CallInst *call = dyn_cast<CallInst>(&inst);
1767
1768 // MaybeHandleCallArguments handles error reporting; we are silent here
1769 if (!call)
1770 continue;
1771
1772 bool remove = false;
1773
1774 llvm::Function *func = call->getCalledFunction();
1775
1776 if (func && func->getName() == "__cxa_atexit")
1777 remove = true;
1778
1779 llvm::Value *val = call->getCalledValue();
1780
1781 if (val && val->getName() == "__cxa_atexit")
1782 remove = true;
1783
1784 if (remove)
1785 calls_to_remove.push_back(call);
1786 }
1787
1788 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1789 ci != ce;
1790 ++ci)
1791 {
1792 (*ci)->eraseFromParent();
1793 }
1794
1795 return true;
1796}
1797
1798bool
Sean Callanan79763a42011-05-23 21:40:23 +00001799IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001800{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001801 /////////////////////////////////////////////////////////////////////////
1802 // Prepare the current basic block for execution in the remote process
1803 //
1804
Sean Callanan7ea35012010-07-27 21:39:39 +00001805 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001806
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001807 for (ii = basic_block.begin();
1808 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001809 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001810 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001811 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001812
Sean Callanana4e55172010-11-08 00:31:32 +00001813 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001814
Sean Callanan3989fb92011-01-27 01:07:04 +00001815 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001816 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001817 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001818 }
1819
1820 return true;
1821}
1822
Sean Callanana4e55172010-11-08 00:31:32 +00001823bool
Sean Callanan79763a42011-05-23 21:40:23 +00001824IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001825{
Greg Clayton5160ce52013-03-27 23:08:40 +00001826 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001827
Sean Callanan79763a42011-05-23 21:40:23 +00001828 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001829 global != end;
1830 ++global)
1831 {
Sean Callanan694e2442011-12-22 21:24:49 +00001832 if (!global)
1833 {
1834 if (m_error_stream)
1835 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1836
1837 return false;
1838 }
1839
1840 std::string global_name = (*global).getName().str();
1841
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001842 if (log)
1843 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001844 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001845 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001846
1847 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001848 {
Sean Callanan79763a42011-05-23 21:40:23 +00001849 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001850 {
1851 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001852 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 +00001853
Sean Callananc3a16002011-01-17 23:42:46 +00001854 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001855 }
Sean Callananc3a16002011-01-17 23:42:46 +00001856 }
Sean Callananfc89c142011-11-01 23:38:03 +00001857 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1858 {
1859 if (!HandleObjCClass(global))
1860 {
1861 if (m_error_stream)
1862 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1863
1864 return false;
1865 }
1866 }
Sean Callanan79763a42011-05-23 21:40:23 +00001867 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001868 {
Sean Callanan79763a42011-05-23 21:40:23 +00001869 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001870 {
1871 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001872 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 +00001873
Sean Callananc3a16002011-01-17 23:42:46 +00001874 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001875 }
Sean Callananc3a16002011-01-17 23:42:46 +00001876 }
Sean Callanana4e55172010-11-08 00:31:32 +00001877 }
1878
1879 return true;
1880}
1881
Sean Callanan79763a42011-05-23 21:40:23 +00001882bool
1883IRForTarget::ReplaceStrings ()
1884{
Greg Clayton5160ce52013-03-27 23:08:40 +00001885 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001886
Sean Callanan79763a42011-05-23 21:40:23 +00001887 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1888
1889 OffsetsTy offsets;
1890
1891 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1892 gi != ge;
1893 ++gi)
1894 {
1895 GlobalVariable *gv = gi;
1896
1897 if (!gv->hasInitializer())
1898 continue;
1899
1900 Constant *gc = gv->getInitializer();
1901
Sean Callanan5207a342011-08-10 21:05:52 +00001902 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001903
Sean Callanan5207a342011-08-10 21:05:52 +00001904 if (gc->isNullValue())
1905 {
1906 Type *gc_type = gc->getType();
1907
1908 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1909
1910 if (!gc_array_type)
1911 continue;
1912
1913 Type *gc_element_type = gc_array_type->getElementType();
1914
1915 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1916
1917 if (gc_integer_type->getBitWidth() != 8)
1918 continue;
1919
1920 str = "";
1921 }
1922 else
1923 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001924 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001925
1926 if (!gc_array)
1927 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001928
Sean Callanan5207a342011-08-10 21:05:52 +00001929 if (!gc_array->isCString())
1930 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001931
Sean Callanan5207a342011-08-10 21:05:52 +00001932 if (log)
1933 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001934
Sean Callanan5207a342011-08-10 21:05:52 +00001935 str = gc_array->getAsString();
1936 }
1937
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001938 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001939
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001940 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001941 }
1942
Sean Callanancc427fa2011-07-30 02:42:06 +00001943 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001944
1945 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1946 oi != oe;
1947 ++oi)
1948 {
1949 GlobalVariable *gv = oi->first;
1950 size_t offset = oi->second;
1951
1952 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1953
1954 if (log)
1955 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1956
1957 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1958 ui != ue;
1959 ++ui)
1960 {
1961 if (log)
1962 log->Printf("Found use %s", PrintValue(*ui).c_str());
1963
1964 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1965 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1966
1967 if (const_expr)
1968 {
1969 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1970 {
1971 if (log)
1972 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1973
1974 return false;
1975 }
1976
Sean Callanan5207a342011-08-10 21:05:52 +00001977 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1978 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1979
1980 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001981 }
1982 else if (store_inst)
1983 {
1984 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1985
1986 store_inst->setOperand(0, bit_cast);
1987 }
1988 else
1989 {
1990 if (log)
1991 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1992
1993 return false;
1994 }
1995 }
1996
1997 gv->eraseFromParent();
1998 }
1999
2000 return true;
2001}
2002
2003bool
2004IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
2005{
Greg Clayton5160ce52013-03-27 23:08:40 +00002006 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002007
2008 typedef SmallVector <Value*, 2> ConstantList;
2009 typedef SmallVector <llvm::Instruction*, 2> UserList;
2010 typedef ConstantList::iterator ConstantIterator;
2011 typedef UserList::iterator UserIterator;
2012
2013 ConstantList static_constants;
2014 UserList static_users;
2015
2016 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2017 ii != ie;
2018 ++ii)
2019 {
2020 llvm::Instruction &inst = *ii;
2021
2022 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2023 oi != oe;
2024 ++oi)
2025 {
2026 Value *operand_val = oi->get();
2027
2028 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2029
Sean Callanan822944c2012-04-26 20:51:20 +00002030 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00002031 {
2032 static_constants.push_back(operand_val);
2033 static_users.push_back(ii);
2034 }
2035 }
2036 }
2037
2038 ConstantIterator constant_iter;
2039 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00002040
Sean Callanan79763a42011-05-23 21:40:23 +00002041 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2042 constant_iter != static_constants.end();
2043 ++constant_iter, ++user_iter)
2044 {
2045 Value *operand_val = *constant_iter;
2046 llvm::Instruction *inst = *user_iter;
2047
2048 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2049
2050 if (operand_constant_fp)
2051 {
Sean Callanan1582ee62013-04-18 22:06:33 +00002052 Type *operand_type = operand_constant_fp->getType();
2053
Sean Callanan79763a42011-05-23 21:40:23 +00002054 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2055 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2056
2057 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2058 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2059
2060 if (log)
2061 {
2062 std::string s;
2063 raw_string_ostream ss(s);
2064 for (size_t index = 0;
2065 index < operand_data_size;
2066 ++index)
2067 {
2068 ss << (uint32_t)operand_raw_data[index];
2069 ss << " ";
2070 }
2071 ss.flush();
2072
Jason Molendafd54b362011-09-20 21:44:10 +00002073 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002074 }
2075
2076 lldb_private::DataBufferHeap data(operand_data_size, 0);
2077
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002078 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002079 {
2080 uint8_t *data_bytes = data.GetBytes();
2081
2082 for (size_t index = 0;
2083 index < operand_data_size;
2084 ++index)
2085 {
2086 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2087 }
2088 }
2089 else
2090 {
2091 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2092 }
2093
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002094 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002095
Sean Callanane3333d62012-06-08 22:20:41 +00002096 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2097
2098 const size_t mask = (align - 1);
2099 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002100 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002101 offset = aligned_offset;
2102
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002103 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002104
Sean Callanancc427fa2011-07-30 02:42:06 +00002105 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002106
Sean Callanan1582ee62013-04-18 22:06:33 +00002107 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002108
2109 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2110
2111 operand_constant_fp->replaceAllUsesWith(fp_load);
2112 }
2113 }
2114
2115 return true;
2116}
2117
Sean Callanan7ea35012010-07-27 21:39:39 +00002118static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002119{
Sean Callanan77eaf442011-07-08 00:39:14 +00002120 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002121
Sean Callananafe16a72010-11-17 23:00:36 +00002122 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002123 return false;
2124
Sean Callanan77eaf442011-07-08 00:39:14 +00002125 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002126
2127 if ((CE = dyn_cast<ConstantExpr>(V)))
2128 {
2129 if (CE->getOpcode() != Instruction::BitCast)
2130 return false;
2131
Sean Callananafe16a72010-11-17 23:00:36 +00002132 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002133 }
2134
Sean Callananafe16a72010-11-17 23:00:36 +00002135 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002136
2137 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2138 return false;
2139
2140 return true;
2141}
2142
Sean Callanan79763a42011-05-23 21:40:23 +00002143void
2144IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002145{
Sean Callanan79763a42011-05-23 21:40:23 +00002146 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002147
2148 Value::use_iterator ui;
2149
2150 for (ui = guard_load->use_begin();
2151 ui != guard_load->use_end();
2152 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002153 {
Greg Claytone6371122010-07-30 20:30:44 +00002154 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002155 {
2156 // do nothing for the moment
2157 }
2158 else
2159 {
2160 ui->replaceUsesOfWith(guard_load, zero);
2161 }
2162 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002163
2164 guard_load->eraseFromParent();
2165}
2166
2167static void ExciseGuardStore(Instruction* guard_store)
2168{
2169 guard_store->eraseFromParent();
2170}
2171
2172bool
Sean Callanan79763a42011-05-23 21:40:23 +00002173IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002174{
2175 ///////////////////////////////////////////////////////
2176 // Eliminate any reference to guard variables found.
2177 //
2178
Sean Callanan7ea35012010-07-27 21:39:39 +00002179 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002180
Sean Callanan7ea35012010-07-27 21:39:39 +00002181 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002182 typedef InstrList::iterator InstrIterator;
2183
2184 InstrList guard_loads;
2185 InstrList guard_stores;
2186
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002187 for (ii = basic_block.begin();
2188 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002189 ++ii)
2190 {
2191 Instruction &inst = *ii;
2192
2193 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2194 if (isGuardVariableRef(load->getPointerOperand()))
2195 guard_loads.push_back(&inst);
2196
2197 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2198 if (isGuardVariableRef(store->getPointerOperand()))
2199 guard_stores.push_back(&inst);
2200 }
2201
2202 InstrIterator iter;
2203
2204 for (iter = guard_loads.begin();
2205 iter != guard_loads.end();
2206 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002207 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002208
2209 for (iter = guard_stores.begin();
2210 iter != guard_stores.end();
2211 ++iter)
2212 ExciseGuardStore(*iter);
2213
2214 return true;
2215}
2216
Sean Callanan3989fb92011-01-27 01:07:04 +00002217// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002218bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002219IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002220{
Greg Clayton5160ce52013-03-27 23:08:40 +00002221 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002222
2223 Value::use_iterator ui;
2224
Sean Callanan2235f322010-08-11 03:57:18 +00002225 SmallVector<User*, 16> users;
2226
2227 // We do this because the use list might change, invalidating our iterator.
2228 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002229 for (ui = old_constant->use_begin();
2230 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002231 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002232 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002233
Johnny Chen44805302011-07-19 19:48:13 +00002234 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002235 i < users.size();
2236 ++i)
2237 {
2238 User *user = users[i];
2239
Sean Callanan7618f4e2010-07-14 23:40:29 +00002240 if (Constant *constant = dyn_cast<Constant>(user))
2241 {
2242 // synthesize a new non-constant equivalent of the constant
2243
2244 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2245 {
2246 switch (constant_expr->getOpcode())
2247 {
2248 default:
2249 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002250 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002251 return false;
2252 case Instruction::BitCast:
2253 {
2254 // UnaryExpr
2255 // OperandList[0] is value
2256
2257 Value *s = constant_expr->getOperand(0);
2258
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002259 if (s == old_constant)
2260 s = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002261
Sean Callanan79763a42011-05-23 21:40:23 +00002262 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002263
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002264 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002265 }
2266 break;
2267 case Instruction::GetElementPtr:
2268 {
2269 // GetElementPtrConstantExpr
2270 // OperandList[0] is base
2271 // OperandList[1]... are indices
2272
2273 Value *ptr = constant_expr->getOperand(0);
2274
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002275 if (ptr == old_constant)
2276 ptr = new_constant;
Sean Callanancc427fa2011-07-30 02:42:06 +00002277
2278 std::vector<Value*> index_vector;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002279
2280 unsigned operand_index;
2281 unsigned num_operands = constant_expr->getNumOperands();
2282
2283 for (operand_index = 1;
2284 operand_index < num_operands;
2285 ++operand_index)
2286 {
2287 Value *operand = constant_expr->getOperand(operand_index);
2288
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002289 if (operand == old_constant)
2290 operand = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002291
Sean Callanancc427fa2011-07-30 02:42:06 +00002292 index_vector.push_back(operand);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002293 }
2294
Sean Callanancc427fa2011-07-30 02:42:06 +00002295 ArrayRef <Value*> indices(index_vector);
2296
2297 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002298
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002299 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002300 }
2301 break;
2302 }
2303 }
2304 else
2305 {
2306 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002307 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002308 return false;
2309 }
2310 }
2311 else
2312 {
2313 // simple fall-through case for non-constants
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002314 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002315 }
2316 }
2317
2318 return true;
2319}
2320
Sean Callanan549c9f72010-07-13 21:41:46 +00002321bool
Sean Callanan79763a42011-05-23 21:40:23 +00002322IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002323{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002324 if (!m_resolve_vars)
2325 return true;
2326
Greg Clayton5160ce52013-03-27 23:08:40 +00002327 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002328
2329 m_decl_map->DoStructLayout();
2330
2331 if (log)
2332 log->Printf("Element arrangement:");
2333
2334 uint32_t num_elements;
2335 uint32_t element_index;
2336
2337 size_t size;
2338 off_t alignment;
2339
2340 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2341 return false;
2342
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002343 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002344
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002345 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002346 {
2347 if (m_error_stream)
2348 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2349
Sean Callanan549c9f72010-07-13 21:41:46 +00002350 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002351 }
2352
Sean Callanan7ea35012010-07-27 21:39:39 +00002353 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002354
Sean Callananfc55f5d2010-09-21 00:44:12 +00002355 if (argument->getName().equals("this"))
2356 {
2357 ++iter;
2358
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002359 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002360 {
2361 if (m_error_stream)
2362 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2363
Sean Callananfc55f5d2010-09-21 00:44:12 +00002364 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002365 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002366
2367 argument = iter;
2368 }
Sean Callanan17827832010-12-13 22:46:15 +00002369 else if (argument->getName().equals("self"))
2370 {
2371 ++iter;
2372
2373 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002374 {
2375 if (m_error_stream)
2376 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2377
Sean Callanan17827832010-12-13 22:46:15 +00002378 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002379 }
Sean Callanan17827832010-12-13 22:46:15 +00002380
2381 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002382 {
2383 if (m_error_stream)
2384 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2385
Sean Callanan17827832010-12-13 22:46:15 +00002386 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002387 }
Sean Callanan17827832010-12-13 22:46:15 +00002388
2389 ++iter;
2390
2391 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002392 {
2393 if (m_error_stream)
2394 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2395
Sean Callanan17827832010-12-13 22:46:15 +00002396 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002397 }
Sean Callanan17827832010-12-13 22:46:15 +00002398
2399 argument = iter;
2400 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002401
Greg Clayton7b462cc2010-10-15 22:48:33 +00002402 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002403 {
2404 if (m_error_stream)
2405 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2406
Sean Callanan549c9f72010-07-13 21:41:46 +00002407 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002408 }
2409
Sean Callanan549c9f72010-07-13 21:41:46 +00002410 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002411 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002412
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002413 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002414 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002415
Sean Callananafe16a72010-11-17 23:00:36 +00002416 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002417 {
2418 if (m_error_stream)
2419 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2420
Sean Callanan549c9f72010-07-13 21:41:46 +00002421 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002422 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002423
Sean Callanan79763a42011-05-23 21:40:23 +00002424 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002425 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002426
2427 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002428 {
2429 if (m_error_stream)
2430 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2431
Sean Callanan549c9f72010-07-13 21:41:46 +00002432 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002433 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002434
2435 for (element_index = 0; element_index < num_elements; ++element_index)
2436 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002437 const clang::NamedDecl *decl = NULL;
2438 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002439 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002440 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002441
Sean Callanan823bb4c2010-08-30 22:17:16 +00002442 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002443 {
2444 if (m_error_stream)
2445 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2446
Sean Callanan549c9f72010-07-13 21:41:46 +00002447 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002448 }
2449
Sean Callanan549c9f72010-07-13 21:41:46 +00002450 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002451 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002452 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002453 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002454 offset);
2455
Sean Callanancc427fa2011-07-30 02:42:06 +00002456 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callananafe16a72010-11-17 23:00:36 +00002457 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan92adcac2011-01-13 08:53:35 +00002458
Sean Callananc70ed462011-10-25 18:36:40 +00002459 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002460 {
Sean Callananc70ed462011-10-25 18:36:40 +00002461 Value *replacement = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00002462
Sean Callananc70ed462011-10-25 18:36:40 +00002463 if (log)
2464 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002465
Sean Callananc70ed462011-10-25 18:36:40 +00002466 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2467 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2468 // entry in order to produce the static variable that the AST thinks it is accessing.
2469 if (name == m_result_name && !m_result_is_pointer)
2470 {
2471 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2472
2473 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2474
2475 replacement = load;
2476 }
2477 else
2478 {
2479 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2480
2481 replacement = bit_cast;
2482 }
2483
2484 if (Constant *constant = dyn_cast<Constant>(value))
2485 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2486 else
2487 value->replaceAllUsesWith(replacement);
2488
2489 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2490 var->eraseFromParent();
2491 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002492 }
2493
2494 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002495 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002496
2497 return true;
2498}
2499
Sean Callanan79763a42011-05-23 21:40:23 +00002500llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002501IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002502{
Sean Callanancc427fa2011-07-30 02:42:06 +00002503 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002504 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002505
2506 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002507
2508 llvm::Constant *offset_array[1];
2509
2510 offset_array[0] = offset_int;
2511
2512 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2513
2514 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002515 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2516
2517 return reloc_getbitcast;
2518}
2519
2520bool
2521IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002522{
Greg Clayton5160ce52013-03-27 23:08:40 +00002523 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002524
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002525 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002526 return true;
2527
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002528 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002529
2530 if (log)
2531 {
2532 if (allocation)
2533 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2534 else
2535 log->Printf("Failed to allocate static data");
2536 }
2537
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002538 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002539 return false;
2540
Sean Callanancc427fa2011-07-30 02:42:06 +00002541 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002542 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002543
2544 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2545 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2546
2547 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2548
2549 m_reloc_placeholder->eraseFromParent();
2550
2551 return true;
2552}
2553
Sean Callanan2ab712f22010-07-03 01:35:46 +00002554bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002555IRForTarget::StripAllGVs (Module &llvm_module)
2556{
Greg Clayton5160ce52013-03-27 23:08:40 +00002557 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002558 std::vector<GlobalVariable *> global_vars;
2559 std::set<GlobalVariable *>erased_vars;
2560
2561 bool erased = true;
2562
2563 while (erased)
2564 {
2565 erased = false;
2566
2567 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2568 gi != ge;
2569 ++gi)
2570 {
2571 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2572
2573 global_var->removeDeadConstantUsers();
2574
2575 if (global_var->use_empty())
2576 {
2577 if (log)
2578 log->Printf("Did remove %s",
2579 PrintValue(global_var).c_str());
2580 global_var->eraseFromParent();
2581 erased = true;
2582 break;
2583 }
2584 }
2585 }
2586
2587 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2588 gi != ge;
2589 ++gi)
2590 {
2591 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2592
2593 GlobalValue::use_iterator ui = global_var->use_begin();
2594
Jim Inghamd77557d2012-11-26 19:54:04 +00002595 if (log)
2596 log->Printf("Couldn't remove %s because of %s",
2597 PrintValue(global_var).c_str(),
2598 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002599 }
2600
2601 return true;
2602}
2603
2604bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002605IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002606{
Greg Clayton5160ce52013-03-27 23:08:40 +00002607 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002608
Sean Callanan79763a42011-05-23 21:40:23 +00002609 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002610 m_target_data.reset(new DataLayout(m_module));
Sean Callanan79763a42011-05-23 21:40:23 +00002611
2612 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002613
2614 if (!function)
2615 {
2616 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002617 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00002618
2619 if (m_error_stream)
Sean Callanan79763a42011-05-23 21:40:23 +00002620 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002621
Sean Callanan2ab712f22010-07-03 01:35:46 +00002622 return false;
2623 }
Sean Callanan79763a42011-05-23 21:40:23 +00002624
2625 if (!FixFunctionLinkage (*function))
2626 {
2627 if (log)
2628 log->Printf("Couldn't fix the linkage for the function");
2629
2630 return false;
2631 }
2632
Sean Callananc70ed462011-10-25 18:36:40 +00002633 if (log)
2634 {
2635 std::string s;
2636 raw_string_ostream oss(s);
2637
2638 m_module->print(oss, NULL);
2639
2640 oss.flush();
2641
2642 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2643 }
2644
Sean Callanancc427fa2011-07-30 02:42:06 +00002645 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002646
2647 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2648 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002649 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002650 GlobalVariable::InternalLinkage,
2651 Constant::getNullValue(intptr_ty),
2652 "reloc_placeholder",
2653 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002654 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002655 0 /* AddressSpace */);
Sean Callanan2ab712f22010-07-03 01:35:46 +00002656
Sean Callanan7ea35012010-07-27 21:39:39 +00002657 Function::iterator bbi;
Sean Callanan2ab712f22010-07-03 01:35:46 +00002658
Sean Callanan79763a42011-05-23 21:40:23 +00002659 m_has_side_effects = HasSideEffects(*function);
Sean Callanane4ec90e2010-12-16 03:17:46 +00002660
Sean Callanand1e5b432010-08-12 01:56:52 +00002661 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002662 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002663 //
2664
Sean Callanan79763a42011-05-23 21:40:23 +00002665 if (!CreateResultVariable(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002666 {
2667 if (log)
2668 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002669
2670 // CreateResultVariable() reports its own errors, so we don't do so here
2671
Sean Callanand1e5b432010-08-12 01:56:52 +00002672 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002673 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002674
2675 for (bbi = function->begin();
2676 bbi != function->end();
2677 ++bbi)
2678 {
2679 if (!RemoveGuards(*bbi))
2680 {
2681 if (log)
2682 log->Printf("RemoveGuards() failed");
2683
2684 // RemoveGuards() reports its own errors, so we don't do so here
2685
2686 return false;
2687 }
2688
2689 if (!RewritePersistentAllocs(*bbi))
2690 {
2691 if (log)
2692 log->Printf("RewritePersistentAllocs() failed");
2693
2694 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2695
2696 return false;
2697 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002698
2699 if (!RemoveCXAAtExit(*bbi))
2700 {
2701 if (log)
2702 log->Printf("RemoveCXAAtExit() failed");
2703
2704 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2705
2706 return false;
2707 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002708 }
2709
Sean Callananea685ae2011-11-01 17:33:54 +00002710 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002711 {
2712 std::string s;
2713 raw_string_ostream oss(s);
2714
2715 m_module->print(oss, NULL);
2716
2717 oss.flush();
2718
2719 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2720 }
2721
Sean Callananafe16a72010-11-17 23:00:36 +00002722 ///////////////////////////////////////////////////////////////////////////////
2723 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2724 //
Sean Callananafe16a72010-11-17 23:00:36 +00002725
Sean Callanan79763a42011-05-23 21:40:23 +00002726 if (!RewriteObjCConstStrings(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002727 {
2728 if (log)
2729 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002730
2731 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2732
Sean Callananafe16a72010-11-17 23:00:36 +00002733 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002734 }
Sean Callananafe16a72010-11-17 23:00:36 +00002735
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002736 ///////////////////////////////
2737 // Resolve function pointers
2738 //
2739
2740 if (!ResolveFunctionPointers(llvm_module, *function))
2741 {
2742 if (log)
2743 log->Printf("ResolveFunctionPointers() failed");
2744
2745 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2746
2747 return false;
2748 }
2749
Sean Callanan2ab712f22010-07-03 01:35:46 +00002750 for (bbi = function->begin();
2751 bbi != function->end();
2752 ++bbi)
2753 {
Sean Callanan79763a42011-05-23 21:40:23 +00002754 if (!RewriteObjCSelectors(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002755 {
2756 if (log)
2757 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002758
2759 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2760
Sean Callanan2235f322010-08-11 03:57:18 +00002761 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002762 }
Sean Callananbad134f2012-07-27 19:25:24 +00002763 }
Sean Callanan2235f322010-08-11 03:57:18 +00002764
Sean Callananbad134f2012-07-27 19:25:24 +00002765 for (bbi = function->begin();
2766 bbi != function->end();
2767 ++bbi)
2768 {
Sean Callanan79763a42011-05-23 21:40:23 +00002769 if (!ResolveCalls(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002770 {
2771 if (log)
2772 log->Printf("ResolveCalls() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002773
2774 // ResolveCalls() reports its own errors, so we don't do so here
2775
Sean Callanan549c9f72010-07-13 21:41:46 +00002776 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002777 }
Sean Callanan79763a42011-05-23 21:40:23 +00002778
2779 if (!ReplaceStaticLiterals(*bbi))
2780 {
2781 if (log)
2782 log->Printf("ReplaceStaticLiterals() failed");
2783
2784 return false;
2785 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002786 }
2787
Sean Callanan038df5032010-09-30 21:18:25 +00002788 ///////////////////////////////
2789 // Run function-level passes
2790 //
2791
Sean Callanan79763a42011-05-23 21:40:23 +00002792 if (!ResolveExternals(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002793 {
2794 if (log)
2795 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002796
2797 // ResolveExternals() reports its own errors, so we don't do so here
2798
Sean Callanana4e55172010-11-08 00:31:32 +00002799 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002800 }
Sean Callanana4e55172010-11-08 00:31:32 +00002801
Sean Callanan79763a42011-05-23 21:40:23 +00002802 if (!ReplaceVariables(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002803 {
2804 if (log)
2805 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002806
2807 // ReplaceVariables() reports its own errors, so we don't do so here
2808
Sean Callanan038df5032010-09-30 21:18:25 +00002809 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002810 }
Sean Callanan038df5032010-09-30 21:18:25 +00002811
Sean Callanan79763a42011-05-23 21:40:23 +00002812 if (!ReplaceStrings())
2813 {
2814 if (log)
2815 log->Printf("ReplaceStrings() failed");
2816
2817 return false;
2818 }
2819
2820 if (!CompleteDataAllocation())
2821 {
2822 if (log)
2823 log->Printf("CompleteDataAllocation() failed");
2824
2825 return false;
2826 }
2827
Sean Callanan3d654b32012-09-24 22:25:51 +00002828 if (!StripAllGVs(llvm_module))
2829 {
2830 if (log)
2831 log->Printf("StripAllGVs() failed");
2832 }
2833
Sean Callananea685ae2011-11-01 17:33:54 +00002834 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002835 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002836 std::string s;
2837 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002838
Sean Callanan79763a42011-05-23 21:40:23 +00002839 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002840
2841 oss.flush();
2842
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002843 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002844 }
2845
2846 return true;
2847}
2848
2849void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002850IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002851{
2852}
2853
2854PassManagerType
2855IRForTarget::getPotentialPassManagerType() const
2856{
2857 return PMT_ModulePassManager;
2858}