blob: a6d1651727f356fe09631dcbd2266d0cfb8652fb [file] [log] [blame]
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001//===-- IRForTarget.cpp -------------------------------------------*- C++ -*-===//
2//
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"
13#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000014#include "llvm/Instructions.h"
Sean Callanan3cb1fd82010-09-28 23:55:00 +000015#include "llvm/Intrinsics.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000016#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000017#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000018#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000019
20#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000021
Greg Clayton8de27c72010-10-15 22:48:33 +000022#include "lldb/Core/ConstString.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000023#include "lldb/Core/dwarf.h"
24#include "lldb/Core/Log.h"
25#include "lldb/Core/Scalar.h"
26#include "lldb/Core/StreamString.h"
27#include "lldb/Expression/ClangExpressionDeclMap.h"
28
29#include <map>
30
31using namespace llvm;
32
Sean Callanan3351dac2010-08-18 18:50:51 +000033static char ID;
34
Greg Clayton3c7feb42010-11-19 01:05:25 +000035IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
36 bool resolve_vars,
Sean Callanan05a5a1b2010-12-16 03:17:46 +000037 lldb::ClangExpressionVariableSP *const_result,
Sean Callanan97c924e2011-01-27 01:07:04 +000038 lldb_private::Stream *error_stream,
Greg Clayton3c7feb42010-11-19 01:05:25 +000039 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000040 ModulePass(ID),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000041 m_resolve_vars(resolve_vars),
42 m_func_name(func_name),
Sean Callanan8bce6652010-07-13 21:41:46 +000043 m_decl_map(decl_map),
Sean Callanan6ba533e2010-11-17 23:00:36 +000044 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000045 m_sel_registerName(NULL),
Sean Callanan05a5a1b2010-12-16 03:17:46 +000046 m_const_result(const_result),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000047 m_error_stream(error_stream),
Sean Callanan6a925532011-01-13 08:53:35 +000048 m_has_side_effects(false),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000049 m_result_is_pointer(false)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000050{
51}
52
Sean Callanan771131d2010-09-30 21:18:25 +000053/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000054
55static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000056PrintValue(const Value *value, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000057{
58 std::string s;
59 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000060 value->print(rso);
Sean Callanana48fe162010-08-11 03:57:18 +000061 rso.flush();
62 if (truncate)
63 s.resize(s.length() - 1);
64 return s;
65}
66
Sean Callanan771131d2010-09-30 21:18:25 +000067static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000068PrintType(const Type *type, bool truncate = false)
Sean Callanan771131d2010-09-30 21:18:25 +000069{
70 std::string s;
71 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000072 type->print(rso);
Sean Callanan771131d2010-09-30 21:18:25 +000073 rso.flush();
74 if (truncate)
75 s.resize(s.length() - 1);
76 return s;
77}
78
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000079IRForTarget::~IRForTarget()
80{
81}
82
Sean Callanan82b74c82010-08-12 01:56:52 +000083bool
Sean Callanan05a5a1b2010-12-16 03:17:46 +000084IRForTarget::HasSideEffects (llvm::Module &llvm_module,
85 llvm::Function &llvm_function)
86{
87 llvm::Function::iterator bbi;
88 BasicBlock::iterator ii;
89
90 for (bbi = llvm_function.begin();
91 bbi != llvm_function.end();
92 ++bbi)
93 {
94 BasicBlock &basic_block = *bbi;
95
96 for (ii = basic_block.begin();
97 ii != basic_block.end();
98 ++ii)
99 {
100 switch (ii->getOpcode())
101 {
102 default:
103 return true;
104 case Instruction::Store:
105 {
106 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
107
108 Value *store_ptr = store_inst->getPointerOperand();
109
110 if (!isa <AllocaInst> (store_ptr))
111 return true;
112 else
113 break;
114 }
115 case Instruction::Load:
116 case Instruction::Alloca:
117 case Instruction::GetElementPtr:
118 case Instruction::Ret:
119 break;
120 }
121 }
122 }
123
124 return false;
125}
126
127void
128IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
129 const lldb_private::ConstString &name,
130 lldb_private::TypeFromParser type)
131{
132 if (!m_const_result)
133 return;
134
135 if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
136 {
137 *m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
138 }
139}
140
141bool
Greg Clayton3c7feb42010-11-19 01:05:25 +0000142IRForTarget::CreateResultVariable (llvm::Module &llvm_module, llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000143{
Greg Claytone005f2c2010-11-06 01:53:30 +0000144 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000145
Sean Callanane8a59a82010-09-13 21:34:21 +0000146 if (!m_resolve_vars)
147 return true;
148
149 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000150
Greg Clayton8de27c72010-10-15 22:48:33 +0000151 ValueSymbolTable& value_symbol_table = llvm_module.getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000152
153 const char *result_name = NULL;
154
155 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
156 vi != ve;
157 ++vi)
158 {
Sean Callanan6a925532011-01-13 08:53:35 +0000159 if (strstr(vi->first(), "$__lldb_expr_result_ptr") &&
160 !strstr(vi->first(), "GV"))
161 {
162 result_name = vi->first();
163 m_result_is_pointer = true;
164 break;
165 }
166
Greg Clayton8de27c72010-10-15 22:48:33 +0000167 if (strstr(vi->first(), "$__lldb_expr_result") &&
Sean Callananc04743d2010-09-28 21:13:03 +0000168 !strstr(vi->first(), "GV"))
169 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000170 result_name = vi->first();
Sean Callanan6a925532011-01-13 08:53:35 +0000171 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000172 break;
173 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000174 }
175
176 if (!result_name)
177 {
178 if (log)
179 log->PutCString("Couldn't find result variable");
180
181 return true;
182 }
183
Sean Callananc04743d2010-09-28 21:13:03 +0000184 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000185 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000186
Greg Clayton8de27c72010-10-15 22:48:33 +0000187 Value *result_value = llvm_module.getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000188
189 if (!result_value)
190 {
191 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000192 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000193
Sean Callanan97c924e2011-01-27 01:07:04 +0000194 if (m_error_stream)
195 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
196
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000197 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000198 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000199
Sean Callanan82b74c82010-08-12 01:56:52 +0000200 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000201 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000202
203 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
204
205 if (!result_global)
206 {
207 if (log)
208 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000209
210 if (m_error_stream)
211 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
212
Sean Callanan82b74c82010-08-12 01:56:52 +0000213 return false;
214 }
215
216 // Find the metadata and follow it to the VarDecl
217
Greg Clayton8de27c72010-10-15 22:48:33 +0000218 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000219
220 if (!named_metadata)
221 {
222 if (log)
223 log->PutCString("No global metadata");
224
Sean Callanan97c924e2011-01-27 01:07:04 +0000225 if (m_error_stream)
226 m_error_stream->Printf("Internal error [IRForTarget]: No metadata\n");
227
Sean Callanan82b74c82010-08-12 01:56:52 +0000228 return false;
229 }
230
231 unsigned num_nodes = named_metadata->getNumOperands();
232 unsigned node_index;
233
234 MDNode *metadata_node = NULL;
235
236 for (node_index = 0;
237 node_index < num_nodes;
238 ++node_index)
239 {
240 metadata_node = named_metadata->getOperand(node_index);
241
242 if (metadata_node->getNumOperands() != 2)
243 continue;
244
245 if (metadata_node->getOperand(0) == result_global)
246 break;
247 }
248
249 if (!metadata_node)
250 {
251 if (log)
252 log->PutCString("Couldn't find result metadata");
Sean Callanan97c924e2011-01-27 01:07:04 +0000253
254 if (m_error_stream)
255 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is a global variable, but has no metadata\n", result_name);
256
Sean Callanan82b74c82010-08-12 01:56:52 +0000257 return false;
258 }
259
260 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
261
Greg Claytonb5037af2010-11-15 01:47:11 +0000262 lldb::addr_t result_decl_intptr = constant_int->getZExtValue();
Sean Callanan82b74c82010-08-12 01:56:52 +0000263
264 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
265
266 // Get the next available result name from m_decl_map and create the persistent
267 // variable for it
268
Sean Callanan6a925532011-01-13 08:53:35 +0000269 lldb_private::TypeFromParser result_decl_type;
270
271 if (m_result_is_pointer)
272 {
273 clang::QualType pointer_qual_type = result_decl->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000274 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
275 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000276
277 if (!pointer_pointertype)
278 {
279 if (log)
280 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000281
282 if (m_error_stream)
283 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
284
Sean Callanan6a925532011-01-13 08:53:35 +0000285 return false;
286 }
287
288 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
289
290 result_decl_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
291 &result_decl->getASTContext());
292 }
293 else
294 {
295 result_decl_type = lldb_private::TypeFromParser(result_decl->getType().getAsOpaquePtr(),
296 &result_decl->getASTContext());
297 }
298
299 m_result_name = m_decl_map->GetPersistentResultName();
300 // If the result is an Lvalue, it is emitted as a pointer; see
301 // ASTResultSynthesizer::SynthesizeBodyResult.
302 m_decl_map->AddPersistentVariable(result_decl,
303 m_result_name,
304 result_decl_type,
305 true,
306 m_result_is_pointer);
Sean Callanan82b74c82010-08-12 01:56:52 +0000307
308 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000309 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000310
311 // Construct a new result global and set up its metadata
312
Greg Clayton8de27c72010-10-15 22:48:33 +0000313 GlobalVariable *new_result_global = new GlobalVariable(llvm_module,
Sean Callanan82b74c82010-08-12 01:56:52 +0000314 result_global->getType()->getElementType(),
315 false, /* not constant */
316 GlobalValue::ExternalLinkage,
317 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000318 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000319
320 // It's too late in compilation to create a new VarDecl for this, but we don't
321 // need to. We point the metadata at the old VarDecl. This creates an odd
322 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000323 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000324 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
325 // fixed up.
326
327 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
328 result_decl_intptr,
329 false);
330
331 llvm::Value* values[2];
332 values[0] = new_result_global;
333 values[1] = new_constant_int;
334
Greg Clayton8de27c72010-10-15 22:48:33 +0000335 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanan82b74c82010-08-12 01:56:52 +0000336 named_metadata->addOperand(persistent_global_md);
337
338 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000339 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000340 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000341 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000342
343 if (result_global->hasNUses(0))
344 {
345 // We need to synthesize a store for this variable, because otherwise
346 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000347
Greg Clayton8de27c72010-10-15 22:48:33 +0000348 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000349 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
350
351 if (!first_entry_instruction)
352 return false;
353
354 if (!result_global->hasInitializer())
355 {
356 if (log)
357 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000358
359 if (m_error_stream)
360 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
361
Sean Callanan2e2db532010-09-07 22:43:19 +0000362 return false;
363 }
364
365 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000366
367 // Here we write the initializer into a result variable assuming it
368 // can be computed statically.
369
370 if (!m_has_side_effects)
371 {
372 MaybeSetConstantResult (initializer,
Sean Callanan6a925532011-01-13 08:53:35 +0000373 m_result_name,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000374 result_decl_type);
375 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000376
Greg Clayton2c344ca2011-02-05 02:28:58 +0000377 StoreInst *synthesized_store = new StoreInst(initializer,
378 new_result_global,
379 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000380
381 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000382 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000383 }
384 else
385 {
386 result_global->replaceAllUsesWith(new_result_global);
387 }
388
Sean Callanan82b74c82010-08-12 01:56:52 +0000389 result_global->eraseFromParent();
390
391 return true;
392}
393
Greg Clayton3c7feb42010-11-19 01:05:25 +0000394static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000395{
396 if (!depth)
397 return;
398
399 depth--;
400
Greg Clayton3c7feb42010-11-19 01:05:25 +0000401 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000402
Greg Clayton3c7feb42010-11-19 01:05:25 +0000403 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000404 ui != ue;
405 ++ui)
406 {
407 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
408 DebugUsers(log, *ui, depth);
409 }
410
411 log->Printf(" <End uses>");
412}
413
414bool
Greg Clayton3c7feb42010-11-19 01:05:25 +0000415IRForTarget::RewriteObjCConstString (llvm::Module &llvm_module,
416 llvm::GlobalVariable *ns_str,
417 llvm::GlobalVariable *cstr,
418 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000419{
420 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
421
Greg Clayton3c7feb42010-11-19 01:05:25 +0000422 const Type *i8_ptr_ty = Type::getInt8PtrTy(llvm_module.getContext());
423 const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(),
424 (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32);
425 const Type *i32_ty = Type::getInt32Ty(llvm_module.getContext());
426 const Type *i8_ty = Type::getInt8Ty(llvm_module.getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000427
428 if (!m_CFStringCreateWithBytes)
429 {
430 lldb::addr_t CFStringCreateWithBytes_addr;
431
432 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
433
434 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
435 {
436 if (log)
437 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
438
Sean Callanan97c924e2011-01-27 01:07:04 +0000439 if (m_error_stream)
440 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
441
Sean Callanan6ba533e2010-11-17 23:00:36 +0000442 return false;
443 }
444
445 if (log)
446 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
447
448 // Build the function type:
449 //
450 // CFStringRef CFStringCreateWithBytes (
451 // CFAllocatorRef alloc,
452 // const UInt8 *bytes,
453 // CFIndex numBytes,
454 // CFStringEncoding encoding,
455 // Boolean isExternalRepresentation
456 // );
457 //
458 // We make the following substitutions:
459 //
460 // CFStringRef -> i8*
461 // CFAllocatorRef -> i8*
462 // UInt8 * -> i8*
463 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
464 // CFStringEncoding -> i32
465 // Boolean -> i8
466
467 std::vector <const Type *> CFSCWB_arg_types;
468 CFSCWB_arg_types.push_back(i8_ptr_ty);
469 CFSCWB_arg_types.push_back(i8_ptr_ty);
470 CFSCWB_arg_types.push_back(intptr_ty);
471 CFSCWB_arg_types.push_back(i32_ty);
472 CFSCWB_arg_types.push_back(i8_ty);
473 llvm::Type *CFSCWB_ty = FunctionType::get(i8_ptr_ty, CFSCWB_arg_types, false);
474
475 // Build the constant containing the pointer to the function
476 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
477 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
478 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
479 }
480
Sean Callanan0ece5262011-02-10 22:17:53 +0000481 ConstantArray *string_array;
482
483 if (cstr)
484 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
485 else
486 string_array = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +0000487
488 SmallVector <Value*, 5> CFSCWB_arguments;
489
490 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000491 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
492 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000493 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
494 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
495
496 CFSCWB_arguments.push_back(alloc_arg);
497 CFSCWB_arguments.push_back(bytes_arg);
498 CFSCWB_arguments.push_back(numBytes_arg);
499 CFSCWB_arguments.push_back(encoding_arg);
500 CFSCWB_arguments.push_back(isExternal_arg);
501
502 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
503 CFSCWB_arguments.begin(),
504 CFSCWB_arguments.end(),
505 "CFStringCreateWithBytes",
506 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000507
Greg Clayton3c7feb42010-11-19 01:05:25 +0000508 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000509 {
510 if (log)
511 log->PutCString("Couldn't replace the NSString with the result of the call");
512
Sean Callanan97c924e2011-01-27 01:07:04 +0000513 if (m_error_stream)
514 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
515
Sean Callanan6ba533e2010-11-17 23:00:36 +0000516 return false;
517 }
518
Greg Clayton3c7feb42010-11-19 01:05:25 +0000519 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000520
521 return true;
522}
523
524bool
Greg Clayton3c7feb42010-11-19 01:05:25 +0000525IRForTarget::RewriteObjCConstStrings(Module &llvm_module, Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000526{
527 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
528
Greg Clayton3c7feb42010-11-19 01:05:25 +0000529 ValueSymbolTable& value_symbol_table = llvm_module.getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000530
Greg Clayton3c7feb42010-11-19 01:05:25 +0000531 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000532 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
533
534 if (!FirstEntryInstruction)
535 {
536 if (log)
537 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
538
Sean Callanan97c924e2011-01-27 01:07:04 +0000539 if (m_error_stream)
540 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
541
Sean Callanan6ba533e2010-11-17 23:00:36 +0000542 return false;
543 }
544
545 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
546 vi != ve;
547 ++vi)
548 {
549 if (strstr(vi->first(), "_unnamed_cfstring_"))
550 {
551 Value *nsstring_value = vi->second;
552
553 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
554
555 if (!nsstring_global)
556 {
557 if (log)
558 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000559
560 if (m_error_stream)
561 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
562
Sean Callanan6ba533e2010-11-17 23:00:36 +0000563 return false;
564 }
565
566 if (!nsstring_global->hasInitializer())
567 {
568 if (log)
569 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000570
571 if (m_error_stream)
572 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
573
Sean Callanan6ba533e2010-11-17 23:00:36 +0000574 return false;
575 }
576
577 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
578
579 if (!nsstring_struct)
580 {
581 if (log)
582 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000583
584 if (m_error_stream)
585 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
586
Sean Callanan6ba533e2010-11-17 23:00:36 +0000587 return false;
588 }
589
590 // We expect the following structure:
591 //
592 // struct {
593 // int *isa;
594 // int flags;
595 // char *str;
596 // long length;
597 // };
598
599 if (nsstring_struct->getNumOperands() != 4)
600 {
601 if (log)
602 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
Sean Callanan97c924e2011-01-27 01:07:04 +0000603
604 if (m_error_stream)
605 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
606
Sean Callanan6ba533e2010-11-17 23:00:36 +0000607 return false;
608 }
609
610 Constant *nsstring_member = nsstring_struct->getOperand(2);
611
612 if (!nsstring_member)
613 {
614 if (log)
615 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000616
617 if (m_error_stream)
618 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
619
Sean Callanan6ba533e2010-11-17 23:00:36 +0000620 return false;
621 }
622
623 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
624
625 if (!nsstring_expr)
626 {
627 if (log)
628 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +0000629
630 if (m_error_stream)
631 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
632
Sean Callanan6ba533e2010-11-17 23:00:36 +0000633 return false;
634 }
635
636 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
637 {
638 if (log)
639 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
Sean Callanan97c924e2011-01-27 01:07:04 +0000640
641 if (m_error_stream)
642 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
643
Sean Callanan6ba533e2010-11-17 23:00:36 +0000644 return false;
645 }
646
647 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
648
649 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
650
651 if (!cstr_global)
652 {
653 if (log)
654 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000655
656 if (m_error_stream)
657 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan65e2aee2010-11-20 02:06:01 +0000658
Sean Callanan6ba533e2010-11-17 23:00:36 +0000659 return false;
660 }
661
662 if (!cstr_global->hasInitializer())
663 {
664 if (log)
665 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000666
667 if (m_error_stream)
668 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
669
Sean Callanan6ba533e2010-11-17 23:00:36 +0000670 return false;
671 }
Sean Callanan0ece5262011-02-10 22:17:53 +0000672
673 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +0000674 if (!cstr_array)
675 {
676 if (log)
677 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +0000678
679 if (m_error_stream)
680 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
681
Sean Callanan6ba533e2010-11-17 23:00:36 +0000682 return false;
683 }
684
685 if (!cstr_array->isCString())
686 {
687 if (log)
688 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +0000689
690 if (m_error_stream)
691 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
692
Sean Callanan6ba533e2010-11-17 23:00:36 +0000693 return false;
694 }
Sean Callanan0ece5262011-02-10 22:17:53 +0000695 */
696
697 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000698
699 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +0000700 {
701 if (cstr_array)
702 log->Printf("Found NSString constant %s, which contains \"%s\"", vi->first(), cstr_array->getAsString().c_str());
703 else
704 log->Printf("Found NSString constant %s, which contains \"\"", vi->first());
705 }
706
707 if (!cstr_array)
708 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +0000709
Greg Clayton3c7feb42010-11-19 01:05:25 +0000710 if (!RewriteObjCConstString(llvm_module, nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +0000711 {
Sean Callanan6ba533e2010-11-17 23:00:36 +0000712 if (log)
713 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +0000714
715 // We don't print an error message here because RewriteObjCConstString has done so for us.
716
Sean Callanan6ba533e2010-11-17 23:00:36 +0000717 return false;
718 }
Sean Callanan6ba533e2010-11-17 23:00:36 +0000719 }
720 }
721
722 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
723 vi != ve;
724 ++vi)
725 {
726 if (!strcmp(vi->first(), "__CFConstantStringClassReference"))
727 {
728 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
729
730 if (!gv)
731 {
732 if (log)
733 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000734
735 if (m_error_stream)
736 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
737
Sean Callanan6ba533e2010-11-17 23:00:36 +0000738 return false;
739 }
740
741 gv->eraseFromParent();
742
743 break;
744 }
745 }
746
747 return true;
748}
749
Greg Clayton3c7feb42010-11-19 01:05:25 +0000750static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +0000751{
Greg Clayton3c7feb42010-11-19 01:05:25 +0000752 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +0000753
Greg Clayton3c7feb42010-11-19 01:05:25 +0000754 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +0000755 return false;
756
757 return true;
758}
759
Sean Callanan97c924e2011-01-27 01:07:04 +0000760// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +0000761bool
Greg Clayton3c7feb42010-11-19 01:05:25 +0000762IRForTarget::RewriteObjCSelector (Instruction* selector_load, Module &llvm_module)
Sean Callananf5857a02010-07-31 01:32:05 +0000763{
Greg Claytone005f2c2010-11-06 01:53:30 +0000764 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000765
766 LoadInst *load = dyn_cast<LoadInst>(selector_load);
767
768 if (!load)
769 return false;
770
771 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
772 //
773 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
774 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
775 //
776 // where %obj is the object pointer and %tmp is the selector.
777 //
Greg Clayton3c7feb42010-11-19 01:05:25 +0000778 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
779 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +0000780
781 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
782
783 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
784
785 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
786 return false;
787
788 Constant *osr_initializer = _objc_selector_references_->getInitializer();
789
790 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
791
792 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
793 return false;
794
795 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
796
797 if (!osr_initializer_base)
798 return false;
799
800 // Find the string's initializer (a ConstantArray) and get the string from it
801
802 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
803
804 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
805 return false;
806
807 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
808
809 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
810
811 if (!omvn_initializer_array->isString())
812 return false;
813
814 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
815
816 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000817 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000818
819 // Construct a call to sel_registerName
820
821 if (!m_sel_registerName)
822 {
Greg Claytonb5037af2010-11-15 01:47:11 +0000823 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000824
Greg Clayton8de27c72010-10-15 22:48:33 +0000825 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +0000826 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +0000827 return false;
828
Sean Callananc2c6f772010-10-26 00:31:56 +0000829 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000830 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +0000831
Sean Callananf5857a02010-07-31 01:32:05 +0000832 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
833
834 // The below code would be "more correct," but in actuality what's required is uint8_t*
Greg Clayton3c7feb42010-11-19 01:05:25 +0000835 //Type *sel_type = StructType::get(llvm_module.getContext());
Sean Callananf5857a02010-07-31 01:32:05 +0000836 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Greg Clayton3c7feb42010-11-19 01:05:25 +0000837 const Type *sel_ptr_type = Type::getInt8PtrTy(llvm_module.getContext());
Sean Callananf5857a02010-07-31 01:32:05 +0000838
839 std::vector <const Type *> srN_arg_types;
Greg Clayton3c7feb42010-11-19 01:05:25 +0000840 srN_arg_types.push_back(Type::getInt8PtrTy(llvm_module.getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +0000841 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
842
843 // Build the constant containing the pointer to the function
Greg Clayton3c7feb42010-11-19 01:05:25 +0000844 const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(),
845 (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +0000846 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +0000847 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000848 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
849 }
850
851 SmallVector <Value*, 1> srN_arguments;
852
Greg Clayton3c7feb42010-11-19 01:05:25 +0000853 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(llvm_module.getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +0000854
855 srN_arguments.push_back(omvn_pointer);
856
857 CallInst *srN_call = CallInst::Create(m_sel_registerName,
858 srN_arguments.begin(),
859 srN_arguments.end(),
Sean Callanan6ba533e2010-11-17 23:00:36 +0000860 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +0000861 selector_load);
862
863 // Replace the load with the call in all users
864
865 selector_load->replaceAllUsesWith(srN_call);
866
867 selector_load->eraseFromParent();
868
869 return true;
870}
871
872bool
Greg Clayton3c7feb42010-11-19 01:05:25 +0000873IRForTarget::RewriteObjCSelectors (Module &llvm_module, BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +0000874{
Greg Claytone005f2c2010-11-06 01:53:30 +0000875 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000876
877 BasicBlock::iterator ii;
878
879 typedef SmallVector <Instruction*, 2> InstrList;
880 typedef InstrList::iterator InstrIterator;
881
882 InstrList selector_loads;
883
Greg Clayton3c7feb42010-11-19 01:05:25 +0000884 for (ii = basic_block.begin();
885 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +0000886 ++ii)
887 {
888 Instruction &inst = *ii;
889
890 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +0000891 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +0000892 selector_loads.push_back(&inst);
893 }
894
895 InstrIterator iter;
896
897 for (iter = selector_loads.begin();
898 iter != selector_loads.end();
899 ++iter)
900 {
Greg Clayton3c7feb42010-11-19 01:05:25 +0000901 if (!RewriteObjCSelector(*iter, llvm_module))
Sean Callananf5857a02010-07-31 01:32:05 +0000902 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000903 if (m_error_stream)
904 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
905
Sean Callananf5857a02010-07-31 01:32:05 +0000906 if(log)
907 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +0000908
Sean Callananf5857a02010-07-31 01:32:05 +0000909 return false;
910 }
911 }
912
913 return true;
914}
915
Sean Callanan97c924e2011-01-27 01:07:04 +0000916// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +0000917bool
Greg Clayton3c7feb42010-11-19 01:05:25 +0000918IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc,
919 llvm::Module &llvm_module)
Sean Callanana48fe162010-08-11 03:57:18 +0000920{
Sean Callanan97678d12011-01-13 21:23:32 +0000921 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
922
Sean Callanana48fe162010-08-11 03:57:18 +0000923 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
924
925 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
926
927 if (!alloc_md || !alloc_md->getNumOperands())
928 return false;
929
930 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
931
932 if (!constant_int)
933 return false;
934
935 // We attempt to register this as a new persistent variable with the DeclMap.
936
937 uintptr_t ptr = constant_int->getZExtValue();
938
Sean Callanan82b74c82010-08-12 01:56:52 +0000939 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000940
Sean Callanan82b74c82010-08-12 01:56:52 +0000941 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
942 &decl->getASTContext());
943
Greg Clayton8de27c72010-10-15 22:48:33 +0000944 StringRef decl_name (decl->getName());
945 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +0000946 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +0000947 return false;
948
Sean Callanan97678d12011-01-13 21:23:32 +0000949 GlobalVariable *persistent_global = new GlobalVariable(llvm_module,
950 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +0000951 false, /* not constant */
952 GlobalValue::ExternalLinkage,
953 NULL, /* no initializer */
954 alloc->getName().str().c_str());
955
956 // What we're going to do here is make believe this was a regular old external
957 // variable. That means we need to make the metadata valid.
958
Greg Clayton8de27c72010-10-15 22:48:33 +0000959 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +0000960
961 llvm::Value* values[2];
962 values[0] = persistent_global;
963 values[1] = constant_int;
964
Greg Clayton8de27c72010-10-15 22:48:33 +0000965 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +0000966 named_metadata->addOperand(persistent_global_md);
967
Sean Callanan97678d12011-01-13 21:23:32 +0000968 // Now, since the variable is a pointer variable, we will drop in a load of that
969 // pointer variable.
970
971 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
972
973 if (log)
974 log->Printf("Replacing \"%s\" with \"%s\"",
975 PrintValue(alloc).c_str(),
976 PrintValue(persistent_load).c_str());
977
978 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +0000979 alloc->eraseFromParent();
980
981 return true;
982}
983
984bool
Greg Clayton3c7feb42010-11-19 01:05:25 +0000985IRForTarget::RewritePersistentAllocs(llvm::Module &llvm_module, llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +0000986{
Sean Callanane8a59a82010-09-13 21:34:21 +0000987 if (!m_resolve_vars)
988 return true;
989
Greg Claytone005f2c2010-11-06 01:53:30 +0000990 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +0000991
992 BasicBlock::iterator ii;
993
994 typedef SmallVector <Instruction*, 2> InstrList;
995 typedef InstrList::iterator InstrIterator;
996
997 InstrList pvar_allocs;
998
Greg Clayton3c7feb42010-11-19 01:05:25 +0000999 for (ii = basic_block.begin();
1000 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001001 ++ii)
1002 {
1003 Instruction &inst = *ii;
1004
1005 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001006 {
1007 llvm::StringRef alloc_name = alloc->getName();
1008
1009 if (alloc_name.startswith("$") &&
1010 !alloc_name.startswith("$__lldb"))
1011 {
1012 if (alloc_name.find_first_of("0123456789") == 1)
1013 {
1014 if (log)
1015 log->Printf("Rejecting a numeric persistent variable.");
1016
Sean Callanan97c924e2011-01-27 01:07:04 +00001017 if (m_error_stream)
1018 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1019
Sean Callanan237e4742011-01-21 22:30:25 +00001020 return false;
1021 }
1022
Sean Callanana48fe162010-08-11 03:57:18 +00001023 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001024 }
1025 }
Sean Callanana48fe162010-08-11 03:57:18 +00001026 }
1027
1028 InstrIterator iter;
1029
1030 for (iter = pvar_allocs.begin();
1031 iter != pvar_allocs.end();
1032 ++iter)
1033 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001034 if (!RewritePersistentAlloc(*iter, llvm_module))
Sean Callanana48fe162010-08-11 03:57:18 +00001035 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001036 if (m_error_stream)
1037 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1038
Sean Callanana48fe162010-08-11 03:57:18 +00001039 if(log)
1040 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001041
Sean Callanana48fe162010-08-11 03:57:18 +00001042 return false;
1043 }
1044 }
1045
1046 return true;
1047}
1048
Sean Callanan8bce6652010-07-13 21:41:46 +00001049static clang::NamedDecl *
Greg Clayton3c7feb42010-11-19 01:05:25 +00001050DeclForGlobalValue(Module &module, GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +00001051{
1052 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
1053
1054 if (!named_metadata)
1055 return NULL;
1056
1057 unsigned num_nodes = named_metadata->getNumOperands();
1058 unsigned node_index;
1059
1060 for (node_index = 0;
1061 node_index < num_nodes;
1062 ++node_index)
1063 {
1064 MDNode *metadata_node = named_metadata->getOperand(node_index);
1065
1066 if (!metadata_node)
1067 return NULL;
1068
1069 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +00001070 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +00001071
1072 if (metadata_node->getOperand(0) != global_value)
1073 continue;
1074
1075 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
1076
1077 if (!constant_int)
1078 return NULL;
1079
1080 uintptr_t ptr = constant_int->getZExtValue();
1081
1082 return reinterpret_cast<clang::NamedDecl *>(ptr);
1083 }
1084
1085 return NULL;
1086}
1087
Sean Callanan97c924e2011-01-27 01:07:04 +00001088// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001089bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001090IRForTarget::MaybeHandleVariable (Module &llvm_module, Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001091{
Greg Claytone005f2c2010-11-06 01:53:30 +00001092 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001093
1094 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001095 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001096
Greg Clayton8de27c72010-10-15 22:48:33 +00001097 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001098 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001099 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001100 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001101 default:
1102 break;
1103 case Instruction::GetElementPtr:
1104 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001105 Value *s = constant_expr->getOperand(0);
Sean Callanan48443652010-12-02 19:47:57 +00001106 if (!MaybeHandleVariable(llvm_module, s))
1107 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001108 }
1109 }
Sean Callananf921cf52010-12-03 19:51:05 +00001110 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001111 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001112 clang::NamedDecl *named_decl = DeclForGlobalValue(llvm_module, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001113
Sean Callananf5857a02010-07-31 01:32:05 +00001114 if (!named_decl)
1115 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001116 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001117 return true;
1118
Sean Callanan7cd46742010-12-06 00:56:39 +00001119 if (!global_variable->hasExternalLinkage())
1120 return true;
1121
Sean Callananf5857a02010-07-31 01:32:05 +00001122 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001123 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001124
Sean Callananf5857a02010-07-31 01:32:05 +00001125 return false;
1126 }
1127
Greg Clayton8de27c72010-10-15 22:48:33 +00001128 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001129
Sean Callanan771131d2010-09-30 21:18:25 +00001130 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001131 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001132
1133 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001134 {
Sean Callanan771131d2010-09-30 21:18:25 +00001135 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001136 ast_context = &value_decl->getASTContext();
1137 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001138 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001139 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001140 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001141 }
Sean Callanan771131d2010-09-30 21:18:25 +00001142
Sean Callanan6a925532011-01-13 08:53:35 +00001143 clang::QualType qual_type;
1144 const Type *value_type;
1145
Sean Callanan97678d12011-01-13 21:23:32 +00001146 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001147 {
1148 // The $__lldb_expr_result name indicates the the return value has allocated as
1149 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1150 // accesses to this static variable need to be redirected to the result of dereferencing
1151 // a pointer that is passed in as one of the arguments.
1152 //
1153 // Consequently, when reporting the size of the type, we report a pointer type pointing
1154 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001155 //
1156 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001157
Sean Callanan6a925532011-01-13 08:53:35 +00001158 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1159 value_type = PointerType::get(global_variable->getType(), 0);
1160 }
1161 else
1162 {
1163 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1164 value_type = global_variable->getType();
1165 }
Sean Callanan771131d2010-09-30 21:18:25 +00001166
1167 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1168 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001169
Sean Callanan771131d2010-09-30 21:18:25 +00001170 if (log)
Sean Callanan97678d12011-01-13 21:23:32 +00001171 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %d, align %d]",
Sean Callanan771131d2010-09-30 21:18:25 +00001172 name.c_str(),
1173 qual_type.getAsString().c_str(),
1174 PrintType(value_type).c_str(),
1175 value_size,
1176 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001177
Sean Callanan8bce6652010-07-13 21:41:46 +00001178
Sean Callanan8c127202010-08-23 23:09:38 +00001179 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001180 lldb_private::ConstString (name.c_str()),
1181 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001182 value_size,
1183 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +00001184 return false;
1185 }
Sean Callananf3143b72010-12-03 03:02:31 +00001186 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001187 {
1188 if (log)
1189 log->Printf("Function pointers aren't handled right now");
1190
1191 return false;
1192 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001193
1194 return true;
1195}
1196
Sean Callanan97c924e2011-01-27 01:07:04 +00001197// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001198bool
Sean Callananc7674af2011-01-17 23:42:46 +00001199IRForTarget::HandleSymbol (Module &llvm_module,
1200 Value *symbol)
1201{
1202 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1203
1204 lldb_private::ConstString name(symbol->getName().str().c_str());
1205
1206 uint64_t symbol_addr;
1207
1208 if (!m_decl_map->GetSymbolAddress (name, symbol_addr))
1209 {
1210 if (log)
1211 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1212
1213 return false;
1214 }
1215
1216 if (log)
1217 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1218
1219 const Type *symbol_type = symbol->getType();
1220
1221 const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(),
1222 (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32);
1223
1224 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1225
1226 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1227
1228 if (log)
1229 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1230
1231 symbol->replaceAllUsesWith(symbol_addr_ptr);
1232
1233 return true;
1234}
1235
1236bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001237IRForTarget::MaybeHandleCallArguments (Module &llvm_module, CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001238{
Sean Callanan48443652010-12-02 19:47:57 +00001239 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1240
1241 if (log)
1242 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001243
Sean Callanan6ba533e2010-11-17 23:00:36 +00001244 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001245 op_index < num_ops;
1246 ++op_index)
Greg Clayton3c7feb42010-11-19 01:05:25 +00001247 if (!MaybeHandleVariable(llvm_module, Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001248 {
1249 if (m_error_stream)
1250 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1251
Sean Callanandc27aba2010-10-05 22:26:43 +00001252 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001253 }
1254
Sean Callanandc27aba2010-10-05 22:26:43 +00001255 return true;
1256}
1257
1258bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001259IRForTarget::MaybeHandleCall (Module &llvm_module, CallInst *llvm_call_inst)
Sean Callananba992c52010-07-27 02:07:53 +00001260{
Greg Claytone005f2c2010-11-06 01:53:30 +00001261 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananba992c52010-07-27 02:07:53 +00001262
Greg Clayton8de27c72010-10-15 22:48:33 +00001263 Function *fun = llvm_call_inst->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +00001264
1265 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +00001266 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001267 Value *val = llvm_call_inst->getCalledValue();
Sean Callanan65af7342010-09-08 20:04:08 +00001268
1269 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
Sean Callanand5b3c352011-01-27 04:42:51 +00001270 LoadInst *load_inst = dyn_cast<LoadInst>(val);
Sean Callanan65af7342010-09-08 20:04:08 +00001271
1272 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
1273 {
1274 fun = dyn_cast<Function>(const_expr->getOperand(0));
1275
1276 if (!fun)
Sean Callanan97c924e2011-01-27 01:07:04 +00001277 {
1278 if (m_error_stream)
1279 m_error_stream->Printf("Internal error [IRForTarget]: Called entity is a cast of something not a function\n");
1280
Sean Callanan48443652010-12-02 19:47:57 +00001281 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001282 }
Sean Callanan65af7342010-09-08 20:04:08 +00001283 }
Sean Callananc4217a62010-12-06 23:53:20 +00001284 else if (const_expr && const_expr->getOpcode() == Instruction::IntToPtr)
1285 {
1286 return true; // already resolved
1287 }
Sean Callanand5b3c352011-01-27 04:42:51 +00001288 else if (load_inst)
1289 {
1290 return true; // virtual method call
1291 }
Sean Callanan65af7342010-09-08 20:04:08 +00001292 else
1293 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001294 if (m_error_stream)
1295 m_error_stream->Printf("Internal error [IRForTarget]: Called entity is not a function\n");
1296
Sean Callanan48443652010-12-02 19:47:57 +00001297 return false;
Sean Callanan65af7342010-09-08 20:04:08 +00001298 }
1299 }
Sean Callananba992c52010-07-27 02:07:53 +00001300
Greg Clayton8de27c72010-10-15 22:48:33 +00001301 lldb_private::ConstString str;
Sean Callananc04743d2010-09-28 21:13:03 +00001302
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001303 if (fun->isIntrinsic())
Sean Callananc04743d2010-09-28 21:13:03 +00001304 {
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001305 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
Sean Callananc04743d2010-09-28 21:13:03 +00001306
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001307 switch (intrinsic_id)
1308 {
1309 default:
1310 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001311 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001312
1313 if (m_error_stream)
1314 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
1315
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001316 return false;
1317 case Intrinsic::memcpy:
Greg Clayton8de27c72010-10-15 22:48:33 +00001318 {
1319 static lldb_private::ConstString g_memcpy_str ("memcpy");
1320 str = g_memcpy_str;
1321 }
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001322 break;
1323 }
Sean Callananc04743d2010-09-28 21:13:03 +00001324
Greg Clayton8de27c72010-10-15 22:48:33 +00001325 if (log && str)
Greg Claytonb5037af2010-11-15 01:47:11 +00001326 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString());
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001327 }
1328 else
1329 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001330 str.SetCStringWithLength (fun->getName().data(), fun->getName().size());
Sean Callananc04743d2010-09-28 21:13:03 +00001331 }
1332
Greg Clayton8de27c72010-10-15 22:48:33 +00001333 clang::NamedDecl *fun_decl = DeclForGlobalValue (llvm_module, fun);
Greg Claytonb5037af2010-11-15 01:47:11 +00001334 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS;
Sean Callananf5857a02010-07-31 01:32:05 +00001335 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +00001336
Sean Callananf5857a02010-07-31 01:32:05 +00001337 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +00001338 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001339 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001340 {
Sean Callanan92aa6662010-09-07 21:49:41 +00001341 fun_value_ptr = NULL;
1342
Greg Clayton8de27c72010-10-15 22:48:33 +00001343 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +00001344 {
1345 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001346 log->Printf("Function \"%s\" had no address", str.GetCString());
Sean Callanan92aa6662010-09-07 21:49:41 +00001347
Sean Callanan97c924e2011-01-27 01:07:04 +00001348 if (m_error_stream)
1349 m_error_stream->Printf("Error [IRForTarget]: Call to a function '%s' that is not present in the target\n", str.GetCString());
1350
Sean Callanan92aa6662010-09-07 21:49:41 +00001351 return false;
1352 }
Sean Callananf5857a02010-07-31 01:32:05 +00001353 }
1354 }
1355 else
1356 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001357 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001358 {
1359 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001360 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString());
Sean Callanan97c924e2011-01-27 01:07:04 +00001361
1362 if (m_error_stream)
1363 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", str.GetCString());
1364
1365 return false;
Sean Callananf5857a02010-07-31 01:32:05 +00001366 }
Sean Callananba992c52010-07-27 02:07:53 +00001367 }
1368
1369 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001370 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +00001371
Sean Callananf5857a02010-07-31 01:32:05 +00001372 Value *fun_addr_ptr;
1373
1374 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +00001375 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001376 const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(),
1377 (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +00001378 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +00001379 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
1380 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001381 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
1382
1383 if (fun_value_ptr)
1384 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001385 }
Sean Callananf5857a02010-07-31 01:32:05 +00001386
1387 if (fun_value_ptr)
1388 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001389
Greg Clayton8de27c72010-10-15 22:48:33 +00001390 llvm_call_inst->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +00001391
Greg Clayton8de27c72010-10-15 22:48:33 +00001392 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(llvm_module.getContext(), str.GetCString());
Sean Callanane8a59a82010-09-13 21:34:21 +00001393
1394 Value *values[1];
1395 values[0] = func_name;
Greg Clayton8de27c72010-10-15 22:48:33 +00001396 MDNode *func_metadata = MDNode::get(llvm_module.getContext(), values, 1);
Sean Callanane8a59a82010-09-13 21:34:21 +00001397
Greg Clayton8de27c72010-10-15 22:48:33 +00001398 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata);
Sean Callanane8a59a82010-09-13 21:34:21 +00001399
1400 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001401 log->Printf("Set metadata for %p [%d, \"%s\"]", llvm_call_inst, func_name->isString(), func_name->getAsString().c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +00001402
Sean Callananba992c52010-07-27 02:07:53 +00001403 return true;
1404}
1405
1406bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001407IRForTarget::ResolveCalls(Module &llvm_module, BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001408{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001409 /////////////////////////////////////////////////////////////////////////
1410 // Prepare the current basic block for execution in the remote process
1411 //
1412
Sean Callanan02fbafa2010-07-27 21:39:39 +00001413 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001414
Greg Clayton3c7feb42010-11-19 01:05:25 +00001415 for (ii = basic_block.begin();
1416 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001417 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001418 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001419 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001420
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001421 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001422
Sean Callanan97c924e2011-01-27 01:07:04 +00001423 // MaybeHandleCall handles error reporting; we are silent here
Greg Clayton3c7feb42010-11-19 01:05:25 +00001424 if (call && !MaybeHandleCall(llvm_module, call))
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001425 return false;
Sean Callanan48443652010-12-02 19:47:57 +00001426
Sean Callanan97c924e2011-01-27 01:07:04 +00001427 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan48443652010-12-02 19:47:57 +00001428 if (call && !MaybeHandleCallArguments(llvm_module, call))
1429 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001430 }
1431
1432 return true;
1433}
1434
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001435bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001436IRForTarget::ResolveExternals (Module &llvm_module, Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001437{
Sean Callananae71e302010-11-18 22:21:58 +00001438 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1439
Greg Clayton3c7feb42010-11-19 01:05:25 +00001440 for (Module::global_iterator global = llvm_module.global_begin(), end = llvm_module.global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001441 global != end;
1442 ++global)
1443 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001444 if (log)
1445 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1446 (*global).getName().str().c_str(),
1447 DeclForGlobalValue(llvm_module, global));
1448
Sean Callananc7674af2011-01-17 23:42:46 +00001449 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1450 {
1451 if (!HandleSymbol(llvm_module, global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001452 {
1453 if (m_error_stream)
1454 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1455
Sean Callananc7674af2011-01-17 23:42:46 +00001456 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001457 }
Sean Callananc7674af2011-01-17 23:42:46 +00001458 }
1459 else if (DeclForGlobalValue(llvm_module, global))
1460 {
1461 if (!MaybeHandleVariable (llvm_module, global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001462 {
1463 if (m_error_stream)
1464 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1465
Sean Callananc7674af2011-01-17 23:42:46 +00001466 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001467 }
Sean Callananc7674af2011-01-17 23:42:46 +00001468 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001469 }
1470
1471 return true;
1472}
1473
Sean Callanan02fbafa2010-07-27 21:39:39 +00001474static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001475{
Sean Callanan6ba533e2010-11-17 23:00:36 +00001476 Constant *Old;
Sean Callanan45839272010-07-24 01:37:44 +00001477
Sean Callanan6ba533e2010-11-17 23:00:36 +00001478 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001479 return false;
1480
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001481 ConstantExpr *CE;
1482
1483 if ((CE = dyn_cast<ConstantExpr>(V)))
1484 {
1485 if (CE->getOpcode() != Instruction::BitCast)
1486 return false;
1487
Sean Callanan6ba533e2010-11-17 23:00:36 +00001488 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001489 }
1490
Sean Callanan6ba533e2010-11-17 23:00:36 +00001491 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001492
1493 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1494 return false;
1495
1496 return true;
1497}
1498
Greg Clayton3c7feb42010-11-19 01:05:25 +00001499static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &llvm_module)
Sean Callanan45839272010-07-24 01:37:44 +00001500{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001501 Constant* zero(ConstantInt::get(Type::getInt8Ty(llvm_module.getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00001502
1503 Value::use_iterator ui;
1504
1505 for (ui = guard_load->use_begin();
1506 ui != guard_load->use_end();
1507 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001508 {
Greg Clayton6e713402010-07-30 20:30:44 +00001509 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001510 {
1511 // do nothing for the moment
1512 }
1513 else
1514 {
1515 ui->replaceUsesOfWith(guard_load, zero);
1516 }
1517 }
Sean Callanan45839272010-07-24 01:37:44 +00001518
1519 guard_load->eraseFromParent();
1520}
1521
1522static void ExciseGuardStore(Instruction* guard_store)
1523{
1524 guard_store->eraseFromParent();
1525}
1526
1527bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001528IRForTarget::RemoveGuards(Module &llvm_module, BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00001529{
1530 ///////////////////////////////////////////////////////
1531 // Eliminate any reference to guard variables found.
1532 //
1533
Sean Callanan02fbafa2010-07-27 21:39:39 +00001534 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001535
Sean Callanan02fbafa2010-07-27 21:39:39 +00001536 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001537 typedef InstrList::iterator InstrIterator;
1538
1539 InstrList guard_loads;
1540 InstrList guard_stores;
1541
Greg Clayton3c7feb42010-11-19 01:05:25 +00001542 for (ii = basic_block.begin();
1543 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00001544 ++ii)
1545 {
1546 Instruction &inst = *ii;
1547
1548 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1549 if (isGuardVariableRef(load->getPointerOperand()))
1550 guard_loads.push_back(&inst);
1551
1552 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1553 if (isGuardVariableRef(store->getPointerOperand()))
1554 guard_stores.push_back(&inst);
1555 }
1556
1557 InstrIterator iter;
1558
1559 for (iter = guard_loads.begin();
1560 iter != guard_loads.end();
1561 ++iter)
Greg Clayton3c7feb42010-11-19 01:05:25 +00001562 TurnGuardLoadIntoZero(*iter, llvm_module);
Sean Callanan45839272010-07-24 01:37:44 +00001563
1564 for (iter = guard_stores.begin();
1565 iter != guard_stores.end();
1566 ++iter)
1567 ExciseGuardStore(*iter);
1568
1569 return true;
1570}
1571
Sean Callanan97c924e2011-01-27 01:07:04 +00001572// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001573bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001574IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00001575{
Greg Claytone005f2c2010-11-06 01:53:30 +00001576 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001577
1578 Value::use_iterator ui;
1579
Sean Callanana48fe162010-08-11 03:57:18 +00001580 SmallVector<User*, 16> users;
1581
1582 // We do this because the use list might change, invalidating our iterator.
1583 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00001584 for (ui = old_constant->use_begin();
1585 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001586 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001587 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001588
Sean Callanana48fe162010-08-11 03:57:18 +00001589 for (int i = 0;
1590 i < users.size();
1591 ++i)
1592 {
1593 User *user = users[i];
1594
Sean Callananbafd6852010-07-14 23:40:29 +00001595 if (Constant *constant = dyn_cast<Constant>(user))
1596 {
1597 // synthesize a new non-constant equivalent of the constant
1598
1599 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1600 {
1601 switch (constant_expr->getOpcode())
1602 {
1603 default:
1604 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001605 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001606 return false;
1607 case Instruction::BitCast:
1608 {
1609 // UnaryExpr
1610 // OperandList[0] is value
1611
1612 Value *s = constant_expr->getOperand(0);
1613
Greg Clayton3c7feb42010-11-19 01:05:25 +00001614 if (s == old_constant)
1615 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00001616
Greg Clayton3c7feb42010-11-19 01:05:25 +00001617 BitCastInst *bit_cast(new BitCastInst(s, old_constant->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00001618
Greg Clayton3c7feb42010-11-19 01:05:25 +00001619 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00001620 }
1621 break;
1622 case Instruction::GetElementPtr:
1623 {
1624 // GetElementPtrConstantExpr
1625 // OperandList[0] is base
1626 // OperandList[1]... are indices
1627
1628 Value *ptr = constant_expr->getOperand(0);
1629
Greg Clayton3c7feb42010-11-19 01:05:25 +00001630 if (ptr == old_constant)
1631 ptr = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00001632
1633 SmallVector<Value*, 16> indices;
1634
1635 unsigned operand_index;
1636 unsigned num_operands = constant_expr->getNumOperands();
1637
1638 for (operand_index = 1;
1639 operand_index < num_operands;
1640 ++operand_index)
1641 {
1642 Value *operand = constant_expr->getOperand(operand_index);
1643
Greg Clayton3c7feb42010-11-19 01:05:25 +00001644 if (operand == old_constant)
1645 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00001646
1647 indices.push_back(operand);
1648 }
1649
Greg Clayton3c7feb42010-11-19 01:05:25 +00001650 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00001651
Greg Clayton3c7feb42010-11-19 01:05:25 +00001652 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00001653 }
1654 break;
1655 }
1656 }
1657 else
1658 {
1659 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001660 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001661 return false;
1662 }
1663 }
1664 else
1665 {
1666 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00001667 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00001668 }
1669 }
1670
1671 return true;
1672}
1673
Sean Callanan8bce6652010-07-13 21:41:46 +00001674bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001675IRForTarget::ReplaceVariables (Module &llvm_module, Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00001676{
Sean Callanane8a59a82010-09-13 21:34:21 +00001677 if (!m_resolve_vars)
1678 return true;
1679
Greg Claytone005f2c2010-11-06 01:53:30 +00001680 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00001681
1682 m_decl_map->DoStructLayout();
1683
1684 if (log)
1685 log->Printf("Element arrangement:");
1686
1687 uint32_t num_elements;
1688 uint32_t element_index;
1689
1690 size_t size;
1691 off_t alignment;
1692
1693 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
1694 return false;
1695
Greg Clayton3c7feb42010-11-19 01:05:25 +00001696 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00001697
Greg Clayton3c7feb42010-11-19 01:05:25 +00001698 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00001699 {
1700 if (m_error_stream)
1701 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
1702
Sean Callanan8bce6652010-07-13 21:41:46 +00001703 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001704 }
1705
Sean Callanan02fbafa2010-07-27 21:39:39 +00001706 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00001707
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001708 if (argument->getName().equals("this"))
1709 {
1710 ++iter;
1711
Greg Clayton3c7feb42010-11-19 01:05:25 +00001712 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00001713 {
1714 if (m_error_stream)
1715 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
1716
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001717 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001718 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001719
1720 argument = iter;
1721 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00001722 else if (argument->getName().equals("self"))
1723 {
1724 ++iter;
1725
1726 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00001727 {
1728 if (m_error_stream)
1729 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
1730
Sean Callanan3aa7da52010-12-13 22:46:15 +00001731 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001732 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00001733
1734 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00001735 {
1736 if (m_error_stream)
1737 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
1738
Sean Callanan3aa7da52010-12-13 22:46:15 +00001739 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001740 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00001741
1742 ++iter;
1743
1744 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00001745 {
1746 if (m_error_stream)
1747 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
1748
Sean Callanan3aa7da52010-12-13 22:46:15 +00001749 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001750 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00001751
1752 argument = iter;
1753 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001754
Greg Clayton8de27c72010-10-15 22:48:33 +00001755 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00001756 {
1757 if (m_error_stream)
1758 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
1759
Sean Callanan8bce6652010-07-13 21:41:46 +00001760 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001761 }
1762
Sean Callanan8bce6652010-07-13 21:41:46 +00001763 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001764 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00001765
Greg Clayton3c7feb42010-11-19 01:05:25 +00001766 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001767 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00001768
Sean Callanan6ba533e2010-11-17 23:00:36 +00001769 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00001770 {
1771 if (m_error_stream)
1772 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
1773
Sean Callanan8bce6652010-07-13 21:41:46 +00001774 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001775 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001776
Greg Clayton3c7feb42010-11-19 01:05:25 +00001777 LLVMContext &context(llvm_module.getContext());
Sean Callanan8bce6652010-07-13 21:41:46 +00001778 const IntegerType *offset_type(Type::getInt32Ty(context));
1779
1780 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00001781 {
1782 if (m_error_stream)
1783 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
1784
Sean Callanan8bce6652010-07-13 21:41:46 +00001785 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001786 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001787
1788 for (element_index = 0; element_index < num_elements; ++element_index)
1789 {
1790 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001791 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +00001792 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00001793 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00001794
Sean Callanan45690fe2010-08-30 22:17:16 +00001795 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00001796 {
1797 if (m_error_stream)
1798 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
1799
Sean Callanan8bce6652010-07-13 21:41:46 +00001800 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001801 }
1802
Sean Callanan8bce6652010-07-13 21:41:46 +00001803 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001804 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00001805 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00001806 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00001807 PrintValue(value, true).c_str(),
1808 offset);
1809
1810 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
Sean Callanan6ba533e2010-11-17 23:00:36 +00001811 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00001812
1813 Value *replacement;
Sean Callanan8bce6652010-07-13 21:41:46 +00001814
Sean Callanan6a925532011-01-13 08:53:35 +00001815 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
1816 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
1817 // entry in order to produce the static variable that the AST thinks it is accessing.
1818 if (name == m_result_name && !m_result_is_pointer)
1819 {
1820 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
1821
1822 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
1823
1824 replacement = load;
1825 }
Sean Callananbafd6852010-07-14 23:40:29 +00001826 else
Sean Callanan6a925532011-01-13 08:53:35 +00001827 {
1828 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
1829
1830 replacement = bit_cast;
1831 }
1832
1833 if (Constant *constant = dyn_cast<Constant>(value))
1834 UnfoldConstant(constant, replacement, FirstEntryInstruction);
1835 else
1836 value->replaceAllUsesWith(replacement);
Sean Callananb51ee982010-11-02 23:51:17 +00001837
1838 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1839 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00001840 }
1841
1842 if (log)
1843 log->Printf("Total structure [align %d, size %d]", alignment, size);
1844
1845 return true;
1846}
1847
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001848bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001849IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001850{
Greg Claytone005f2c2010-11-06 01:53:30 +00001851 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001852
Greg Clayton3c7feb42010-11-19 01:05:25 +00001853 Function* function = llvm_module.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001854
1855 if (!function)
1856 {
1857 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001858 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001859
1860 if (m_error_stream)
1861 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the mdoule", m_func_name.c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00001862
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001863 return false;
1864 }
1865
Sean Callanan02fbafa2010-07-27 21:39:39 +00001866 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001867
Sean Callanan05a5a1b2010-12-16 03:17:46 +00001868 m_has_side_effects = HasSideEffects(llvm_module, *function);
1869
Sean Callanan82b74c82010-08-12 01:56:52 +00001870 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00001871 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00001872 //
1873
Greg Clayton3c7feb42010-11-19 01:05:25 +00001874 if (!CreateResultVariable(llvm_module, *function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001875 {
1876 if (log)
1877 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001878
1879 // CreateResultVariable() reports its own errors, so we don't do so here
1880
Sean Callanan82b74c82010-08-12 01:56:52 +00001881 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001882 }
Sean Callanan82b74c82010-08-12 01:56:52 +00001883
Sean Callanan6ba533e2010-11-17 23:00:36 +00001884 ///////////////////////////////////////////////////////////////////////////////
1885 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
1886 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00001887
Greg Clayton3c7feb42010-11-19 01:05:25 +00001888 if (!RewriteObjCConstStrings(llvm_module, *function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001889 {
1890 if (log)
1891 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001892
1893 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
1894
Sean Callanan6ba533e2010-11-17 23:00:36 +00001895 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001896 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001897
Sean Callananf5857a02010-07-31 01:32:05 +00001898 //////////////////////////////////
1899 // Run basic-block level passes
1900 //
1901
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001902 for (bbi = function->begin();
1903 bbi != function->end();
1904 ++bbi)
1905 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001906 if (!RemoveGuards(llvm_module, *bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001907 {
1908 if (log)
1909 log->Printf("RemoveGuards() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001910
1911 // RemoveGuards() reports its own errors, so we don't do so here
1912
Sean Callanan8c127202010-08-23 23:09:38 +00001913 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001914 }
Sean Callanan8c127202010-08-23 23:09:38 +00001915
Greg Clayton3c7feb42010-11-19 01:05:25 +00001916 if (!RewritePersistentAllocs(llvm_module, *bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001917 {
1918 if (log)
1919 log->Printf("RewritePersistentAllocs() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001920
1921 // RewritePersistentAllocs() reports its own errors, so we don't do so here
1922
Sean Callananf5857a02010-07-31 01:32:05 +00001923 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001924 }
Sean Callananf5857a02010-07-31 01:32:05 +00001925
Greg Clayton3c7feb42010-11-19 01:05:25 +00001926 if (!RewriteObjCSelectors(llvm_module, *bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001927 {
1928 if (log)
1929 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001930
1931 // RewriteObjCSelectors() reports its own errors, so we don't do so here
1932
Sean Callanana48fe162010-08-11 03:57:18 +00001933 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001934 }
Sean Callanana48fe162010-08-11 03:57:18 +00001935
Greg Clayton3c7feb42010-11-19 01:05:25 +00001936 if (!ResolveCalls(llvm_module, *bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001937 {
1938 if (log)
1939 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001940
1941 // ResolveCalls() reports its own errors, so we don't do so here
1942
Sean Callanan8bce6652010-07-13 21:41:46 +00001943 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001944 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001945 }
1946
Sean Callanan771131d2010-09-30 21:18:25 +00001947 ///////////////////////////////
1948 // Run function-level passes
1949 //
1950
Greg Clayton3c7feb42010-11-19 01:05:25 +00001951 if (!ResolveExternals(llvm_module, *function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001952 {
1953 if (log)
1954 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001955
1956 // ResolveExternals() reports its own errors, so we don't do so here
1957
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001958 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001959 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001960
Greg Clayton3c7feb42010-11-19 01:05:25 +00001961 if (!ReplaceVariables(llvm_module, *function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00001962 {
1963 if (log)
1964 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00001965
1966 // ReplaceVariables() reports its own errors, so we don't do so here
1967
Sean Callanan771131d2010-09-30 21:18:25 +00001968 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001969 }
Sean Callanan771131d2010-09-30 21:18:25 +00001970
Sean Callanan8bce6652010-07-13 21:41:46 +00001971 if (log)
1972 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001973 std::string s;
1974 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001975
Greg Clayton3c7feb42010-11-19 01:05:25 +00001976 llvm_module.print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00001977
1978 oss.flush();
1979
Greg Claytonb5037af2010-11-15 01:47:11 +00001980 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001981 }
1982
1983 return true;
1984}
1985
1986void
Greg Clayton3c7feb42010-11-19 01:05:25 +00001987IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001988{
1989}
1990
1991PassManagerType
1992IRForTarget::getPotentialPassManagerType() const
1993{
1994 return PMT_ModulePassManager;
1995}