blob: b76dd2c57761d3b852bb53635a8568f505923aa2 [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,
35 const char *func_name) :
Sean Callanana6223432010-08-20 01:02:30 +000036 ModulePass(&ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000037 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000038 m_target_data(target_data),
Sean Callanan65dafa82010-08-27 01:01:44 +000039 m_sel_registerName(NULL),
40 m_func_name(func_name)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000041{
42}
43
Sean Callanana48fe162010-08-11 03:57:18 +000044/* A handy utility function used at several places in the code */
45
46static std::string
47PrintValue(Value *V, bool truncate = false)
48{
49 std::string s;
50 raw_string_ostream rso(s);
51 V->print(rso);
52 rso.flush();
53 if (truncate)
54 s.resize(s.length() - 1);
55 return s;
56}
57
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000058IRForTarget::~IRForTarget()
59{
60}
61
Sean Callanan82b74c82010-08-12 01:56:52 +000062bool
63IRForTarget::createResultVariable(llvm::Module &M,
64 llvm::Function &F)
65{
66 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
67
68 // Find the result variable
69
70 Value *result_value = M.getNamedValue("___clang_expr_result");
71
72 if (!result_value)
73 {
74 if (log)
75 log->PutCString("Couldn't find result variable");
76 return false;
77 }
78
79 if (log)
80 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
81
82 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
83
84 if (!result_global)
85 {
86 if (log)
87 log->PutCString("Result variable isn't a GlobalVariable");
88 return false;
89 }
90
91 // Find the metadata and follow it to the VarDecl
92
93 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
94
95 if (!named_metadata)
96 {
97 if (log)
98 log->PutCString("No global metadata");
99
100 return false;
101 }
102
103 unsigned num_nodes = named_metadata->getNumOperands();
104 unsigned node_index;
105
106 MDNode *metadata_node = NULL;
107
108 for (node_index = 0;
109 node_index < num_nodes;
110 ++node_index)
111 {
112 metadata_node = named_metadata->getOperand(node_index);
113
114 if (metadata_node->getNumOperands() != 2)
115 continue;
116
117 if (metadata_node->getOperand(0) == result_global)
118 break;
119 }
120
121 if (!metadata_node)
122 {
123 if (log)
124 log->PutCString("Couldn't find result metadata");
125 return false;
126 }
127
128 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
129
130 uint64_t result_decl_intptr = constant_int->getZExtValue();
131
132 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
133
134 // Get the next available result name from m_decl_map and create the persistent
135 // variable for it
136
137 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
138 &result_decl->getASTContext());
139 std::string new_result_name;
140
141 m_decl_map->GetPersistentResultName(new_result_name);
Sean Callanan8c127202010-08-23 23:09:38 +0000142 m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000143
144 if (log)
145 log->Printf("Creating a new result global: %s", new_result_name.c_str());
146
147 // Construct a new result global and set up its metadata
148
149 GlobalVariable *new_result_global = new GlobalVariable(M,
150 result_global->getType()->getElementType(),
151 false, /* not constant */
152 GlobalValue::ExternalLinkage,
153 NULL, /* no initializer */
154 new_result_name.c_str());
155
156 // It's too late in compilation to create a new VarDecl for this, but we don't
157 // need to. We point the metadata at the old VarDecl. This creates an odd
158 // anomaly: a variable with a Value whose name is something like $0 and a
159 // Decl whose name is ___clang_expr_result. This condition is handled in
160 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
161 // fixed up.
162
163 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
164 result_decl_intptr,
165 false);
166
167 llvm::Value* values[2];
168 values[0] = new_result_global;
169 values[1] = new_constant_int;
170
171 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
172 named_metadata->addOperand(persistent_global_md);
173
174 if (log)
175 log->Printf("Replacing %s with %s",
176 PrintValue(result_global).c_str(),
177 PrintValue(new_result_global).c_str());
178
179 result_global->replaceAllUsesWith(new_result_global);
180 result_global->eraseFromParent();
181
182 return true;
183}
184
Sean Callananf5857a02010-07-31 01:32:05 +0000185static bool isObjCSelectorRef(Value *V)
186{
187 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
188
189 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
190 return false;
191
192 return true;
193}
194
195bool
196IRForTarget::RewriteObjCSelector(Instruction* selector_load,
197 Module &M)
198{
199 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
200
201 LoadInst *load = dyn_cast<LoadInst>(selector_load);
202
203 if (!load)
204 return false;
205
206 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
207 //
208 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
209 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
210 //
211 // where %obj is the object pointer and %tmp is the selector.
212 //
213 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
214 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
215
216 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
217
218 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
219
220 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
221 return false;
222
223 Constant *osr_initializer = _objc_selector_references_->getInitializer();
224
225 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
226
227 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
228 return false;
229
230 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
231
232 if (!osr_initializer_base)
233 return false;
234
235 // Find the string's initializer (a ConstantArray) and get the string from it
236
237 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
238
239 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
240 return false;
241
242 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
243
244 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
245
246 if (!omvn_initializer_array->isString())
247 return false;
248
249 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
250
251 if (log)
252 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
253
254 // Construct a call to sel_registerName
255
256 if (!m_sel_registerName)
257 {
258 uint64_t srN_addr;
259
260 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
261 return false;
262
263 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
264
265 // The below code would be "more correct," but in actuality what's required is uint8_t*
266 //Type *sel_type = StructType::get(M.getContext());
267 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
268 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
269
270 std::vector <const Type *> srN_arg_types;
271 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
272 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
273
274 // Build the constant containing the pointer to the function
275 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
276 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
277 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
278 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
279 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
280 }
281
282 SmallVector <Value*, 1> srN_arguments;
283
284 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
285
286 srN_arguments.push_back(omvn_pointer);
287
288 CallInst *srN_call = CallInst::Create(m_sel_registerName,
289 srN_arguments.begin(),
290 srN_arguments.end(),
291 "srN",
292 selector_load);
293
294 // Replace the load with the call in all users
295
296 selector_load->replaceAllUsesWith(srN_call);
297
298 selector_load->eraseFromParent();
299
300 return true;
301}
302
303bool
304IRForTarget::rewriteObjCSelectors(Module &M,
305 BasicBlock &BB)
306{
307 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
308
309 BasicBlock::iterator ii;
310
311 typedef SmallVector <Instruction*, 2> InstrList;
312 typedef InstrList::iterator InstrIterator;
313
314 InstrList selector_loads;
315
316 for (ii = BB.begin();
317 ii != BB.end();
318 ++ii)
319 {
320 Instruction &inst = *ii;
321
322 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
323 if (isObjCSelectorRef(load->getPointerOperand()))
324 selector_loads.push_back(&inst);
325 }
326
327 InstrIterator iter;
328
329 for (iter = selector_loads.begin();
330 iter != selector_loads.end();
331 ++iter)
332 {
333 if (!RewriteObjCSelector(*iter, M))
334 {
335 if(log)
336 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
337 return false;
338 }
339 }
340
341 return true;
342}
343
Sean Callanana48fe162010-08-11 03:57:18 +0000344bool
345IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
346 llvm::Module &M)
347{
348 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
349
350 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
351
352 if (!alloc_md || !alloc_md->getNumOperands())
353 return false;
354
355 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
356
357 if (!constant_int)
358 return false;
359
360 // We attempt to register this as a new persistent variable with the DeclMap.
361
362 uintptr_t ptr = constant_int->getZExtValue();
363
Sean Callanan82b74c82010-08-12 01:56:52 +0000364 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000365
Sean Callanan82b74c82010-08-12 01:56:52 +0000366 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
367 &decl->getASTContext());
368
Sean Callanan8c127202010-08-23 23:09:38 +0000369 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000370 return false;
371
372 GlobalVariable *persistent_global = new GlobalVariable(M,
373 alloc->getType()->getElementType(),
374 false, /* not constant */
375 GlobalValue::ExternalLinkage,
376 NULL, /* no initializer */
377 alloc->getName().str().c_str());
378
379 // What we're going to do here is make believe this was a regular old external
380 // variable. That means we need to make the metadata valid.
381
382 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
383
384 llvm::Value* values[2];
385 values[0] = persistent_global;
386 values[1] = constant_int;
387
388 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
389 named_metadata->addOperand(persistent_global_md);
390
391 alloc->replaceAllUsesWith(persistent_global);
392 alloc->eraseFromParent();
393
394 return true;
395}
396
397bool
398IRForTarget::rewritePersistentAllocs(llvm::Module &M,
399 llvm::BasicBlock &BB)
400{
401 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
402
403 BasicBlock::iterator ii;
404
405 typedef SmallVector <Instruction*, 2> InstrList;
406 typedef InstrList::iterator InstrIterator;
407
408 InstrList pvar_allocs;
409
410 for (ii = BB.begin();
411 ii != BB.end();
412 ++ii)
413 {
414 Instruction &inst = *ii;
415
416 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
417 if (alloc->getName().startswith("$"))
418 pvar_allocs.push_back(alloc);
419 }
420
421 InstrIterator iter;
422
423 for (iter = pvar_allocs.begin();
424 iter != pvar_allocs.end();
425 ++iter)
426 {
427 if (!RewritePersistentAlloc(*iter, M))
428 {
429 if(log)
430 log->PutCString("Couldn't rewrite the creation of a persistent variable");
431 return false;
432 }
433 }
434
435 return true;
436}
437
Sean Callanan8bce6652010-07-13 21:41:46 +0000438static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000439DeclForGlobalValue(Module &module,
440 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000441{
442 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
443
444 if (!named_metadata)
445 return NULL;
446
447 unsigned num_nodes = named_metadata->getNumOperands();
448 unsigned node_index;
449
450 for (node_index = 0;
451 node_index < num_nodes;
452 ++node_index)
453 {
454 MDNode *metadata_node = named_metadata->getOperand(node_index);
455
456 if (!metadata_node)
457 return NULL;
458
459 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000460 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000461
462 if (metadata_node->getOperand(0) != global_value)
463 continue;
464
465 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
466
467 if (!constant_int)
468 return NULL;
469
470 uintptr_t ptr = constant_int->getZExtValue();
471
472 return reinterpret_cast<clang::NamedDecl *>(ptr);
473 }
474
475 return NULL;
476}
477
478bool
479IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000480 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000481 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000482{
Sean Callananf5857a02010-07-31 01:32:05 +0000483 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
484
Sean Callananbc2928a2010-08-03 00:23:29 +0000485 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
486 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000487 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000488 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000489 default:
490 break;
491 case Instruction::GetElementPtr:
492 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000493 Value *s = constant_expr->getOperand(0);
494 MaybeHandleVariable(M, s, Store);
495 }
496 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000497 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000498 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000499 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000500
Sean Callananf5857a02010-07-31 01:32:05 +0000501 if (!named_decl)
502 {
503 if (isObjCSelectorRef(V))
504 return true;
505
506 if (log)
507 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
508 return false;
509 }
510
Sean Callanan810f22d2010-07-16 00:09:46 +0000511 std::string name = named_decl->getName().str();
512
513 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000514 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000515
516 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000517 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000518 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000519 ast_context = &value_decl->getASTContext();
520 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000521 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000522 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000523 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000524 }
525
Sean Callanan02fbafa2010-07-27 21:39:39 +0000526 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000527
528 size_t value_size = m_target_data->getTypeStoreSize(value_type);
529 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
530
Sean Callanan8c127202010-08-23 23:09:38 +0000531 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Sean Callanan45690fe2010-08-30 22:17:16 +0000532 name.c_str(),
Sean Callanan8c127202010-08-23 23:09:38 +0000533 V,
Sean Callananba992c52010-07-27 02:07:53 +0000534 value_size,
535 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000536 return false;
537 }
538
539 return true;
540}
541
542bool
Sean Callananba992c52010-07-27 02:07:53 +0000543IRForTarget::MaybeHandleCall(Module &M,
544 CallInst *C)
545{
546 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
547
Sean Callanan02fbafa2010-07-27 21:39:39 +0000548 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000549
550 if (fun == NULL)
551 return true;
552
553 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000554 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000555 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000556
Sean Callananf5857a02010-07-31 01:32:05 +0000557 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000558 {
Sean Callananf5857a02010-07-31 01:32:05 +0000559 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
560 {
561 if (log)
562 log->Printf("Function %s had no address", fun_decl->getNameAsCString());
563 return false;
564 }
565 }
566 else
567 {
568 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
569 {
570 if (log)
571 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
572 return false;
573 }
Sean Callananba992c52010-07-27 02:07:53 +0000574 }
575
576 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000577 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000578
Sean Callananf5857a02010-07-31 01:32:05 +0000579 Value *fun_addr_ptr;
580
581 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000582 {
583 std::vector<const Type*> params;
584
585 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
586 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
587
588 FunctionType *fun_ty = FunctionType::get(intptr_ty, params, true);
589 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
590 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000591 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
592
593 if (fun_value_ptr)
594 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000595 }
Sean Callananf5857a02010-07-31 01:32:05 +0000596
597 if (fun_value_ptr)
598 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000599
Sean Callananf5857a02010-07-31 01:32:05 +0000600 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000601
Sean Callananba992c52010-07-27 02:07:53 +0000602 return true;
603}
604
605bool
Sean Callananf5857a02010-07-31 01:32:05 +0000606IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000607{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000608 /////////////////////////////////////////////////////////////////////////
609 // Prepare the current basic block for execution in the remote process
610 //
611
Sean Callanan02fbafa2010-07-27 21:39:39 +0000612 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000613
614 for (ii = BB.begin();
615 ii != BB.end();
616 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000617 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000618 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000619
Sean Callanan8bce6652010-07-13 21:41:46 +0000620 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000621 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000622 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000623
Sean Callanan8bce6652010-07-13 21:41:46 +0000624 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000625 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
626 return false;
627
628 if (CallInst *call = dyn_cast<CallInst>(&inst))
629 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000630 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000631 }
632
633 return true;
634}
635
Sean Callanan02fbafa2010-07-27 21:39:39 +0000636static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000637{
638 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
639
640 if (!C || C->getOpcode() != Instruction::BitCast)
641 return false;
642
643 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
644
645 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
646 return false;
647
648 return true;
649}
650
651static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
652{
653 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
654
655 Value::use_iterator ui;
656
657 for (ui = guard_load->use_begin();
658 ui != guard_load->use_end();
659 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000660 {
Greg Clayton6e713402010-07-30 20:30:44 +0000661 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000662 {
663 // do nothing for the moment
664 }
665 else
666 {
667 ui->replaceUsesOfWith(guard_load, zero);
668 }
669 }
Sean Callanan45839272010-07-24 01:37:44 +0000670
671 guard_load->eraseFromParent();
672}
673
674static void ExciseGuardStore(Instruction* guard_store)
675{
676 guard_store->eraseFromParent();
677}
678
679bool
680IRForTarget::removeGuards(Module &M, BasicBlock &BB)
681{
682 ///////////////////////////////////////////////////////
683 // Eliminate any reference to guard variables found.
684 //
685
Sean Callanan02fbafa2010-07-27 21:39:39 +0000686 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000687
Sean Callanan02fbafa2010-07-27 21:39:39 +0000688 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000689 typedef InstrList::iterator InstrIterator;
690
691 InstrList guard_loads;
692 InstrList guard_stores;
693
694 for (ii = BB.begin();
695 ii != BB.end();
696 ++ii)
697 {
698 Instruction &inst = *ii;
699
700 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
701 if (isGuardVariableRef(load->getPointerOperand()))
702 guard_loads.push_back(&inst);
703
704 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
705 if (isGuardVariableRef(store->getPointerOperand()))
706 guard_stores.push_back(&inst);
707 }
708
709 InstrIterator iter;
710
711 for (iter = guard_loads.begin();
712 iter != guard_loads.end();
713 ++iter)
714 TurnGuardLoadIntoZero(*iter, M);
715
716 for (iter = guard_stores.begin();
717 iter != guard_stores.end();
718 ++iter)
719 ExciseGuardStore(*iter);
720
721 return true;
722}
723
Sean Callananbafd6852010-07-14 23:40:29 +0000724// UnfoldConstant operates on a constant [C] which has just been replaced with a value
725// [new_value]. We assume that new_value has been properly placed early in the function,
726// most likely somewhere in front of the first instruction in the entry basic block
727// [first_entry_instruction].
728//
729// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
730// Where those uses are constants, the function generates new instructions to compute the
731// result of the new, non-constant expression and places them before first_entry_instruction.
732// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
733// for those.
734
735static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000736UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000737{
738 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
739
740 Value::use_iterator ui;
741
Sean Callanana48fe162010-08-11 03:57:18 +0000742 SmallVector<User*, 16> users;
743
744 // We do this because the use list might change, invalidating our iterator.
745 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000746 for (ui = C->use_begin();
747 ui != C->use_end();
748 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000749 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000750
Sean Callanana48fe162010-08-11 03:57:18 +0000751 for (int i = 0;
752 i < users.size();
753 ++i)
754 {
755 User *user = users[i];
756
Sean Callananbafd6852010-07-14 23:40:29 +0000757 if (Constant *constant = dyn_cast<Constant>(user))
758 {
759 // synthesize a new non-constant equivalent of the constant
760
761 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
762 {
763 switch (constant_expr->getOpcode())
764 {
765 default:
766 if (log)
767 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
768 return false;
769 case Instruction::BitCast:
770 {
771 // UnaryExpr
772 // OperandList[0] is value
773
774 Value *s = constant_expr->getOperand(0);
775
776 if (s == C)
777 s = new_value;
778
779 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
780
781 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
782 }
783 break;
784 case Instruction::GetElementPtr:
785 {
786 // GetElementPtrConstantExpr
787 // OperandList[0] is base
788 // OperandList[1]... are indices
789
790 Value *ptr = constant_expr->getOperand(0);
791
792 if (ptr == C)
793 ptr = new_value;
794
795 SmallVector<Value*, 16> indices;
796
797 unsigned operand_index;
798 unsigned num_operands = constant_expr->getNumOperands();
799
800 for (operand_index = 1;
801 operand_index < num_operands;
802 ++operand_index)
803 {
804 Value *operand = constant_expr->getOperand(operand_index);
805
806 if (operand == C)
807 operand = new_value;
808
809 indices.push_back(operand);
810 }
811
812 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
813
814 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
815 }
816 break;
817 }
818 }
819 else
820 {
821 if (log)
822 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
823 return false;
824 }
825 }
826 else
827 {
828 // simple fall-through case for non-constants
829 user->replaceUsesOfWith(C, new_value);
830 }
831 }
832
833 return true;
834}
835
Sean Callanan8bce6652010-07-13 21:41:46 +0000836bool
Sean Callananf5857a02010-07-31 01:32:05 +0000837IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000838{
839 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
840
841 m_decl_map->DoStructLayout();
842
843 if (log)
844 log->Printf("Element arrangement:");
845
846 uint32_t num_elements;
847 uint32_t element_index;
848
849 size_t size;
850 off_t alignment;
851
852 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
853 return false;
854
Sean Callananf5857a02010-07-31 01:32:05 +0000855 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000856
Sean Callananf5857a02010-07-31 01:32:05 +0000857 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000858 return false;
859
Sean Callanan02fbafa2010-07-27 21:39:39 +0000860 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000861
862 if (!argument->getName().equals("___clang_arg"))
863 return false;
864
865 if (log)
866 log->Printf("Arg: %s", PrintValue(argument).c_str());
867
Sean Callananf5857a02010-07-31 01:32:05 +0000868 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000869 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000870
871 if (!first_entry_instruction)
872 return false;
873
874 LLVMContext &context(M.getContext());
875 const IntegerType *offset_type(Type::getInt32Ty(context));
876
877 if (!offset_type)
878 return false;
879
880 for (element_index = 0; element_index < num_elements; ++element_index)
881 {
882 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000883 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000884 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +0000885 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +0000886
Sean Callanan45690fe2010-08-30 22:17:16 +0000887 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +0000888 return false;
889
890 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +0000891 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000892 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +0000893 name,
Sean Callanan8bce6652010-07-13 21:41:46 +0000894 PrintValue(value, true).c_str(),
895 offset);
896
897 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
898 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
899 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
900
Sean Callananbafd6852010-07-14 23:40:29 +0000901 if (Constant *constant = dyn_cast<Constant>(value))
902 UnfoldConstant(constant, bit_cast, first_entry_instruction);
903 else
904 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000905 }
906
907 if (log)
908 log->Printf("Total structure [align %d, size %d]", alignment, size);
909
910 return true;
911}
912
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000913bool
914IRForTarget::runOnModule(Module &M)
915{
916 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
917
Sean Callanan65dafa82010-08-27 01:01:44 +0000918 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000919
920 if (!function)
921 {
922 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000923 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000924
925 return false;
926 }
927
Sean Callanan02fbafa2010-07-27 21:39:39 +0000928 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000929
Sean Callanan82b74c82010-08-12 01:56:52 +0000930 ////////////////////////////////////////////////////////////
931 // Replace __clang_expr_result with a persistent variable
932 //
933
934 if (!createResultVariable(M, *function))
935 return false;
936
Sean Callananf5857a02010-07-31 01:32:05 +0000937 //////////////////////////////////
938 // Run basic-block level passes
939 //
940
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000941 for (bbi = function->begin();
942 bbi != function->end();
943 ++bbi)
944 {
Sean Callanan8c127202010-08-23 23:09:38 +0000945 if (!removeGuards(M, *bbi))
946 return false;
947
Sean Callanana48fe162010-08-11 03:57:18 +0000948 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000949 return false;
950
Sean Callanana48fe162010-08-11 03:57:18 +0000951 if (!rewriteObjCSelectors(M, *bbi))
952 return false;
953
Sean Callananf5857a02010-07-31 01:32:05 +0000954 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +0000955 return false;
956 }
957
Sean Callanan8bce6652010-07-13 21:41:46 +0000958 if (log)
959 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000960 std::string s;
961 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +0000962
Sean Callanan321fe9e2010-07-28 01:00:59 +0000963 M.print(oss, NULL);
964
965 oss.flush();
966
967 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000968 }
969
Sean Callanana48fe162010-08-11 03:57:18 +0000970 ///////////////////////////////
971 // Run function-level passes
972 //
973
974 if (!replaceVariables(M, *function))
975 return false;
976
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000977 return true;
978}
979
980void
981IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +0000982 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000983{
984}
985
986PassManagerType
987IRForTarget::getPotentialPassManagerType() const
988{
989 return PMT_ModulePassManager;
990}