blob: 6dd72e7e95b59fcc014c7f6042794523eda07892 [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
35IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +000036 bool resolve_vars,
Sean Callanan65dafa82010-08-27 01:01:44 +000037 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000038 ModulePass(ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000039 m_decl_map(decl_map),
Sean Callanan6ba533e2010-11-17 23:00:36 +000040 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000041 m_sel_registerName(NULL),
Sean Callanane8a59a82010-09-13 21:34:21 +000042 m_func_name(func_name),
43 m_resolve_vars(resolve_vars)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000044{
45}
46
Sean Callanan771131d2010-09-30 21:18:25 +000047/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000048
49static std::string
Sean Callanan771131d2010-09-30 21:18:25 +000050PrintValue(const Value *V, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000051{
52 std::string s;
53 raw_string_ostream rso(s);
54 V->print(rso);
55 rso.flush();
56 if (truncate)
57 s.resize(s.length() - 1);
58 return s;
59}
60
Sean Callanan771131d2010-09-30 21:18:25 +000061static std::string
62PrintType(const Type *T, bool truncate = false)
63{
64 std::string s;
65 raw_string_ostream rso(s);
66 T->print(rso);
67 rso.flush();
68 if (truncate)
69 s.resize(s.length() - 1);
70 return s;
71}
72
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000073IRForTarget::~IRForTarget()
74{
75}
76
Sean Callanan82b74c82010-08-12 01:56:52 +000077bool
Greg Clayton8de27c72010-10-15 22:48:33 +000078IRForTarget::createResultVariable (llvm::Module &llvm_module, llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +000079{
Greg Claytone005f2c2010-11-06 01:53:30 +000080 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +000081
Sean Callanane8a59a82010-09-13 21:34:21 +000082 if (!m_resolve_vars)
83 return true;
84
85 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000086
Greg Clayton8de27c72010-10-15 22:48:33 +000087 ValueSymbolTable& value_symbol_table = llvm_module.getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000088
89 const char *result_name = NULL;
90
91 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
92 vi != ve;
93 ++vi)
94 {
Greg Clayton8de27c72010-10-15 22:48:33 +000095 if (strstr(vi->first(), "$__lldb_expr_result") &&
Sean Callananc04743d2010-09-28 21:13:03 +000096 !strstr(vi->first(), "GV"))
97 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000098 result_name = vi->first();
Sean Callananc04743d2010-09-28 21:13:03 +000099 break;
100 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000101 }
102
103 if (!result_name)
104 {
105 if (log)
106 log->PutCString("Couldn't find result variable");
107
108 return true;
109 }
110
Sean Callananc04743d2010-09-28 21:13:03 +0000111 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000112 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000113
Greg Clayton8de27c72010-10-15 22:48:33 +0000114 Value *result_value = llvm_module.getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000115
116 if (!result_value)
117 {
118 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000119 log->PutCString("Result variable had no data");
Sean Callanane8a59a82010-09-13 21:34:21 +0000120
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000121 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000122 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000123
Sean Callanan82b74c82010-08-12 01:56:52 +0000124 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000125 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000126
127 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
128
129 if (!result_global)
130 {
131 if (log)
132 log->PutCString("Result variable isn't a GlobalVariable");
133 return false;
134 }
135
136 // Find the metadata and follow it to the VarDecl
137
Greg Clayton8de27c72010-10-15 22:48:33 +0000138 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000139
140 if (!named_metadata)
141 {
142 if (log)
143 log->PutCString("No global metadata");
144
145 return false;
146 }
147
148 unsigned num_nodes = named_metadata->getNumOperands();
149 unsigned node_index;
150
151 MDNode *metadata_node = NULL;
152
153 for (node_index = 0;
154 node_index < num_nodes;
155 ++node_index)
156 {
157 metadata_node = named_metadata->getOperand(node_index);
158
159 if (metadata_node->getNumOperands() != 2)
160 continue;
161
162 if (metadata_node->getOperand(0) == result_global)
163 break;
164 }
165
166 if (!metadata_node)
167 {
168 if (log)
169 log->PutCString("Couldn't find result metadata");
170 return false;
171 }
172
173 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
174
Greg Claytonb5037af2010-11-15 01:47:11 +0000175 lldb::addr_t result_decl_intptr = constant_int->getZExtValue();
Sean Callanan82b74c82010-08-12 01:56:52 +0000176
177 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
178
179 // Get the next available result name from m_decl_map and create the persistent
180 // variable for it
181
182 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
183 &result_decl->getASTContext());
Greg Clayton8de27c72010-10-15 22:48:33 +0000184
185 lldb_private::ConstString new_result_name (m_decl_map->GetPersistentResultName());
186 m_decl_map->AddPersistentVariable(result_decl, new_result_name, result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000187
188 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000189 log->Printf("Creating a new result global: \"%s\"", new_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000190
191 // Construct a new result global and set up its metadata
192
Greg Clayton8de27c72010-10-15 22:48:33 +0000193 GlobalVariable *new_result_global = new GlobalVariable(llvm_module,
Sean Callanan82b74c82010-08-12 01:56:52 +0000194 result_global->getType()->getElementType(),
195 false, /* not constant */
196 GlobalValue::ExternalLinkage,
197 NULL, /* no initializer */
Greg Clayton8de27c72010-10-15 22:48:33 +0000198 new_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000199
200 // It's too late in compilation to create a new VarDecl for this, but we don't
201 // need to. We point the metadata at the old VarDecl. This creates an odd
202 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000203 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000204 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
205 // fixed up.
206
207 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
208 result_decl_intptr,
209 false);
210
211 llvm::Value* values[2];
212 values[0] = new_result_global;
213 values[1] = new_constant_int;
214
Greg Clayton8de27c72010-10-15 22:48:33 +0000215 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanan82b74c82010-08-12 01:56:52 +0000216 named_metadata->addOperand(persistent_global_md);
217
218 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000219 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000220 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000221 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000222
223 if (result_global->hasNUses(0))
224 {
225 // We need to synthesize a store for this variable, because otherwise
226 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000227
Greg Clayton8de27c72010-10-15 22:48:33 +0000228 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000229 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
230
231 if (!first_entry_instruction)
232 return false;
233
234 if (!result_global->hasInitializer())
235 {
236 if (log)
237 log->Printf("Couldn't find initializer for unused variable");
238 return false;
239 }
240
241 Constant *initializer = result_global->getInitializer();
242
243 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
244 new_result_global,
245 first_entry_instruction);
246
247 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000248 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000249 }
250 else
251 {
252 result_global->replaceAllUsesWith(new_result_global);
253 }
254
Sean Callanan82b74c82010-08-12 01:56:52 +0000255 result_global->eraseFromParent();
256
257 return true;
258}
259
Sean Callanan6ba533e2010-11-17 23:00:36 +0000260static void DebugUsers(lldb::LogSP &log, Value *V, uint8_t depth)
261{
262 if (!depth)
263 return;
264
265 depth--;
266
267 log->Printf(" <Begin %d users>", V->getNumUses());
268
269 for (Value::use_iterator ui = V->use_begin(), ue = V->use_end();
270 ui != ue;
271 ++ui)
272 {
273 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
274 DebugUsers(log, *ui, depth);
275 }
276
277 log->Printf(" <End uses>");
278}
279
280bool
281IRForTarget::rewriteObjCConstString(llvm::Module &M,
282 llvm::GlobalVariable *NSStr,
283 llvm::GlobalVariable *CStr,
284 Instruction *FirstEntryInstruction)
285{
286 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
287
288 const Type *i8_ptr_ty = Type::getInt8PtrTy(M.getContext());
289 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
290 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
291 const Type *i32_ty = Type::getInt32Ty(M.getContext());
292 const Type *i8_ty = Type::getInt8Ty(M.getContext());
293
294 if (!m_CFStringCreateWithBytes)
295 {
296 lldb::addr_t CFStringCreateWithBytes_addr;
297
298 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
299
300 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
301 {
302 if (log)
303 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
304
305 return false;
306 }
307
308 if (log)
309 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
310
311 // Build the function type:
312 //
313 // CFStringRef CFStringCreateWithBytes (
314 // CFAllocatorRef alloc,
315 // const UInt8 *bytes,
316 // CFIndex numBytes,
317 // CFStringEncoding encoding,
318 // Boolean isExternalRepresentation
319 // );
320 //
321 // We make the following substitutions:
322 //
323 // CFStringRef -> i8*
324 // CFAllocatorRef -> i8*
325 // UInt8 * -> i8*
326 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
327 // CFStringEncoding -> i32
328 // Boolean -> i8
329
330 std::vector <const Type *> CFSCWB_arg_types;
331 CFSCWB_arg_types.push_back(i8_ptr_ty);
332 CFSCWB_arg_types.push_back(i8_ptr_ty);
333 CFSCWB_arg_types.push_back(intptr_ty);
334 CFSCWB_arg_types.push_back(i32_ty);
335 CFSCWB_arg_types.push_back(i8_ty);
336 llvm::Type *CFSCWB_ty = FunctionType::get(i8_ptr_ty, CFSCWB_arg_types, false);
337
338 // Build the constant containing the pointer to the function
339 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
340 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
341 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
342 }
343
344 ConstantArray *string_array = dyn_cast<ConstantArray>(CStr->getInitializer());
345
346 SmallVector <Value*, 5> CFSCWB_arguments;
347
348 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
349 Constant *bytes_arg = ConstantExpr::getBitCast(CStr, i8_ptr_ty);
350 Constant *numBytes_arg = ConstantInt::get(intptr_ty, string_array->getType()->getNumElements(), false);
351 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
352 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
353
354 CFSCWB_arguments.push_back(alloc_arg);
355 CFSCWB_arguments.push_back(bytes_arg);
356 CFSCWB_arguments.push_back(numBytes_arg);
357 CFSCWB_arguments.push_back(encoding_arg);
358 CFSCWB_arguments.push_back(isExternal_arg);
359
360 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
361 CFSCWB_arguments.begin(),
362 CFSCWB_arguments.end(),
363 "CFStringCreateWithBytes",
364 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000365
Sean Callanan6ba533e2010-11-17 23:00:36 +0000366 if (!UnfoldConstant(NSStr, CFSCWB_call, FirstEntryInstruction))
367 {
368 if (log)
369 log->PutCString("Couldn't replace the NSString with the result of the call");
370
371 return false;
372 }
373
374 NSStr->eraseFromParent();
375
376 return true;
377}
378
379bool
380IRForTarget::rewriteObjCConstStrings(Module &M,
381 Function &F)
382{
383 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
384
385 ValueSymbolTable& value_symbol_table = M.getValueSymbolTable();
386
387 BasicBlock &entry_block(F.getEntryBlock());
388 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
389
390 if (!FirstEntryInstruction)
391 {
392 if (log)
393 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
394
395 return false;
396 }
397
398 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
399 vi != ve;
400 ++vi)
401 {
402 if (strstr(vi->first(), "_unnamed_cfstring_"))
403 {
404 Value *nsstring_value = vi->second;
405
406 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
407
408 if (!nsstring_global)
409 {
410 if (log)
411 log->PutCString("NSString variable is not a GlobalVariable");
412 return false;
413 }
414
415 if (!nsstring_global->hasInitializer())
416 {
417 if (log)
418 log->PutCString("NSString variable does not have an initializer");
419 return false;
420 }
421
422 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
423
424 if (!nsstring_struct)
425 {
426 if (log)
427 log->PutCString("NSString variable's initializer is not a ConstantStruct");
428 return false;
429 }
430
431 // We expect the following structure:
432 //
433 // struct {
434 // int *isa;
435 // int flags;
436 // char *str;
437 // long length;
438 // };
439
440 if (nsstring_struct->getNumOperands() != 4)
441 {
442 if (log)
443 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
444 return false;
445 }
446
447 Constant *nsstring_member = nsstring_struct->getOperand(2);
448
449 if (!nsstring_member)
450 {
451 if (log)
452 log->PutCString("NSString initializer's str element was empty");
453 return false;
454 }
455
456 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
457
458 if (!nsstring_expr)
459 {
460 if (log)
461 log->PutCString("NSString initializer's str element is not a ConstantExpr");
462 return false;
463 }
464
465 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
466 {
467 if (log)
468 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
469 return false;
470 }
471
472 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
473
474 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
475
476 if (!cstr_global)
477 {
478 if (log)
479 log->PutCString("NSString initializer's str element is not a GlobalVariable");
480
481 nsstring_cstr->dump();
482
483 return false;
484 }
485
486 if (!cstr_global->hasInitializer())
487 {
488 if (log)
489 log->PutCString("NSString initializer's str element does not have an initializer");
490 return false;
491 }
492
493 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
494
495 if (!cstr_array)
496 {
497 if (log)
498 log->PutCString("NSString initializer's str element is not a ConstantArray");
499 return false;
500 }
501
502 if (!cstr_array->isCString())
503 {
504 if (log)
505 log->PutCString("NSString initializer's str element is not a C string array");
506 return false;
507 }
508
509 if (log)
510 log->Printf("Found NSString constant %s, which contains \"%s\"", vi->first(), cstr_array->getAsString().c_str());
511
512 if (!rewriteObjCConstString(M, nsstring_global, cstr_global, FirstEntryInstruction))
513 {
514 if (log)
515 log->PutCString("Error rewriting the constant string");
516 return false;
517 }
518
519
520 }
521 }
522
523 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
524 vi != ve;
525 ++vi)
526 {
527 if (!strcmp(vi->first(), "__CFConstantStringClassReference"))
528 {
529 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
530
531 if (!gv)
532 {
533 if (log)
534 log->PutCString("__CFConstantStringClassReference is not a global variable");
535 return false;
536 }
537
538 gv->eraseFromParent();
539
540 break;
541 }
542 }
543
544 return true;
545}
546
Sean Callananf5857a02010-07-31 01:32:05 +0000547static bool isObjCSelectorRef(Value *V)
548{
549 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
550
551 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
552 return false;
553
554 return true;
555}
556
557bool
558IRForTarget::RewriteObjCSelector(Instruction* selector_load,
559 Module &M)
560{
Greg Claytone005f2c2010-11-06 01:53:30 +0000561 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000562
563 LoadInst *load = dyn_cast<LoadInst>(selector_load);
564
565 if (!load)
566 return false;
567
568 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
569 //
570 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
571 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
572 //
573 // where %obj is the object pointer and %tmp is the selector.
574 //
575 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
576 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
577
578 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
579
580 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
581
582 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
583 return false;
584
585 Constant *osr_initializer = _objc_selector_references_->getInitializer();
586
587 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
588
589 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
590 return false;
591
592 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
593
594 if (!osr_initializer_base)
595 return false;
596
597 // Find the string's initializer (a ConstantArray) and get the string from it
598
599 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
600
601 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
602 return false;
603
604 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
605
606 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
607
608 if (!omvn_initializer_array->isString())
609 return false;
610
611 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
612
613 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000614 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000615
616 // Construct a call to sel_registerName
617
618 if (!m_sel_registerName)
619 {
Greg Claytonb5037af2010-11-15 01:47:11 +0000620 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000621
Greg Clayton8de27c72010-10-15 22:48:33 +0000622 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +0000623 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +0000624 return false;
625
Sean Callananc2c6f772010-10-26 00:31:56 +0000626 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000627 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +0000628
Sean Callananf5857a02010-07-31 01:32:05 +0000629 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
630
631 // The below code would be "more correct," but in actuality what's required is uint8_t*
632 //Type *sel_type = StructType::get(M.getContext());
633 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
634 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
635
636 std::vector <const Type *> srN_arg_types;
637 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
638 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
639
640 // Build the constant containing the pointer to the function
641 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
642 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
643 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +0000644 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000645 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
646 }
647
648 SmallVector <Value*, 1> srN_arguments;
649
650 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
651
652 srN_arguments.push_back(omvn_pointer);
653
654 CallInst *srN_call = CallInst::Create(m_sel_registerName,
655 srN_arguments.begin(),
656 srN_arguments.end(),
Sean Callanan6ba533e2010-11-17 23:00:36 +0000657 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +0000658 selector_load);
659
660 // Replace the load with the call in all users
661
662 selector_load->replaceAllUsesWith(srN_call);
663
664 selector_load->eraseFromParent();
665
666 return true;
667}
668
669bool
670IRForTarget::rewriteObjCSelectors(Module &M,
671 BasicBlock &BB)
672{
Greg Claytone005f2c2010-11-06 01:53:30 +0000673 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000674
675 BasicBlock::iterator ii;
676
677 typedef SmallVector <Instruction*, 2> InstrList;
678 typedef InstrList::iterator InstrIterator;
679
680 InstrList selector_loads;
681
682 for (ii = BB.begin();
683 ii != BB.end();
684 ++ii)
685 {
686 Instruction &inst = *ii;
687
688 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
689 if (isObjCSelectorRef(load->getPointerOperand()))
690 selector_loads.push_back(&inst);
691 }
692
693 InstrIterator iter;
694
695 for (iter = selector_loads.begin();
696 iter != selector_loads.end();
697 ++iter)
698 {
699 if (!RewriteObjCSelector(*iter, M))
700 {
701 if(log)
702 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
703 return false;
704 }
705 }
706
707 return true;
708}
709
Sean Callanana48fe162010-08-11 03:57:18 +0000710bool
711IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
Greg Clayton8de27c72010-10-15 22:48:33 +0000712 llvm::Module &llvm_module)
Sean Callanana48fe162010-08-11 03:57:18 +0000713{
714 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
715
716 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
717
718 if (!alloc_md || !alloc_md->getNumOperands())
719 return false;
720
721 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
722
723 if (!constant_int)
724 return false;
725
726 // We attempt to register this as a new persistent variable with the DeclMap.
727
728 uintptr_t ptr = constant_int->getZExtValue();
729
Sean Callanan82b74c82010-08-12 01:56:52 +0000730 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000731
Sean Callanan82b74c82010-08-12 01:56:52 +0000732 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
733 &decl->getASTContext());
734
Greg Clayton8de27c72010-10-15 22:48:33 +0000735 StringRef decl_name (decl->getName());
736 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
737 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000738 return false;
739
Greg Clayton8de27c72010-10-15 22:48:33 +0000740 GlobalVariable *persistent_global = new GlobalVariable(llvm_module,
Sean Callanana48fe162010-08-11 03:57:18 +0000741 alloc->getType()->getElementType(),
742 false, /* not constant */
743 GlobalValue::ExternalLinkage,
744 NULL, /* no initializer */
745 alloc->getName().str().c_str());
746
747 // What we're going to do here is make believe this was a regular old external
748 // variable. That means we need to make the metadata valid.
749
Greg Clayton8de27c72010-10-15 22:48:33 +0000750 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +0000751
752 llvm::Value* values[2];
753 values[0] = persistent_global;
754 values[1] = constant_int;
755
Greg Clayton8de27c72010-10-15 22:48:33 +0000756 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +0000757 named_metadata->addOperand(persistent_global_md);
758
759 alloc->replaceAllUsesWith(persistent_global);
760 alloc->eraseFromParent();
761
762 return true;
763}
764
765bool
766IRForTarget::rewritePersistentAllocs(llvm::Module &M,
767 llvm::BasicBlock &BB)
768{
Sean Callanane8a59a82010-09-13 21:34:21 +0000769 if (!m_resolve_vars)
770 return true;
771
Greg Claytone005f2c2010-11-06 01:53:30 +0000772 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +0000773
774 BasicBlock::iterator ii;
775
776 typedef SmallVector <Instruction*, 2> InstrList;
777 typedef InstrList::iterator InstrIterator;
778
779 InstrList pvar_allocs;
780
781 for (ii = BB.begin();
782 ii != BB.end();
783 ++ii)
784 {
785 Instruction &inst = *ii;
786
787 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan03c997b2010-10-21 22:41:32 +0000788 if (alloc->getName().startswith("$") &&
789 !alloc->getName().startswith("$__lldb"))
Sean Callanana48fe162010-08-11 03:57:18 +0000790 pvar_allocs.push_back(alloc);
791 }
792
793 InstrIterator iter;
794
795 for (iter = pvar_allocs.begin();
796 iter != pvar_allocs.end();
797 ++iter)
798 {
799 if (!RewritePersistentAlloc(*iter, M))
800 {
801 if(log)
802 log->PutCString("Couldn't rewrite the creation of a persistent variable");
803 return false;
804 }
805 }
806
807 return true;
808}
809
Sean Callanan8bce6652010-07-13 21:41:46 +0000810static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000811DeclForGlobalValue(Module &module,
812 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000813{
814 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
815
816 if (!named_metadata)
817 return NULL;
818
819 unsigned num_nodes = named_metadata->getNumOperands();
820 unsigned node_index;
821
822 for (node_index = 0;
823 node_index < num_nodes;
824 ++node_index)
825 {
826 MDNode *metadata_node = named_metadata->getOperand(node_index);
827
828 if (!metadata_node)
829 return NULL;
830
831 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000832 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000833
834 if (metadata_node->getOperand(0) != global_value)
835 continue;
836
837 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
838
839 if (!constant_int)
840 return NULL;
841
842 uintptr_t ptr = constant_int->getZExtValue();
843
844 return reinterpret_cast<clang::NamedDecl *>(ptr);
845 }
846
847 return NULL;
848}
849
850bool
Greg Clayton8de27c72010-10-15 22:48:33 +0000851IRForTarget::MaybeHandleVariable
852(
853 Module &llvm_module,
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000854 Value *llvm_value_ptr
Greg Clayton8de27c72010-10-15 22:48:33 +0000855)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000856{
Greg Claytone005f2c2010-11-06 01:53:30 +0000857 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000858
Greg Clayton8de27c72010-10-15 22:48:33 +0000859 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +0000860 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000861 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000862 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000863 default:
864 break;
865 case Instruction::GetElementPtr:
866 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000867 Value *s = constant_expr->getOperand(0);
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000868 MaybeHandleVariable(llvm_module, s);
Sean Callananbc2928a2010-08-03 00:23:29 +0000869 }
870 }
Greg Clayton8de27c72010-10-15 22:48:33 +0000871 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +0000872 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000873 clang::NamedDecl *named_decl = DeclForGlobalValue(llvm_module, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000874
Sean Callananf5857a02010-07-31 01:32:05 +0000875 if (!named_decl)
876 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000877 if (isObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +0000878 return true;
879
880 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000881 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000882 return false;
883 }
884
Greg Clayton8de27c72010-10-15 22:48:33 +0000885 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +0000886
Sean Callanan771131d2010-09-30 21:18:25 +0000887 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000888 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000889
890 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000891 {
Sean Callanan771131d2010-09-30 21:18:25 +0000892 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000893 ast_context = &value_decl->getASTContext();
894 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000895 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000896 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000897 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000898 }
Sean Callanan771131d2010-09-30 21:18:25 +0000899
900 clang::QualType qual_type(clang::QualType::getFromOpaquePtr(opaque_type));
Sean Callananf328c9f2010-07-20 23:31:16 +0000901
Sean Callanan02fbafa2010-07-27 21:39:39 +0000902 const Type *value_type = global_variable->getType();
Sean Callanan771131d2010-09-30 21:18:25 +0000903
904 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
905 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
906
907 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000908 log->Printf("Type of \"%s\" is [clang \"%s\", lldb \"%s\"] [size %d, align %d]",
Sean Callanan771131d2010-09-30 21:18:25 +0000909 name.c_str(),
910 qual_type.getAsString().c_str(),
911 PrintType(value_type).c_str(),
912 value_size,
913 value_alignment);
914
Sean Callanan8bce6652010-07-13 21:41:46 +0000915
Sean Callanan8c127202010-08-23 23:09:38 +0000916 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +0000917 lldb_private::ConstString (name.c_str()),
918 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +0000919 value_size,
920 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000921 return false;
922 }
923
924 return true;
925}
926
927bool
Sean Callanandc27aba2010-10-05 22:26:43 +0000928IRForTarget::MaybeHandleCallArguments(Module &M,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000929 CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +0000930{
Greg Claytone005f2c2010-11-06 01:53:30 +0000931 // lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanandc27aba2010-10-05 22:26:43 +0000932
Sean Callanan6ba533e2010-11-17 23:00:36 +0000933 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +0000934 op_index < num_ops;
935 ++op_index)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000936 if (!MaybeHandleVariable(M, Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanandc27aba2010-10-05 22:26:43 +0000937 return false;
938
939 return true;
940}
941
942bool
Greg Clayton8de27c72010-10-15 22:48:33 +0000943IRForTarget::MaybeHandleCall(Module &llvm_module,
944 CallInst *llvm_call_inst)
Sean Callananba992c52010-07-27 02:07:53 +0000945{
Greg Claytone005f2c2010-11-06 01:53:30 +0000946 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananba992c52010-07-27 02:07:53 +0000947
Greg Clayton8de27c72010-10-15 22:48:33 +0000948 Function *fun = llvm_call_inst->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000949
950 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +0000951 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000952 Value *val = llvm_call_inst->getCalledValue();
Sean Callanan65af7342010-09-08 20:04:08 +0000953
954 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
955
956 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
957 {
958 fun = dyn_cast<Function>(const_expr->getOperand(0));
959
960 if (!fun)
961 return true;
962 }
963 else
964 {
965 return true;
966 }
967 }
Sean Callananba992c52010-07-27 02:07:53 +0000968
Greg Clayton8de27c72010-10-15 22:48:33 +0000969 lldb_private::ConstString str;
Sean Callananc04743d2010-09-28 21:13:03 +0000970
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000971 if (fun->isIntrinsic())
Sean Callananc04743d2010-09-28 21:13:03 +0000972 {
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000973 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
Sean Callananc04743d2010-09-28 21:13:03 +0000974
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000975 switch (intrinsic_id)
976 {
977 default:
978 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000979 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000980 return false;
981 case Intrinsic::memcpy:
Greg Clayton8de27c72010-10-15 22:48:33 +0000982 {
983 static lldb_private::ConstString g_memcpy_str ("memcpy");
984 str = g_memcpy_str;
985 }
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000986 break;
987 }
Sean Callananc04743d2010-09-28 21:13:03 +0000988
Greg Clayton8de27c72010-10-15 22:48:33 +0000989 if (log && str)
Greg Claytonb5037af2010-11-15 01:47:11 +0000990 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString());
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000991 }
992 else
993 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000994 str.SetCStringWithLength (fun->getName().data(), fun->getName().size());
Sean Callananc04743d2010-09-28 21:13:03 +0000995 }
996
Greg Clayton8de27c72010-10-15 22:48:33 +0000997 clang::NamedDecl *fun_decl = DeclForGlobalValue (llvm_module, fun);
Greg Claytonb5037af2010-11-15 01:47:11 +0000998 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS;
Sean Callananf5857a02010-07-31 01:32:05 +0000999 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +00001000
Sean Callananf5857a02010-07-31 01:32:05 +00001001 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +00001002 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001003 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001004 {
Sean Callanan92aa6662010-09-07 21:49:41 +00001005 fun_value_ptr = NULL;
1006
Greg Clayton8de27c72010-10-15 22:48:33 +00001007 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +00001008 {
1009 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001010 log->Printf("Function \"%s\" had no address", str.GetCString());
Sean Callanan92aa6662010-09-07 21:49:41 +00001011
1012 return false;
1013 }
Sean Callananf5857a02010-07-31 01:32:05 +00001014 }
1015 }
1016 else
1017 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001018 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001019 {
1020 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001021 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString());
Sean Callananf5857a02010-07-31 01:32:05 +00001022 }
Sean Callananba992c52010-07-27 02:07:53 +00001023 }
1024
1025 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001026 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +00001027
Sean Callananf5857a02010-07-31 01:32:05 +00001028 Value *fun_addr_ptr;
1029
1030 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +00001031 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001032 const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(),
1033 (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +00001034 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +00001035 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
1036 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001037 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
1038
1039 if (fun_value_ptr)
1040 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001041 }
Sean Callananf5857a02010-07-31 01:32:05 +00001042
1043 if (fun_value_ptr)
1044 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001045
Greg Clayton8de27c72010-10-15 22:48:33 +00001046 llvm_call_inst->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +00001047
Greg Clayton8de27c72010-10-15 22:48:33 +00001048 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(llvm_module.getContext(), str.GetCString());
Sean Callanane8a59a82010-09-13 21:34:21 +00001049
1050 Value *values[1];
1051 values[0] = func_name;
Greg Clayton8de27c72010-10-15 22:48:33 +00001052 MDNode *func_metadata = MDNode::get(llvm_module.getContext(), values, 1);
Sean Callanane8a59a82010-09-13 21:34:21 +00001053
Greg Clayton8de27c72010-10-15 22:48:33 +00001054 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata);
Sean Callanane8a59a82010-09-13 21:34:21 +00001055
1056 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001057 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 +00001058
Sean Callananba992c52010-07-27 02:07:53 +00001059 return true;
1060}
1061
1062bool
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001063IRForTarget::resolveCalls(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +00001064{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001065 /////////////////////////////////////////////////////////////////////////
1066 // Prepare the current basic block for execution in the remote process
1067 //
1068
Sean Callanan02fbafa2010-07-27 21:39:39 +00001069 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001070
1071 for (ii = BB.begin();
1072 ii != BB.end();
1073 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001074 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001075 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001076
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001077 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001078
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001079 if (call && !MaybeHandleCall(M, call))
1080 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001081 }
1082
1083 return true;
1084}
1085
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001086bool
1087IRForTarget::resolveExternals(Module &M,
1088 Function &F)
1089{
Sean Callananae71e302010-11-18 22:21:58 +00001090 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1091
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001092 for (Module::global_iterator global = M.global_begin(), end = M.global_end();
1093 global != end;
1094 ++global)
1095 {
Sean Callananae71e302010-11-18 22:21:58 +00001096 if (DeclForGlobalValue(M, global) &&
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001097 !MaybeHandleVariable (M, global))
1098 return false;
1099 }
1100
1101 return true;
1102}
1103
Sean Callanan02fbafa2010-07-27 21:39:39 +00001104static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001105{
Sean Callanan6ba533e2010-11-17 23:00:36 +00001106 Constant *Old;
Sean Callanan45839272010-07-24 01:37:44 +00001107
Sean Callanan6ba533e2010-11-17 23:00:36 +00001108 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001109 return false;
1110
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001111 ConstantExpr *CE;
1112
1113 if ((CE = dyn_cast<ConstantExpr>(V)))
1114 {
1115 if (CE->getOpcode() != Instruction::BitCast)
1116 return false;
1117
Sean Callanan6ba533e2010-11-17 23:00:36 +00001118 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001119 }
1120
Sean Callanan6ba533e2010-11-17 23:00:36 +00001121 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001122
1123 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1124 return false;
1125
1126 return true;
1127}
1128
1129static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
1130{
1131 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
1132
1133 Value::use_iterator ui;
1134
1135 for (ui = guard_load->use_begin();
1136 ui != guard_load->use_end();
1137 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001138 {
Greg Clayton6e713402010-07-30 20:30:44 +00001139 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001140 {
1141 // do nothing for the moment
1142 }
1143 else
1144 {
1145 ui->replaceUsesOfWith(guard_load, zero);
1146 }
1147 }
Sean Callanan45839272010-07-24 01:37:44 +00001148
1149 guard_load->eraseFromParent();
1150}
1151
1152static void ExciseGuardStore(Instruction* guard_store)
1153{
1154 guard_store->eraseFromParent();
1155}
1156
1157bool
1158IRForTarget::removeGuards(Module &M, BasicBlock &BB)
1159{
1160 ///////////////////////////////////////////////////////
1161 // Eliminate any reference to guard variables found.
1162 //
1163
Sean Callanan02fbafa2010-07-27 21:39:39 +00001164 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001165
Sean Callanan02fbafa2010-07-27 21:39:39 +00001166 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001167 typedef InstrList::iterator InstrIterator;
1168
1169 InstrList guard_loads;
1170 InstrList guard_stores;
1171
1172 for (ii = BB.begin();
1173 ii != BB.end();
1174 ++ii)
1175 {
1176 Instruction &inst = *ii;
1177
1178 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1179 if (isGuardVariableRef(load->getPointerOperand()))
1180 guard_loads.push_back(&inst);
1181
1182 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1183 if (isGuardVariableRef(store->getPointerOperand()))
1184 guard_stores.push_back(&inst);
1185 }
1186
1187 InstrIterator iter;
1188
1189 for (iter = guard_loads.begin();
1190 iter != guard_loads.end();
1191 ++iter)
1192 TurnGuardLoadIntoZero(*iter, M);
1193
1194 for (iter = guard_stores.begin();
1195 iter != guard_stores.end();
1196 ++iter)
1197 ExciseGuardStore(*iter);
1198
1199 return true;
1200}
1201
Sean Callanan6ba533e2010-11-17 23:00:36 +00001202bool
1203IRForTarget::UnfoldConstant(Constant *Old, Value *New, Instruction *FirstEntryInstruction)
Sean Callananbafd6852010-07-14 23:40:29 +00001204{
Greg Claytone005f2c2010-11-06 01:53:30 +00001205 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001206
1207 Value::use_iterator ui;
1208
Sean Callanana48fe162010-08-11 03:57:18 +00001209 SmallVector<User*, 16> users;
1210
1211 // We do this because the use list might change, invalidating our iterator.
1212 // Much better to keep a work list ourselves.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001213 for (ui = Old->use_begin();
1214 ui != Old->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001215 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001216 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001217
Sean Callanana48fe162010-08-11 03:57:18 +00001218 for (int i = 0;
1219 i < users.size();
1220 ++i)
1221 {
1222 User *user = users[i];
1223
Sean Callananbafd6852010-07-14 23:40:29 +00001224 if (Constant *constant = dyn_cast<Constant>(user))
1225 {
1226 // synthesize a new non-constant equivalent of the constant
1227
1228 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1229 {
1230 switch (constant_expr->getOpcode())
1231 {
1232 default:
1233 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001234 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001235 return false;
1236 case Instruction::BitCast:
1237 {
1238 // UnaryExpr
1239 // OperandList[0] is value
1240
1241 Value *s = constant_expr->getOperand(0);
1242
Sean Callanan6ba533e2010-11-17 23:00:36 +00001243 if (s == Old)
1244 s = New;
Sean Callananbafd6852010-07-14 23:40:29 +00001245
Sean Callanan6ba533e2010-11-17 23:00:36 +00001246 BitCastInst *bit_cast(new BitCastInst(s, Old->getType(), "", FirstEntryInstruction));
Sean Callananbafd6852010-07-14 23:40:29 +00001247
Sean Callanan6ba533e2010-11-17 23:00:36 +00001248 UnfoldConstant(constant_expr, bit_cast, FirstEntryInstruction);
Sean Callananbafd6852010-07-14 23:40:29 +00001249 }
1250 break;
1251 case Instruction::GetElementPtr:
1252 {
1253 // GetElementPtrConstantExpr
1254 // OperandList[0] is base
1255 // OperandList[1]... are indices
1256
1257 Value *ptr = constant_expr->getOperand(0);
1258
Sean Callanan6ba533e2010-11-17 23:00:36 +00001259 if (ptr == Old)
1260 ptr = New;
Sean Callananbafd6852010-07-14 23:40:29 +00001261
1262 SmallVector<Value*, 16> indices;
1263
1264 unsigned operand_index;
1265 unsigned num_operands = constant_expr->getNumOperands();
1266
1267 for (operand_index = 1;
1268 operand_index < num_operands;
1269 ++operand_index)
1270 {
1271 Value *operand = constant_expr->getOperand(operand_index);
1272
Sean Callanan6ba533e2010-11-17 23:00:36 +00001273 if (operand == Old)
1274 operand = New;
Sean Callananbafd6852010-07-14 23:40:29 +00001275
1276 indices.push_back(operand);
1277 }
1278
Sean Callanan6ba533e2010-11-17 23:00:36 +00001279 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", FirstEntryInstruction));
Sean Callananbafd6852010-07-14 23:40:29 +00001280
Sean Callanan6ba533e2010-11-17 23:00:36 +00001281 UnfoldConstant(constant_expr, get_element_ptr, FirstEntryInstruction);
Sean Callananbafd6852010-07-14 23:40:29 +00001282 }
1283 break;
1284 }
1285 }
1286 else
1287 {
1288 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001289 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001290 return false;
1291 }
1292 }
1293 else
1294 {
1295 // simple fall-through case for non-constants
Sean Callanan6ba533e2010-11-17 23:00:36 +00001296 user->replaceUsesOfWith(Old, New);
Sean Callananbafd6852010-07-14 23:40:29 +00001297 }
1298 }
1299
1300 return true;
1301}
1302
Sean Callanan8bce6652010-07-13 21:41:46 +00001303bool
Sean Callananf5857a02010-07-31 01:32:05 +00001304IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +00001305{
Sean Callanane8a59a82010-09-13 21:34:21 +00001306 if (!m_resolve_vars)
1307 return true;
1308
Greg Claytone005f2c2010-11-06 01:53:30 +00001309 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00001310
1311 m_decl_map->DoStructLayout();
1312
1313 if (log)
1314 log->Printf("Element arrangement:");
1315
1316 uint32_t num_elements;
1317 uint32_t element_index;
1318
1319 size_t size;
1320 off_t alignment;
1321
1322 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
1323 return false;
1324
Sean Callananf5857a02010-07-31 01:32:05 +00001325 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00001326
Sean Callananf5857a02010-07-31 01:32:05 +00001327 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +00001328 return false;
1329
Sean Callanan02fbafa2010-07-27 21:39:39 +00001330 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00001331
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001332 if (argument->getName().equals("this"))
1333 {
1334 ++iter;
1335
1336 if (iter == F.getArgumentList().end())
1337 return false;
1338
1339 argument = iter;
1340 }
1341
Greg Clayton8de27c72010-10-15 22:48:33 +00001342 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan8bce6652010-07-13 21:41:46 +00001343 return false;
1344
1345 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001346 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00001347
Sean Callananf5857a02010-07-31 01:32:05 +00001348 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001349 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00001350
Sean Callanan6ba533e2010-11-17 23:00:36 +00001351 if (!FirstEntryInstruction)
Sean Callanan8bce6652010-07-13 21:41:46 +00001352 return false;
1353
1354 LLVMContext &context(M.getContext());
1355 const IntegerType *offset_type(Type::getInt32Ty(context));
1356
1357 if (!offset_type)
1358 return false;
1359
1360 for (element_index = 0; element_index < num_elements; ++element_index)
1361 {
1362 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001363 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +00001364 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00001365 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00001366
Sean Callanan45690fe2010-08-30 22:17:16 +00001367 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +00001368 return false;
1369
1370 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001371 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00001372 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00001373 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00001374 PrintValue(value, true).c_str(),
1375 offset);
1376
1377 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
Sean Callanan6ba533e2010-11-17 23:00:36 +00001378 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
1379 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
Sean Callanan8bce6652010-07-13 21:41:46 +00001380
Sean Callananbafd6852010-07-14 23:40:29 +00001381 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001382 UnfoldConstant(constant, bit_cast, FirstEntryInstruction);
Sean Callananbafd6852010-07-14 23:40:29 +00001383 else
1384 value->replaceAllUsesWith(bit_cast);
Sean Callananb51ee982010-11-02 23:51:17 +00001385
1386 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1387 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00001388 }
1389
1390 if (log)
1391 log->Printf("Total structure [align %d, size %d]", alignment, size);
1392
1393 return true;
1394}
1395
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001396bool
1397IRForTarget::runOnModule(Module &M)
1398{
Greg Claytone005f2c2010-11-06 01:53:30 +00001399 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001400
Sean Callanan65dafa82010-08-27 01:01:44 +00001401 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001402
1403 if (!function)
1404 {
1405 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001406 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001407
1408 return false;
1409 }
1410
Sean Callanan02fbafa2010-07-27 21:39:39 +00001411 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001412
Sean Callanan82b74c82010-08-12 01:56:52 +00001413 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00001414 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00001415 //
1416
1417 if (!createResultVariable(M, *function))
1418 return false;
1419
Sean Callanan6ba533e2010-11-17 23:00:36 +00001420 ///////////////////////////////////////////////////////////////////////////////
1421 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
1422 //
1423
1424 if (log)
1425 {
1426 std::string s;
1427 raw_string_ostream oss(s);
1428
1429 M.print(oss, NULL);
1430
1431 oss.flush();
1432
1433 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
1434 }
1435
1436 if (!rewriteObjCConstStrings(M, *function))
1437 return false;
1438
1439 if (log)
1440 {
1441 std::string s;
1442 raw_string_ostream oss(s);
1443
1444 M.print(oss, NULL);
1445
1446 oss.flush();
1447
1448 log->Printf("Module after rewriting Objective-C const strings: \n\"%s\"", s.c_str());
1449 }
1450
Sean Callananf5857a02010-07-31 01:32:05 +00001451 //////////////////////////////////
1452 // Run basic-block level passes
1453 //
1454
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001455 for (bbi = function->begin();
1456 bbi != function->end();
1457 ++bbi)
1458 {
Sean Callanan8c127202010-08-23 23:09:38 +00001459 if (!removeGuards(M, *bbi))
1460 return false;
1461
Sean Callanana48fe162010-08-11 03:57:18 +00001462 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +00001463 return false;
1464
Sean Callanana48fe162010-08-11 03:57:18 +00001465 if (!rewriteObjCSelectors(M, *bbi))
1466 return false;
1467
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001468 if (!resolveCalls(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001469 return false;
1470 }
1471
Sean Callanan771131d2010-09-30 21:18:25 +00001472 ///////////////////////////////
1473 // Run function-level passes
1474 //
1475
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001476 if (!resolveExternals(M, *function))
1477 return false;
1478
Sean Callanan771131d2010-09-30 21:18:25 +00001479 if (!replaceVariables(M, *function))
1480 return false;
1481
Sean Callanan8bce6652010-07-13 21:41:46 +00001482 if (log)
1483 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001484 std::string s;
1485 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001486
Sean Callanan321fe9e2010-07-28 01:00:59 +00001487 M.print(oss, NULL);
1488
1489 oss.flush();
1490
Greg Claytonb5037af2010-11-15 01:47:11 +00001491 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001492 }
1493
1494 return true;
1495}
1496
1497void
1498IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001499 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001500{
1501}
1502
1503PassManagerType
1504IRForTarget::getPotentialPassManagerType() const
1505{
1506 return PMT_ModulePassManager;
1507}