blob: ca1aeb4327c82b4b2851761c2497b4fcf05ec042 [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
31IRForTarget::IRForTarget(const void *pid,
Sean Callanan8bce6652010-07-13 21:41:46 +000032 lldb_private::ClangExpressionDeclMap *decl_map,
Sean Callanan02fbafa2010-07-27 21:39:39 +000033 const TargetData *target_data) :
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000034 ModulePass(pid),
Sean Callanan8bce6652010-07-13 21:41:46 +000035 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000036 m_target_data(target_data),
37 m_sel_registerName(NULL)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000038{
39}
40
Sean Callanana48fe162010-08-11 03:57:18 +000041/* A handy utility function used at several places in the code */
42
43static std::string
44PrintValue(Value *V, bool truncate = false)
45{
46 std::string s;
47 raw_string_ostream rso(s);
48 V->print(rso);
49 rso.flush();
50 if (truncate)
51 s.resize(s.length() - 1);
52 return s;
53}
54
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000055IRForTarget::~IRForTarget()
56{
57}
58
Sean Callanan82b74c82010-08-12 01:56:52 +000059bool
60IRForTarget::createResultVariable(llvm::Module &M,
61 llvm::Function &F)
62{
63 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
64
65 // Find the result variable
66
67 Value *result_value = M.getNamedValue("___clang_expr_result");
68
69 if (!result_value)
70 {
71 if (log)
72 log->PutCString("Couldn't find result variable");
73 return false;
74 }
75
76 if (log)
77 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
78
79 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
80
81 if (!result_global)
82 {
83 if (log)
84 log->PutCString("Result variable isn't a GlobalVariable");
85 return false;
86 }
87
88 // Find the metadata and follow it to the VarDecl
89
90 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
91
92 if (!named_metadata)
93 {
94 if (log)
95 log->PutCString("No global metadata");
96
97 return false;
98 }
99
100 unsigned num_nodes = named_metadata->getNumOperands();
101 unsigned node_index;
102
103 MDNode *metadata_node = NULL;
104
105 for (node_index = 0;
106 node_index < num_nodes;
107 ++node_index)
108 {
109 metadata_node = named_metadata->getOperand(node_index);
110
111 if (metadata_node->getNumOperands() != 2)
112 continue;
113
114 if (metadata_node->getOperand(0) == result_global)
115 break;
116 }
117
118 if (!metadata_node)
119 {
120 if (log)
121 log->PutCString("Couldn't find result metadata");
122 return false;
123 }
124
125 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
126
127 uint64_t result_decl_intptr = constant_int->getZExtValue();
128
129 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
130
131 // Get the next available result name from m_decl_map and create the persistent
132 // variable for it
133
134 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
135 &result_decl->getASTContext());
136 std::string new_result_name;
137
138 m_decl_map->GetPersistentResultName(new_result_name);
139 m_decl_map->AddPersistentVariable(new_result_name.c_str(), result_decl_type);
140
141 if (log)
142 log->Printf("Creating a new result global: %s", new_result_name.c_str());
143
144 // Construct a new result global and set up its metadata
145
146 GlobalVariable *new_result_global = new GlobalVariable(M,
147 result_global->getType()->getElementType(),
148 false, /* not constant */
149 GlobalValue::ExternalLinkage,
150 NULL, /* no initializer */
151 new_result_name.c_str());
152
153 // It's too late in compilation to create a new VarDecl for this, but we don't
154 // need to. We point the metadata at the old VarDecl. This creates an odd
155 // anomaly: a variable with a Value whose name is something like $0 and a
156 // Decl whose name is ___clang_expr_result. This condition is handled in
157 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
158 // fixed up.
159
160 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
161 result_decl_intptr,
162 false);
163
164 llvm::Value* values[2];
165 values[0] = new_result_global;
166 values[1] = new_constant_int;
167
168 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
169 named_metadata->addOperand(persistent_global_md);
170
171 if (log)
172 log->Printf("Replacing %s with %s",
173 PrintValue(result_global).c_str(),
174 PrintValue(new_result_global).c_str());
175
176 result_global->replaceAllUsesWith(new_result_global);
177 result_global->eraseFromParent();
178
179 return true;
180}
181
Sean Callananf5857a02010-07-31 01:32:05 +0000182static bool isObjCSelectorRef(Value *V)
183{
184 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
185
186 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
187 return false;
188
189 return true;
190}
191
192bool
193IRForTarget::RewriteObjCSelector(Instruction* selector_load,
194 Module &M)
195{
196 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
197
198 LoadInst *load = dyn_cast<LoadInst>(selector_load);
199
200 if (!load)
201 return false;
202
203 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
204 //
205 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
206 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
207 //
208 // where %obj is the object pointer and %tmp is the selector.
209 //
210 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
211 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
212
213 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
214
215 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
216
217 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
218 return false;
219
220 Constant *osr_initializer = _objc_selector_references_->getInitializer();
221
222 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
223
224 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
225 return false;
226
227 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
228
229 if (!osr_initializer_base)
230 return false;
231
232 // Find the string's initializer (a ConstantArray) and get the string from it
233
234 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
235
236 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
237 return false;
238
239 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
240
241 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
242
243 if (!omvn_initializer_array->isString())
244 return false;
245
246 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
247
248 if (log)
249 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
250
251 // Construct a call to sel_registerName
252
253 if (!m_sel_registerName)
254 {
255 uint64_t srN_addr;
256
257 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
258 return false;
259
260 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
261
262 // The below code would be "more correct," but in actuality what's required is uint8_t*
263 //Type *sel_type = StructType::get(M.getContext());
264 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
265 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
266
267 std::vector <const Type *> srN_arg_types;
268 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
269 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
270
271 // Build the constant containing the pointer to the function
272 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
273 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
274 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
275 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
276 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
277 }
278
279 SmallVector <Value*, 1> srN_arguments;
280
281 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
282
283 srN_arguments.push_back(omvn_pointer);
284
285 CallInst *srN_call = CallInst::Create(m_sel_registerName,
286 srN_arguments.begin(),
287 srN_arguments.end(),
288 "srN",
289 selector_load);
290
291 // Replace the load with the call in all users
292
293 selector_load->replaceAllUsesWith(srN_call);
294
295 selector_load->eraseFromParent();
296
297 return true;
298}
299
300bool
301IRForTarget::rewriteObjCSelectors(Module &M,
302 BasicBlock &BB)
303{
304 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
305
306 BasicBlock::iterator ii;
307
308 typedef SmallVector <Instruction*, 2> InstrList;
309 typedef InstrList::iterator InstrIterator;
310
311 InstrList selector_loads;
312
313 for (ii = BB.begin();
314 ii != BB.end();
315 ++ii)
316 {
317 Instruction &inst = *ii;
318
319 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
320 if (isObjCSelectorRef(load->getPointerOperand()))
321 selector_loads.push_back(&inst);
322 }
323
324 InstrIterator iter;
325
326 for (iter = selector_loads.begin();
327 iter != selector_loads.end();
328 ++iter)
329 {
330 if (!RewriteObjCSelector(*iter, M))
331 {
332 if(log)
333 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
334 return false;
335 }
336 }
337
338 return true;
339}
340
Sean Callanana48fe162010-08-11 03:57:18 +0000341bool
342IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
343 llvm::Module &M)
344{
345 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
346
347 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
348
349 if (!alloc_md || !alloc_md->getNumOperands())
350 return false;
351
352 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
353
354 if (!constant_int)
355 return false;
356
357 // We attempt to register this as a new persistent variable with the DeclMap.
358
359 uintptr_t ptr = constant_int->getZExtValue();
360
Sean Callanan82b74c82010-08-12 01:56:52 +0000361 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000362
Sean Callanan82b74c82010-08-12 01:56:52 +0000363 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
364 &decl->getASTContext());
365
366 if (!m_decl_map->AddPersistentVariable(decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000367 return false;
368
369 GlobalVariable *persistent_global = new GlobalVariable(M,
370 alloc->getType()->getElementType(),
371 false, /* not constant */
372 GlobalValue::ExternalLinkage,
373 NULL, /* no initializer */
374 alloc->getName().str().c_str());
375
376 // What we're going to do here is make believe this was a regular old external
377 // variable. That means we need to make the metadata valid.
378
379 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
380
381 llvm::Value* values[2];
382 values[0] = persistent_global;
383 values[1] = constant_int;
384
385 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
386 named_metadata->addOperand(persistent_global_md);
387
388 alloc->replaceAllUsesWith(persistent_global);
389 alloc->eraseFromParent();
390
391 return true;
392}
393
394bool
395IRForTarget::rewritePersistentAllocs(llvm::Module &M,
396 llvm::BasicBlock &BB)
397{
398 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
399
400 BasicBlock::iterator ii;
401
402 typedef SmallVector <Instruction*, 2> InstrList;
403 typedef InstrList::iterator InstrIterator;
404
405 InstrList pvar_allocs;
406
407 for (ii = BB.begin();
408 ii != BB.end();
409 ++ii)
410 {
411 Instruction &inst = *ii;
412
413 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
414 if (alloc->getName().startswith("$"))
415 pvar_allocs.push_back(alloc);
416 }
417
418 InstrIterator iter;
419
420 for (iter = pvar_allocs.begin();
421 iter != pvar_allocs.end();
422 ++iter)
423 {
424 if (!RewritePersistentAlloc(*iter, M))
425 {
426 if(log)
427 log->PutCString("Couldn't rewrite the creation of a persistent variable");
428 return false;
429 }
430 }
431
432 return true;
433}
434
Sean Callanan8bce6652010-07-13 21:41:46 +0000435static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000436DeclForGlobalValue(Module &module,
437 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000438{
439 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
440
441 if (!named_metadata)
442 return NULL;
443
444 unsigned num_nodes = named_metadata->getNumOperands();
445 unsigned node_index;
446
447 for (node_index = 0;
448 node_index < num_nodes;
449 ++node_index)
450 {
451 MDNode *metadata_node = named_metadata->getOperand(node_index);
452
453 if (!metadata_node)
454 return NULL;
455
456 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000457 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000458
459 if (metadata_node->getOperand(0) != global_value)
460 continue;
461
462 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
463
464 if (!constant_int)
465 return NULL;
466
467 uintptr_t ptr = constant_int->getZExtValue();
468
469 return reinterpret_cast<clang::NamedDecl *>(ptr);
470 }
471
472 return NULL;
473}
474
475bool
476IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000477 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000478 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000479{
Sean Callananf5857a02010-07-31 01:32:05 +0000480 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
481
Sean Callananbc2928a2010-08-03 00:23:29 +0000482 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
483 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000484 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000485 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000486 default:
487 break;
488 case Instruction::GetElementPtr:
489 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000490 Value *s = constant_expr->getOperand(0);
491 MaybeHandleVariable(M, s, Store);
492 }
493 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000494 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000495 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000496 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000497
Sean Callananf5857a02010-07-31 01:32:05 +0000498 if (!named_decl)
499 {
500 if (isObjCSelectorRef(V))
501 return true;
502
503 if (log)
504 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
505 return false;
506 }
507
Sean Callanan810f22d2010-07-16 00:09:46 +0000508 std::string name = named_decl->getName().str();
509
510 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000511 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000512
513 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000514 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000515 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000516 ast_context = &value_decl->getASTContext();
517 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000518 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000519 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000520 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000521 }
522
Sean Callanan02fbafa2010-07-27 21:39:39 +0000523 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000524
525 size_t value_size = m_target_data->getTypeStoreSize(value_type);
526 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
527
Sean Callananba992c52010-07-27 02:07:53 +0000528 if (named_decl && !m_decl_map->AddValueToStruct(V,
529 named_decl,
530 name,
531 qual_type,
532 ast_context,
533 value_size,
534 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000535 return false;
536 }
537
538 return true;
539}
540
541bool
Sean Callananba992c52010-07-27 02:07:53 +0000542IRForTarget::MaybeHandleCall(Module &M,
543 CallInst *C)
544{
545 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
546
Sean Callanan02fbafa2010-07-27 21:39:39 +0000547 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000548
549 if (fun == NULL)
550 return true;
551
552 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000553 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000554 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000555
Sean Callananf5857a02010-07-31 01:32:05 +0000556 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000557 {
Sean Callananf5857a02010-07-31 01:32:05 +0000558 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
559 {
560 if (log)
561 log->Printf("Function %s had no address", fun_decl->getNameAsCString());
562 return false;
563 }
564 }
565 else
566 {
567 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
568 {
569 if (log)
570 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
571 return false;
572 }
Sean Callananba992c52010-07-27 02:07:53 +0000573 }
574
575 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000576 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000577
Sean Callananf5857a02010-07-31 01:32:05 +0000578 Value *fun_addr_ptr;
579
580 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000581 {
582 std::vector<const Type*> params;
583
584 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
585 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
586
587 FunctionType *fun_ty = FunctionType::get(intptr_ty, params, true);
588 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
589 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000590 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
591
592 if (fun_value_ptr)
593 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000594 }
Sean Callananf5857a02010-07-31 01:32:05 +0000595
596 if (fun_value_ptr)
597 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000598
Sean Callananf5857a02010-07-31 01:32:05 +0000599 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000600
Sean Callananba992c52010-07-27 02:07:53 +0000601 return true;
602}
603
604bool
Sean Callananf5857a02010-07-31 01:32:05 +0000605IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000606{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000607 /////////////////////////////////////////////////////////////////////////
608 // Prepare the current basic block for execution in the remote process
609 //
610
Sean Callanan02fbafa2010-07-27 21:39:39 +0000611 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000612
613 for (ii = BB.begin();
614 ii != BB.end();
615 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000616 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000617 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000618
Sean Callanan8bce6652010-07-13 21:41:46 +0000619 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000620 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000621 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000622
Sean Callanan8bce6652010-07-13 21:41:46 +0000623 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000624 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
625 return false;
626
627 if (CallInst *call = dyn_cast<CallInst>(&inst))
628 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000629 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000630 }
631
632 return true;
633}
634
Sean Callanan02fbafa2010-07-27 21:39:39 +0000635static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000636{
637 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
638
639 if (!C || C->getOpcode() != Instruction::BitCast)
640 return false;
641
642 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
643
644 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
645 return false;
646
647 return true;
648}
649
650static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
651{
652 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
653
654 Value::use_iterator ui;
655
656 for (ui = guard_load->use_begin();
657 ui != guard_load->use_end();
658 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000659 {
Greg Clayton6e713402010-07-30 20:30:44 +0000660 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000661 {
662 // do nothing for the moment
663 }
664 else
665 {
666 ui->replaceUsesOfWith(guard_load, zero);
667 }
668 }
Sean Callanan45839272010-07-24 01:37:44 +0000669
670 guard_load->eraseFromParent();
671}
672
673static void ExciseGuardStore(Instruction* guard_store)
674{
675 guard_store->eraseFromParent();
676}
677
678bool
679IRForTarget::removeGuards(Module &M, BasicBlock &BB)
680{
681 ///////////////////////////////////////////////////////
682 // Eliminate any reference to guard variables found.
683 //
684
Sean Callanan02fbafa2010-07-27 21:39:39 +0000685 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000686
Sean Callanan02fbafa2010-07-27 21:39:39 +0000687 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000688 typedef InstrList::iterator InstrIterator;
689
690 InstrList guard_loads;
691 InstrList guard_stores;
692
693 for (ii = BB.begin();
694 ii != BB.end();
695 ++ii)
696 {
697 Instruction &inst = *ii;
698
699 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
700 if (isGuardVariableRef(load->getPointerOperand()))
701 guard_loads.push_back(&inst);
702
703 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
704 if (isGuardVariableRef(store->getPointerOperand()))
705 guard_stores.push_back(&inst);
706 }
707
708 InstrIterator iter;
709
710 for (iter = guard_loads.begin();
711 iter != guard_loads.end();
712 ++iter)
713 TurnGuardLoadIntoZero(*iter, M);
714
715 for (iter = guard_stores.begin();
716 iter != guard_stores.end();
717 ++iter)
718 ExciseGuardStore(*iter);
719
720 return true;
721}
722
Sean Callananbafd6852010-07-14 23:40:29 +0000723// UnfoldConstant operates on a constant [C] which has just been replaced with a value
724// [new_value]. We assume that new_value has been properly placed early in the function,
725// most likely somewhere in front of the first instruction in the entry basic block
726// [first_entry_instruction].
727//
728// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
729// Where those uses are constants, the function generates new instructions to compute the
730// result of the new, non-constant expression and places them before first_entry_instruction.
731// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
732// for those.
733
734static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000735UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000736{
737 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
738
739 Value::use_iterator ui;
740
Sean Callanana48fe162010-08-11 03:57:18 +0000741 SmallVector<User*, 16> users;
742
743 // We do this because the use list might change, invalidating our iterator.
744 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000745 for (ui = C->use_begin();
746 ui != C->use_end();
747 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000748 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000749
Sean Callanana48fe162010-08-11 03:57:18 +0000750 for (int i = 0;
751 i < users.size();
752 ++i)
753 {
754 User *user = users[i];
755
Sean Callananbafd6852010-07-14 23:40:29 +0000756 if (Constant *constant = dyn_cast<Constant>(user))
757 {
758 // synthesize a new non-constant equivalent of the constant
759
760 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
761 {
762 switch (constant_expr->getOpcode())
763 {
764 default:
765 if (log)
766 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
767 return false;
768 case Instruction::BitCast:
769 {
770 // UnaryExpr
771 // OperandList[0] is value
772
773 Value *s = constant_expr->getOperand(0);
774
775 if (s == C)
776 s = new_value;
777
778 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
779
780 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
781 }
782 break;
783 case Instruction::GetElementPtr:
784 {
785 // GetElementPtrConstantExpr
786 // OperandList[0] is base
787 // OperandList[1]... are indices
788
789 Value *ptr = constant_expr->getOperand(0);
790
791 if (ptr == C)
792 ptr = new_value;
793
794 SmallVector<Value*, 16> indices;
795
796 unsigned operand_index;
797 unsigned num_operands = constant_expr->getNumOperands();
798
799 for (operand_index = 1;
800 operand_index < num_operands;
801 ++operand_index)
802 {
803 Value *operand = constant_expr->getOperand(operand_index);
804
805 if (operand == C)
806 operand = new_value;
807
808 indices.push_back(operand);
809 }
810
811 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
812
813 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
814 }
815 break;
816 }
817 }
818 else
819 {
820 if (log)
821 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
822 return false;
823 }
824 }
825 else
826 {
827 // simple fall-through case for non-constants
828 user->replaceUsesOfWith(C, new_value);
829 }
830 }
831
832 return true;
833}
834
Sean Callanan8bce6652010-07-13 21:41:46 +0000835bool
Sean Callananf5857a02010-07-31 01:32:05 +0000836IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000837{
838 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
839
840 m_decl_map->DoStructLayout();
841
842 if (log)
843 log->Printf("Element arrangement:");
844
845 uint32_t num_elements;
846 uint32_t element_index;
847
848 size_t size;
849 off_t alignment;
850
851 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
852 return false;
853
Sean Callananf5857a02010-07-31 01:32:05 +0000854 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000855
Sean Callananf5857a02010-07-31 01:32:05 +0000856 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000857 return false;
858
Sean Callanan02fbafa2010-07-27 21:39:39 +0000859 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000860
861 if (!argument->getName().equals("___clang_arg"))
862 return false;
863
864 if (log)
865 log->Printf("Arg: %s", PrintValue(argument).c_str());
866
Sean Callananf5857a02010-07-31 01:32:05 +0000867 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000868 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000869
870 if (!first_entry_instruction)
871 return false;
872
873 LLVMContext &context(M.getContext());
874 const IntegerType *offset_type(Type::getInt32Ty(context));
875
876 if (!offset_type)
877 return false;
878
879 for (element_index = 0; element_index < num_elements; ++element_index)
880 {
881 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000882 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000883 off_t offset;
884
885 if (!m_decl_map->GetStructElement (decl, value, offset, element_index))
886 return false;
887
888 if (log)
889 log->Printf(" %s (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000890 value->getName().str().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +0000891 PrintValue(value, true).c_str(),
892 offset);
893
894 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
895 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
896 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
897
Sean Callananbafd6852010-07-14 23:40:29 +0000898 if (Constant *constant = dyn_cast<Constant>(value))
899 UnfoldConstant(constant, bit_cast, first_entry_instruction);
900 else
901 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000902 }
903
904 if (log)
905 log->Printf("Total structure [align %d, size %d]", alignment, size);
906
907 return true;
908}
909
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000910bool
911IRForTarget::runOnModule(Module &M)
912{
913 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
914
Sean Callanan02fbafa2010-07-27 21:39:39 +0000915 Function* function = M.getFunction(StringRef("___clang_expr"));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000916
917 if (!function)
918 {
919 if (log)
920 log->Printf("Couldn't find ___clang_expr() in the module");
921
922 return false;
923 }
924
Sean Callanan02fbafa2010-07-27 21:39:39 +0000925 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000926
Sean Callanan82b74c82010-08-12 01:56:52 +0000927 ////////////////////////////////////////////////////////////
928 // Replace __clang_expr_result with a persistent variable
929 //
930
931 if (!createResultVariable(M, *function))
932 return false;
933
Sean Callananf5857a02010-07-31 01:32:05 +0000934 //////////////////////////////////
935 // Run basic-block level passes
936 //
937
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000938 for (bbi = function->begin();
939 bbi != function->end();
940 ++bbi)
941 {
Sean Callanana48fe162010-08-11 03:57:18 +0000942 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000943 return false;
944
Sean Callanana48fe162010-08-11 03:57:18 +0000945 if (!rewriteObjCSelectors(M, *bbi))
946 return false;
947
Sean Callananf5857a02010-07-31 01:32:05 +0000948 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +0000949 return false;
Sean Callanan45839272010-07-24 01:37:44 +0000950
951 if (!removeGuards(M, *bbi))
952 return false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000953 }
954
Sean Callanan8bce6652010-07-13 21:41:46 +0000955 if (log)
956 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000957 std::string s;
958 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +0000959
Sean Callanan321fe9e2010-07-28 01:00:59 +0000960 M.print(oss, NULL);
961
962 oss.flush();
963
964 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000965 }
966
Sean Callanana48fe162010-08-11 03:57:18 +0000967 ///////////////////////////////
968 // Run function-level passes
969 //
970
971 if (!replaceVariables(M, *function))
972 return false;
973
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000974 return true;
975}
976
977void
978IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +0000979 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000980{
981}
982
983PassManagerType
984IRForTarget::getPotentialPassManagerType() const
985{
986 return PMT_ModulePassManager;
987}