blob: cec358381d5961425790c607583f7b8002dc77e8 [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 Callanana6223432010-08-20 01:02:30 +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{
731 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
732
733 if (!C || C->getOpcode() != Instruction::BitCast)
734 return false;
735
736 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
737
738 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
739 return false;
740
741 return true;
742}
743
744static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
745{
746 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
747
748 Value::use_iterator ui;
749
750 for (ui = guard_load->use_begin();
751 ui != guard_load->use_end();
752 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000753 {
Greg Clayton6e713402010-07-30 20:30:44 +0000754 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000755 {
756 // do nothing for the moment
757 }
758 else
759 {
760 ui->replaceUsesOfWith(guard_load, zero);
761 }
762 }
Sean Callanan45839272010-07-24 01:37:44 +0000763
764 guard_load->eraseFromParent();
765}
766
767static void ExciseGuardStore(Instruction* guard_store)
768{
769 guard_store->eraseFromParent();
770}
771
772bool
773IRForTarget::removeGuards(Module &M, BasicBlock &BB)
774{
775 ///////////////////////////////////////////////////////
776 // Eliminate any reference to guard variables found.
777 //
778
Sean Callanan02fbafa2010-07-27 21:39:39 +0000779 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000780
Sean Callanan02fbafa2010-07-27 21:39:39 +0000781 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000782 typedef InstrList::iterator InstrIterator;
783
784 InstrList guard_loads;
785 InstrList guard_stores;
786
787 for (ii = BB.begin();
788 ii != BB.end();
789 ++ii)
790 {
791 Instruction &inst = *ii;
792
793 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
794 if (isGuardVariableRef(load->getPointerOperand()))
795 guard_loads.push_back(&inst);
796
797 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
798 if (isGuardVariableRef(store->getPointerOperand()))
799 guard_stores.push_back(&inst);
800 }
801
802 InstrIterator iter;
803
804 for (iter = guard_loads.begin();
805 iter != guard_loads.end();
806 ++iter)
807 TurnGuardLoadIntoZero(*iter, M);
808
809 for (iter = guard_stores.begin();
810 iter != guard_stores.end();
811 ++iter)
812 ExciseGuardStore(*iter);
813
814 return true;
815}
816
Sean Callananbafd6852010-07-14 23:40:29 +0000817// UnfoldConstant operates on a constant [C] which has just been replaced with a value
818// [new_value]. We assume that new_value has been properly placed early in the function,
819// most likely somewhere in front of the first instruction in the entry basic block
820// [first_entry_instruction].
821//
822// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
823// Where those uses are constants, the function generates new instructions to compute the
824// result of the new, non-constant expression and places them before first_entry_instruction.
825// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
826// for those.
827
828static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000829UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000830{
831 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
832
833 Value::use_iterator ui;
834
Sean Callanana48fe162010-08-11 03:57:18 +0000835 SmallVector<User*, 16> users;
836
837 // We do this because the use list might change, invalidating our iterator.
838 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000839 for (ui = C->use_begin();
840 ui != C->use_end();
841 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000842 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000843
Sean Callanana48fe162010-08-11 03:57:18 +0000844 for (int i = 0;
845 i < users.size();
846 ++i)
847 {
848 User *user = users[i];
849
Sean Callananbafd6852010-07-14 23:40:29 +0000850 if (Constant *constant = dyn_cast<Constant>(user))
851 {
852 // synthesize a new non-constant equivalent of the constant
853
854 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
855 {
856 switch (constant_expr->getOpcode())
857 {
858 default:
859 if (log)
860 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
861 return false;
862 case Instruction::BitCast:
863 {
864 // UnaryExpr
865 // OperandList[0] is value
866
867 Value *s = constant_expr->getOperand(0);
868
869 if (s == C)
870 s = new_value;
871
872 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
873
874 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
875 }
876 break;
877 case Instruction::GetElementPtr:
878 {
879 // GetElementPtrConstantExpr
880 // OperandList[0] is base
881 // OperandList[1]... are indices
882
883 Value *ptr = constant_expr->getOperand(0);
884
885 if (ptr == C)
886 ptr = new_value;
887
888 SmallVector<Value*, 16> indices;
889
890 unsigned operand_index;
891 unsigned num_operands = constant_expr->getNumOperands();
892
893 for (operand_index = 1;
894 operand_index < num_operands;
895 ++operand_index)
896 {
897 Value *operand = constant_expr->getOperand(operand_index);
898
899 if (operand == C)
900 operand = new_value;
901
902 indices.push_back(operand);
903 }
904
905 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
906
907 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
908 }
909 break;
910 }
911 }
912 else
913 {
914 if (log)
915 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
916 return false;
917 }
918 }
919 else
920 {
921 // simple fall-through case for non-constants
922 user->replaceUsesOfWith(C, new_value);
923 }
924 }
925
926 return true;
927}
928
Sean Callanan8bce6652010-07-13 21:41:46 +0000929bool
Sean Callananf5857a02010-07-31 01:32:05 +0000930IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000931{
Sean Callanane8a59a82010-09-13 21:34:21 +0000932 if (!m_resolve_vars)
933 return true;
934
Sean Callanan8bce6652010-07-13 21:41:46 +0000935 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
936
937 m_decl_map->DoStructLayout();
938
939 if (log)
940 log->Printf("Element arrangement:");
941
942 uint32_t num_elements;
943 uint32_t element_index;
944
945 size_t size;
946 off_t alignment;
947
948 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
949 return false;
950
Sean Callananf5857a02010-07-31 01:32:05 +0000951 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000952
Sean Callananf5857a02010-07-31 01:32:05 +0000953 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000954 return false;
955
Sean Callanan02fbafa2010-07-27 21:39:39 +0000956 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000957
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000958 if (argument->getName().equals("this"))
959 {
960 ++iter;
961
962 if (iter == F.getArgumentList().end())
963 return false;
964
965 argument = iter;
966 }
967
Sean Callanan8bce6652010-07-13 21:41:46 +0000968 if (!argument->getName().equals("___clang_arg"))
969 return false;
970
971 if (log)
972 log->Printf("Arg: %s", PrintValue(argument).c_str());
973
Sean Callananf5857a02010-07-31 01:32:05 +0000974 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000975 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000976
977 if (!first_entry_instruction)
978 return false;
979
980 LLVMContext &context(M.getContext());
981 const IntegerType *offset_type(Type::getInt32Ty(context));
982
983 if (!offset_type)
984 return false;
985
986 for (element_index = 0; element_index < num_elements; ++element_index)
987 {
988 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000989 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000990 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +0000991 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +0000992
Sean Callanan45690fe2010-08-30 22:17:16 +0000993 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +0000994 return false;
995
996 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +0000997 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000998 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +0000999 name,
Sean Callanan8bce6652010-07-13 21:41:46 +00001000 PrintValue(value, true).c_str(),
1001 offset);
1002
1003 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
1004 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
1005 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
1006
Sean Callananbafd6852010-07-14 23:40:29 +00001007 if (Constant *constant = dyn_cast<Constant>(value))
1008 UnfoldConstant(constant, bit_cast, first_entry_instruction);
1009 else
1010 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +00001011 }
1012
1013 if (log)
1014 log->Printf("Total structure [align %d, size %d]", alignment, size);
1015
1016 return true;
1017}
1018
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001019bool
1020IRForTarget::runOnModule(Module &M)
1021{
1022 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
1023
Sean Callanan65dafa82010-08-27 01:01:44 +00001024 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001025
1026 if (!function)
1027 {
1028 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +00001029 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001030
1031 return false;
1032 }
1033
Sean Callanan02fbafa2010-07-27 21:39:39 +00001034 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001035
Sean Callanan82b74c82010-08-12 01:56:52 +00001036 ////////////////////////////////////////////////////////////
1037 // Replace __clang_expr_result with a persistent variable
1038 //
1039
1040 if (!createResultVariable(M, *function))
1041 return false;
1042
Sean Callananf5857a02010-07-31 01:32:05 +00001043 //////////////////////////////////
1044 // Run basic-block level passes
1045 //
1046
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001047 for (bbi = function->begin();
1048 bbi != function->end();
1049 ++bbi)
1050 {
Sean Callanan8c127202010-08-23 23:09:38 +00001051 if (!removeGuards(M, *bbi))
1052 return false;
1053
Sean Callanana48fe162010-08-11 03:57:18 +00001054 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +00001055 return false;
1056
Sean Callanana48fe162010-08-11 03:57:18 +00001057 if (!rewriteObjCSelectors(M, *bbi))
1058 return false;
1059
Sean Callananf5857a02010-07-31 01:32:05 +00001060 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001061 return false;
1062 }
1063
Sean Callanan8bce6652010-07-13 21:41:46 +00001064 if (log)
1065 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001066 std::string s;
1067 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001068
Sean Callanan321fe9e2010-07-28 01:00:59 +00001069 M.print(oss, NULL);
1070
1071 oss.flush();
1072
1073 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001074 }
1075
Sean Callanana48fe162010-08-11 03:57:18 +00001076 ///////////////////////////////
1077 // Run function-level passes
1078 //
1079
1080 if (!replaceVariables(M, *function))
1081 return false;
1082
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001083 return true;
1084}
1085
1086void
1087IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001088 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001089{
1090}
1091
1092PassManagerType
1093IRForTarget::getPotentialPassManagerType() const
1094{
1095 return PMT_ModulePassManager;
1096}