blob: 626cd547bfee5320a77ca23f4b974111cc689f64 [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 Callanan5cf4a1c2010-07-03 01:35:46 +000015#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000016#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000017#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000018
19#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000020
21#include "lldb/Core/dwarf.h"
22#include "lldb/Core/Log.h"
23#include "lldb/Core/Scalar.h"
24#include "lldb/Core/StreamString.h"
25#include "lldb/Expression/ClangExpressionDeclMap.h"
26
27#include <map>
28
29using namespace llvm;
30
Sean Callanan3351dac2010-08-18 18:50:51 +000031static char ID;
32
33IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
Sean Callanan65dafa82010-08-27 01:01:44 +000034 const TargetData *target_data,
Sean Callanane8a59a82010-09-13 21:34:21 +000035 bool resolve_vars,
Sean Callanan65dafa82010-08-27 01:01:44 +000036 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000037 ModulePass(ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000038 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000039 m_target_data(target_data),
Sean Callanan65dafa82010-08-27 01:01:44 +000040 m_sel_registerName(NULL),
Sean Callanane8a59a82010-09-13 21:34:21 +000041 m_func_name(func_name),
42 m_resolve_vars(resolve_vars)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000043{
44}
45
Sean Callanana48fe162010-08-11 03:57:18 +000046/* A handy utility function used at several places in the code */
47
48static std::string
49PrintValue(Value *V, bool truncate = false)
50{
51 std::string s;
52 raw_string_ostream rso(s);
53 V->print(rso);
54 rso.flush();
55 if (truncate)
56 s.resize(s.length() - 1);
57 return s;
58}
59
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000060IRForTarget::~IRForTarget()
61{
62}
63
Sean Callanan82b74c82010-08-12 01:56:52 +000064bool
65IRForTarget::createResultVariable(llvm::Module &M,
66 llvm::Function &F)
67{
68 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
69
Sean Callanane8a59a82010-09-13 21:34:21 +000070 if (!m_resolve_vars)
71 return true;
72
73 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000074
75 ValueSymbolTable& value_symbol_table = M.getValueSymbolTable();
76
77 const char *result_name = NULL;
78
79 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
80 vi != ve;
81 ++vi)
82 {
83 if (strstr(vi->first(), "___clang_expr_result"))
84 result_name = vi->first();
85 }
86
87 if (!result_name)
88 {
89 if (log)
90 log->PutCString("Couldn't find result variable");
91
92 return true;
93 }
94
95 Value *result_value = M.getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +000096
97 if (!result_value)
98 {
99 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000100 log->PutCString("Result variable had no data");
Sean Callanane8a59a82010-09-13 21:34:21 +0000101
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000102 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000103 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000104
Sean Callanan82b74c82010-08-12 01:56:52 +0000105 if (log)
106 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
107
108 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
109
110 if (!result_global)
111 {
112 if (log)
113 log->PutCString("Result variable isn't a GlobalVariable");
114 return false;
115 }
116
117 // Find the metadata and follow it to the VarDecl
118
119 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
120
121 if (!named_metadata)
122 {
123 if (log)
124 log->PutCString("No global metadata");
125
126 return false;
127 }
128
129 unsigned num_nodes = named_metadata->getNumOperands();
130 unsigned node_index;
131
132 MDNode *metadata_node = NULL;
133
134 for (node_index = 0;
135 node_index < num_nodes;
136 ++node_index)
137 {
138 metadata_node = named_metadata->getOperand(node_index);
139
140 if (metadata_node->getNumOperands() != 2)
141 continue;
142
143 if (metadata_node->getOperand(0) == result_global)
144 break;
145 }
146
147 if (!metadata_node)
148 {
149 if (log)
150 log->PutCString("Couldn't find result metadata");
151 return false;
152 }
153
154 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
155
156 uint64_t result_decl_intptr = constant_int->getZExtValue();
157
158 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
159
160 // Get the next available result name from m_decl_map and create the persistent
161 // variable for it
162
163 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
164 &result_decl->getASTContext());
165 std::string new_result_name;
166
167 m_decl_map->GetPersistentResultName(new_result_name);
Sean Callanan8c127202010-08-23 23:09:38 +0000168 m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000169
170 if (log)
171 log->Printf("Creating a new result global: %s", new_result_name.c_str());
172
173 // Construct a new result global and set up its metadata
174
175 GlobalVariable *new_result_global = new GlobalVariable(M,
176 result_global->getType()->getElementType(),
177 false, /* not constant */
178 GlobalValue::ExternalLinkage,
179 NULL, /* no initializer */
180 new_result_name.c_str());
181
182 // It's too late in compilation to create a new VarDecl for this, but we don't
183 // need to. We point the metadata at the old VarDecl. This creates an odd
184 // anomaly: a variable with a Value whose name is something like $0 and a
185 // Decl whose name is ___clang_expr_result. This condition is handled in
186 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
187 // fixed up.
188
189 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
190 result_decl_intptr,
191 false);
192
193 llvm::Value* values[2];
194 values[0] = new_result_global;
195 values[1] = new_constant_int;
196
197 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
198 named_metadata->addOperand(persistent_global_md);
199
200 if (log)
Sean Callanan2e2db532010-09-07 22:43:19 +0000201 log->Printf("Replacing %s with %s",
202 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000203 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000204
205 if (result_global->hasNUses(0))
206 {
207 // We need to synthesize a store for this variable, because otherwise
208 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000209
Sean Callanan2e2db532010-09-07 22:43:19 +0000210 BasicBlock &entry_block(F.getEntryBlock());
211 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
212
213 if (!first_entry_instruction)
214 return false;
215
216 if (!result_global->hasInitializer())
217 {
218 if (log)
219 log->Printf("Couldn't find initializer for unused variable");
220 return false;
221 }
222
223 Constant *initializer = result_global->getInitializer();
224
225 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
226 new_result_global,
227 first_entry_instruction);
228
229 if (log)
230 log->Printf("Synthesized result store %s\n", PrintValue(synthesized_store).c_str());
231 }
232 else
233 {
234 result_global->replaceAllUsesWith(new_result_global);
235 }
236
Sean Callanan82b74c82010-08-12 01:56:52 +0000237 result_global->eraseFromParent();
238
239 return true;
240}
241
Sean Callananf5857a02010-07-31 01:32:05 +0000242static bool isObjCSelectorRef(Value *V)
243{
244 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
245
246 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
247 return false;
248
249 return true;
250}
251
252bool
253IRForTarget::RewriteObjCSelector(Instruction* selector_load,
254 Module &M)
255{
256 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
257
258 LoadInst *load = dyn_cast<LoadInst>(selector_load);
259
260 if (!load)
261 return false;
262
263 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
264 //
265 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
266 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
267 //
268 // where %obj is the object pointer and %tmp is the selector.
269 //
270 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
271 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
272
273 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
274
275 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
276
277 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
278 return false;
279
280 Constant *osr_initializer = _objc_selector_references_->getInitializer();
281
282 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
283
284 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
285 return false;
286
287 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
288
289 if (!osr_initializer_base)
290 return false;
291
292 // Find the string's initializer (a ConstantArray) and get the string from it
293
294 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
295
296 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
297 return false;
298
299 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
300
301 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
302
303 if (!omvn_initializer_array->isString())
304 return false;
305
306 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
307
308 if (log)
309 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
310
311 // Construct a call to sel_registerName
312
313 if (!m_sel_registerName)
314 {
315 uint64_t srN_addr;
316
317 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
318 return false;
319
320 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
321
322 // The below code would be "more correct," but in actuality what's required is uint8_t*
323 //Type *sel_type = StructType::get(M.getContext());
324 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
325 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
326
327 std::vector <const Type *> srN_arg_types;
328 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
329 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
330
331 // Build the constant containing the pointer to the function
332 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
333 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
334 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
335 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
336 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
337 }
338
339 SmallVector <Value*, 1> srN_arguments;
340
341 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
342
343 srN_arguments.push_back(omvn_pointer);
344
345 CallInst *srN_call = CallInst::Create(m_sel_registerName,
346 srN_arguments.begin(),
347 srN_arguments.end(),
348 "srN",
349 selector_load);
350
351 // Replace the load with the call in all users
352
353 selector_load->replaceAllUsesWith(srN_call);
354
355 selector_load->eraseFromParent();
356
357 return true;
358}
359
360bool
361IRForTarget::rewriteObjCSelectors(Module &M,
362 BasicBlock &BB)
363{
364 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
365
366 BasicBlock::iterator ii;
367
368 typedef SmallVector <Instruction*, 2> InstrList;
369 typedef InstrList::iterator InstrIterator;
370
371 InstrList selector_loads;
372
373 for (ii = BB.begin();
374 ii != BB.end();
375 ++ii)
376 {
377 Instruction &inst = *ii;
378
379 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
380 if (isObjCSelectorRef(load->getPointerOperand()))
381 selector_loads.push_back(&inst);
382 }
383
384 InstrIterator iter;
385
386 for (iter = selector_loads.begin();
387 iter != selector_loads.end();
388 ++iter)
389 {
390 if (!RewriteObjCSelector(*iter, M))
391 {
392 if(log)
393 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
394 return false;
395 }
396 }
397
398 return true;
399}
400
Sean Callanana48fe162010-08-11 03:57:18 +0000401bool
402IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
403 llvm::Module &M)
404{
405 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
406
407 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
408
409 if (!alloc_md || !alloc_md->getNumOperands())
410 return false;
411
412 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
413
414 if (!constant_int)
415 return false;
416
417 // We attempt to register this as a new persistent variable with the DeclMap.
418
419 uintptr_t ptr = constant_int->getZExtValue();
420
Sean Callanan82b74c82010-08-12 01:56:52 +0000421 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000422
Sean Callanan82b74c82010-08-12 01:56:52 +0000423 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
424 &decl->getASTContext());
425
Sean Callanan8c127202010-08-23 23:09:38 +0000426 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000427 return false;
428
429 GlobalVariable *persistent_global = new GlobalVariable(M,
430 alloc->getType()->getElementType(),
431 false, /* not constant */
432 GlobalValue::ExternalLinkage,
433 NULL, /* no initializer */
434 alloc->getName().str().c_str());
435
436 // What we're going to do here is make believe this was a regular old external
437 // variable. That means we need to make the metadata valid.
438
439 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
440
441 llvm::Value* values[2];
442 values[0] = persistent_global;
443 values[1] = constant_int;
444
445 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
446 named_metadata->addOperand(persistent_global_md);
447
448 alloc->replaceAllUsesWith(persistent_global);
449 alloc->eraseFromParent();
450
451 return true;
452}
453
454bool
455IRForTarget::rewritePersistentAllocs(llvm::Module &M,
456 llvm::BasicBlock &BB)
457{
Sean Callanane8a59a82010-09-13 21:34:21 +0000458 if (!m_resolve_vars)
459 return true;
460
Sean Callanana48fe162010-08-11 03:57:18 +0000461 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
462
463 BasicBlock::iterator ii;
464
465 typedef SmallVector <Instruction*, 2> InstrList;
466 typedef InstrList::iterator InstrIterator;
467
468 InstrList pvar_allocs;
469
470 for (ii = BB.begin();
471 ii != BB.end();
472 ++ii)
473 {
474 Instruction &inst = *ii;
475
476 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
477 if (alloc->getName().startswith("$"))
478 pvar_allocs.push_back(alloc);
479 }
480
481 InstrIterator iter;
482
483 for (iter = pvar_allocs.begin();
484 iter != pvar_allocs.end();
485 ++iter)
486 {
487 if (!RewritePersistentAlloc(*iter, M))
488 {
489 if(log)
490 log->PutCString("Couldn't rewrite the creation of a persistent variable");
491 return false;
492 }
493 }
494
495 return true;
496}
497
Sean Callanan8bce6652010-07-13 21:41:46 +0000498static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000499DeclForGlobalValue(Module &module,
500 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000501{
502 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
503
504 if (!named_metadata)
505 return NULL;
506
507 unsigned num_nodes = named_metadata->getNumOperands();
508 unsigned node_index;
509
510 for (node_index = 0;
511 node_index < num_nodes;
512 ++node_index)
513 {
514 MDNode *metadata_node = named_metadata->getOperand(node_index);
515
516 if (!metadata_node)
517 return NULL;
518
519 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000520 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000521
522 if (metadata_node->getOperand(0) != global_value)
523 continue;
524
525 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
526
527 if (!constant_int)
528 return NULL;
529
530 uintptr_t ptr = constant_int->getZExtValue();
531
532 return reinterpret_cast<clang::NamedDecl *>(ptr);
533 }
534
535 return NULL;
536}
537
538bool
539IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000540 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000541 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000542{
Sean Callananf5857a02010-07-31 01:32:05 +0000543 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
544
Sean Callananbc2928a2010-08-03 00:23:29 +0000545 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
546 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000547 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000548 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000549 default:
550 break;
551 case Instruction::GetElementPtr:
552 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000553 Value *s = constant_expr->getOperand(0);
554 MaybeHandleVariable(M, s, Store);
555 }
556 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000557 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000558 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000559 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000560
Sean Callananf5857a02010-07-31 01:32:05 +0000561 if (!named_decl)
562 {
563 if (isObjCSelectorRef(V))
564 return true;
565
566 if (log)
567 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
568 return false;
569 }
570
Sean Callanan810f22d2010-07-16 00:09:46 +0000571 std::string name = named_decl->getName().str();
572
573 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000574 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000575
576 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000577 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000578 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000579 ast_context = &value_decl->getASTContext();
580 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000581 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000582 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000583 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000584 }
585
Sean Callanan02fbafa2010-07-27 21:39:39 +0000586 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000587
588 size_t value_size = m_target_data->getTypeStoreSize(value_type);
589 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
590
Sean Callanan8c127202010-08-23 23:09:38 +0000591 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Sean Callanan45690fe2010-08-30 22:17:16 +0000592 name.c_str(),
Sean Callanan8c127202010-08-23 23:09:38 +0000593 V,
Sean Callananba992c52010-07-27 02:07:53 +0000594 value_size,
595 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000596 return false;
597 }
598
599 return true;
600}
601
602bool
Sean Callananba992c52010-07-27 02:07:53 +0000603IRForTarget::MaybeHandleCall(Module &M,
604 CallInst *C)
605{
606 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
607
Sean Callanan02fbafa2010-07-27 21:39:39 +0000608 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000609
610 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +0000611 {
612 Value *val = C->getCalledValue();
613
614 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
615
616 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
617 {
618 fun = dyn_cast<Function>(const_expr->getOperand(0));
619
620 if (!fun)
621 return true;
622 }
623 else
624 {
625 return true;
626 }
627 }
Sean Callananba992c52010-07-27 02:07:53 +0000628
629 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000630 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000631 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000632
Sean Callananf5857a02010-07-31 01:32:05 +0000633 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000634 {
Sean Callananf5857a02010-07-31 01:32:05 +0000635 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
636 {
Sean Callanan92aa6662010-09-07 21:49:41 +0000637 fun_value_ptr = NULL;
638
639 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
640 {
641 if (log)
642 log->Printf("Function %s had no address", fun->getName().str().c_str());
643
644 return false;
645 }
Sean Callananf5857a02010-07-31 01:32:05 +0000646 }
647 }
648 else
649 {
650 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
651 {
652 if (log)
653 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
654 return false;
655 }
Sean Callananba992c52010-07-27 02:07:53 +0000656 }
657
658 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000659 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000660
Sean Callananf5857a02010-07-31 01:32:05 +0000661 Value *fun_addr_ptr;
662
663 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000664 {
Sean Callanan02fbafa2010-07-27 21:39:39 +0000665 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
666 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +0000667 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +0000668 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
669 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000670 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
671
672 if (fun_value_ptr)
673 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000674 }
Sean Callananf5857a02010-07-31 01:32:05 +0000675
676 if (fun_value_ptr)
677 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000678
Sean Callananf5857a02010-07-31 01:32:05 +0000679 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000680
Sean Callanane8a59a82010-09-13 21:34:21 +0000681 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(M.getContext(), fun->getName());
682
683 Value *values[1];
684 values[0] = func_name;
685 MDNode *func_metadata = MDNode::get(M.getContext(), values, 1);
686
687 C->setMetadata("lldb.call.realName", func_metadata);
688
689 if (log)
690 log->Printf("Set metadata for %p [%d, %s]", C, func_name->isString(), func_name->getAsString().c_str());
691
Sean Callananba992c52010-07-27 02:07:53 +0000692 return true;
693}
694
695bool
Sean Callananf5857a02010-07-31 01:32:05 +0000696IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000697{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000698 /////////////////////////////////////////////////////////////////////////
699 // Prepare the current basic block for execution in the remote process
700 //
701
Sean Callanan02fbafa2010-07-27 21:39:39 +0000702 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000703
704 for (ii = BB.begin();
705 ii != BB.end();
706 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000707 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000708 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000709
Sean Callanane8a59a82010-09-13 21:34:21 +0000710 if (m_resolve_vars)
711 {
712 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
713 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
714 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000715
Sean Callanane8a59a82010-09-13 21:34:21 +0000716 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
717 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
718 return false;
719 }
Sean Callananba992c52010-07-27 02:07:53 +0000720
721 if (CallInst *call = dyn_cast<CallInst>(&inst))
722 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000723 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000724 }
725
726 return true;
727}
728
Sean Callanan02fbafa2010-07-27 21:39:39 +0000729static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000730{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000731 Constant *C;
Sean Callanan45839272010-07-24 01:37:44 +0000732
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000733 if (!(C = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +0000734 return false;
735
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000736 ConstantExpr *CE;
737
738 if ((CE = dyn_cast<ConstantExpr>(V)))
739 {
740 if (CE->getOpcode() != Instruction::BitCast)
741 return false;
742
743 C = CE->getOperand(0);
744 }
745
746 GlobalVariable *GV = dyn_cast<GlobalVariable>(C);
Sean Callanan45839272010-07-24 01:37:44 +0000747
748 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
749 return false;
750
751 return true;
752}
753
754static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
755{
756 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
757
758 Value::use_iterator ui;
759
760 for (ui = guard_load->use_begin();
761 ui != guard_load->use_end();
762 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000763 {
Greg Clayton6e713402010-07-30 20:30:44 +0000764 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000765 {
766 // do nothing for the moment
767 }
768 else
769 {
770 ui->replaceUsesOfWith(guard_load, zero);
771 }
772 }
Sean Callanan45839272010-07-24 01:37:44 +0000773
774 guard_load->eraseFromParent();
775}
776
777static void ExciseGuardStore(Instruction* guard_store)
778{
779 guard_store->eraseFromParent();
780}
781
782bool
783IRForTarget::removeGuards(Module &M, BasicBlock &BB)
784{
785 ///////////////////////////////////////////////////////
786 // Eliminate any reference to guard variables found.
787 //
788
Sean Callanan02fbafa2010-07-27 21:39:39 +0000789 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000790
Sean Callanan02fbafa2010-07-27 21:39:39 +0000791 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000792 typedef InstrList::iterator InstrIterator;
793
794 InstrList guard_loads;
795 InstrList guard_stores;
796
797 for (ii = BB.begin();
798 ii != BB.end();
799 ++ii)
800 {
801 Instruction &inst = *ii;
802
803 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
804 if (isGuardVariableRef(load->getPointerOperand()))
805 guard_loads.push_back(&inst);
806
807 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
808 if (isGuardVariableRef(store->getPointerOperand()))
809 guard_stores.push_back(&inst);
810 }
811
812 InstrIterator iter;
813
814 for (iter = guard_loads.begin();
815 iter != guard_loads.end();
816 ++iter)
817 TurnGuardLoadIntoZero(*iter, M);
818
819 for (iter = guard_stores.begin();
820 iter != guard_stores.end();
821 ++iter)
822 ExciseGuardStore(*iter);
823
824 return true;
825}
826
Sean Callananbafd6852010-07-14 23:40:29 +0000827// UnfoldConstant operates on a constant [C] which has just been replaced with a value
828// [new_value]. We assume that new_value has been properly placed early in the function,
829// most likely somewhere in front of the first instruction in the entry basic block
830// [first_entry_instruction].
831//
832// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
833// Where those uses are constants, the function generates new instructions to compute the
834// result of the new, non-constant expression and places them before first_entry_instruction.
835// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
836// for those.
837
838static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000839UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000840{
841 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
842
843 Value::use_iterator ui;
844
Sean Callanana48fe162010-08-11 03:57:18 +0000845 SmallVector<User*, 16> users;
846
847 // We do this because the use list might change, invalidating our iterator.
848 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000849 for (ui = C->use_begin();
850 ui != C->use_end();
851 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000852 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000853
Sean Callanana48fe162010-08-11 03:57:18 +0000854 for (int i = 0;
855 i < users.size();
856 ++i)
857 {
858 User *user = users[i];
859
Sean Callananbafd6852010-07-14 23:40:29 +0000860 if (Constant *constant = dyn_cast<Constant>(user))
861 {
862 // synthesize a new non-constant equivalent of the constant
863
864 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
865 {
866 switch (constant_expr->getOpcode())
867 {
868 default:
869 if (log)
870 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
871 return false;
872 case Instruction::BitCast:
873 {
874 // UnaryExpr
875 // OperandList[0] is value
876
877 Value *s = constant_expr->getOperand(0);
878
879 if (s == C)
880 s = new_value;
881
882 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
883
884 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
885 }
886 break;
887 case Instruction::GetElementPtr:
888 {
889 // GetElementPtrConstantExpr
890 // OperandList[0] is base
891 // OperandList[1]... are indices
892
893 Value *ptr = constant_expr->getOperand(0);
894
895 if (ptr == C)
896 ptr = new_value;
897
898 SmallVector<Value*, 16> indices;
899
900 unsigned operand_index;
901 unsigned num_operands = constant_expr->getNumOperands();
902
903 for (operand_index = 1;
904 operand_index < num_operands;
905 ++operand_index)
906 {
907 Value *operand = constant_expr->getOperand(operand_index);
908
909 if (operand == C)
910 operand = new_value;
911
912 indices.push_back(operand);
913 }
914
915 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
916
917 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
918 }
919 break;
920 }
921 }
922 else
923 {
924 if (log)
925 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
926 return false;
927 }
928 }
929 else
930 {
931 // simple fall-through case for non-constants
932 user->replaceUsesOfWith(C, new_value);
933 }
934 }
935
936 return true;
937}
938
Sean Callanan8bce6652010-07-13 21:41:46 +0000939bool
Sean Callananf5857a02010-07-31 01:32:05 +0000940IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000941{
Sean Callanane8a59a82010-09-13 21:34:21 +0000942 if (!m_resolve_vars)
943 return true;
944
Sean Callanan8bce6652010-07-13 21:41:46 +0000945 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
946
947 m_decl_map->DoStructLayout();
948
949 if (log)
950 log->Printf("Element arrangement:");
951
952 uint32_t num_elements;
953 uint32_t element_index;
954
955 size_t size;
956 off_t alignment;
957
958 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
959 return false;
960
Sean Callananf5857a02010-07-31 01:32:05 +0000961 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000962
Sean Callananf5857a02010-07-31 01:32:05 +0000963 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000964 return false;
965
Sean Callanan02fbafa2010-07-27 21:39:39 +0000966 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000967
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000968 if (argument->getName().equals("this"))
969 {
970 ++iter;
971
972 if (iter == F.getArgumentList().end())
973 return false;
974
975 argument = iter;
976 }
977
Sean Callanan8bce6652010-07-13 21:41:46 +0000978 if (!argument->getName().equals("___clang_arg"))
979 return false;
980
981 if (log)
982 log->Printf("Arg: %s", PrintValue(argument).c_str());
983
Sean Callananf5857a02010-07-31 01:32:05 +0000984 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000985 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000986
987 if (!first_entry_instruction)
988 return false;
989
990 LLVMContext &context(M.getContext());
991 const IntegerType *offset_type(Type::getInt32Ty(context));
992
993 if (!offset_type)
994 return false;
995
996 for (element_index = 0; element_index < num_elements; ++element_index)
997 {
998 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000999 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +00001000 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +00001001 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +00001002
Sean Callanan45690fe2010-08-30 22:17:16 +00001003 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +00001004 return false;
1005
1006 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +00001007 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00001008 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +00001009 name,
Sean Callanan8bce6652010-07-13 21:41:46 +00001010 PrintValue(value, true).c_str(),
1011 offset);
1012
1013 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
1014 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
1015 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
1016
Sean Callananbafd6852010-07-14 23:40:29 +00001017 if (Constant *constant = dyn_cast<Constant>(value))
1018 UnfoldConstant(constant, bit_cast, first_entry_instruction);
1019 else
1020 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +00001021 }
1022
1023 if (log)
1024 log->Printf("Total structure [align %d, size %d]", alignment, size);
1025
1026 return true;
1027}
1028
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001029bool
1030IRForTarget::runOnModule(Module &M)
1031{
1032 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
1033
Sean Callanan65dafa82010-08-27 01:01:44 +00001034 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001035
1036 if (!function)
1037 {
1038 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +00001039 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001040
1041 return false;
1042 }
1043
Sean Callanan02fbafa2010-07-27 21:39:39 +00001044 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001045
Sean Callanan82b74c82010-08-12 01:56:52 +00001046 ////////////////////////////////////////////////////////////
1047 // Replace __clang_expr_result with a persistent variable
1048 //
1049
1050 if (!createResultVariable(M, *function))
1051 return false;
1052
Sean Callananf5857a02010-07-31 01:32:05 +00001053 //////////////////////////////////
1054 // Run basic-block level passes
1055 //
1056
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001057 for (bbi = function->begin();
1058 bbi != function->end();
1059 ++bbi)
1060 {
Sean Callanan8c127202010-08-23 23:09:38 +00001061 if (!removeGuards(M, *bbi))
1062 return false;
1063
Sean Callanana48fe162010-08-11 03:57:18 +00001064 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +00001065 return false;
1066
Sean Callanana48fe162010-08-11 03:57:18 +00001067 if (!rewriteObjCSelectors(M, *bbi))
1068 return false;
1069
Sean Callananf5857a02010-07-31 01:32:05 +00001070 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001071 return false;
1072 }
1073
Sean Callanan8bce6652010-07-13 21:41:46 +00001074 if (log)
1075 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001076 std::string s;
1077 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001078
Sean Callanan321fe9e2010-07-28 01:00:59 +00001079 M.print(oss, NULL);
1080
1081 oss.flush();
1082
1083 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001084 }
1085
Sean Callanana48fe162010-08-11 03:57:18 +00001086 ///////////////////////////////
1087 // Run function-level passes
1088 //
1089
1090 if (!replaceVariables(M, *function))
1091 return false;
1092
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001093 return true;
1094}
1095
1096void
1097IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001098 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001099{
1100}
1101
1102PassManagerType
1103IRForTarget::getPotentialPassManagerType() const
1104{
1105 return PMT_ModulePassManager;
1106}