blob: 57604aadacddb59aea43f70ccc53f53e39fc5374 [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,
Sean Callanana386e052010-08-13 22:29:54 +0000531 lldb_private::TypeFromParser(qual_type, ast_context),
Sean Callananba992c52010-07-27 02:07:53 +0000532 value_size,
533 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000534 return false;
535 }
536
537 return true;
538}
539
540bool
Sean Callananba992c52010-07-27 02:07:53 +0000541IRForTarget::MaybeHandleCall(Module &M,
542 CallInst *C)
543{
544 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
545
Sean Callanan02fbafa2010-07-27 21:39:39 +0000546 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000547
548 if (fun == NULL)
549 return true;
550
551 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000552 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000553 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000554
Sean Callananf5857a02010-07-31 01:32:05 +0000555 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000556 {
Sean Callananf5857a02010-07-31 01:32:05 +0000557 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
558 {
559 if (log)
560 log->Printf("Function %s had no address", fun_decl->getNameAsCString());
561 return false;
562 }
563 }
564 else
565 {
566 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
567 {
568 if (log)
569 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
570 return false;
571 }
Sean Callananba992c52010-07-27 02:07:53 +0000572 }
573
574 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000575 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000576
Sean Callananf5857a02010-07-31 01:32:05 +0000577 Value *fun_addr_ptr;
578
579 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000580 {
581 std::vector<const Type*> params;
582
583 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
584 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
585
586 FunctionType *fun_ty = FunctionType::get(intptr_ty, params, true);
587 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
588 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000589 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
590
591 if (fun_value_ptr)
592 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000593 }
Sean Callananf5857a02010-07-31 01:32:05 +0000594
595 if (fun_value_ptr)
596 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000597
Sean Callananf5857a02010-07-31 01:32:05 +0000598 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000599
Sean Callananba992c52010-07-27 02:07:53 +0000600 return true;
601}
602
603bool
Sean Callananf5857a02010-07-31 01:32:05 +0000604IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000605{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000606 /////////////////////////////////////////////////////////////////////////
607 // Prepare the current basic block for execution in the remote process
608 //
609
Sean Callanan02fbafa2010-07-27 21:39:39 +0000610 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000611
612 for (ii = BB.begin();
613 ii != BB.end();
614 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000615 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000616 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000617
Sean Callanan8bce6652010-07-13 21:41:46 +0000618 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000619 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000620 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000621
Sean Callanan8bce6652010-07-13 21:41:46 +0000622 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000623 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
624 return false;
625
626 if (CallInst *call = dyn_cast<CallInst>(&inst))
627 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000628 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000629 }
630
631 return true;
632}
633
Sean Callanan02fbafa2010-07-27 21:39:39 +0000634static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000635{
636 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
637
638 if (!C || C->getOpcode() != Instruction::BitCast)
639 return false;
640
641 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
642
643 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
644 return false;
645
646 return true;
647}
648
649static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
650{
651 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
652
653 Value::use_iterator ui;
654
655 for (ui = guard_load->use_begin();
656 ui != guard_load->use_end();
657 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000658 {
Greg Clayton6e713402010-07-30 20:30:44 +0000659 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000660 {
661 // do nothing for the moment
662 }
663 else
664 {
665 ui->replaceUsesOfWith(guard_load, zero);
666 }
667 }
Sean Callanan45839272010-07-24 01:37:44 +0000668
669 guard_load->eraseFromParent();
670}
671
672static void ExciseGuardStore(Instruction* guard_store)
673{
674 guard_store->eraseFromParent();
675}
676
677bool
678IRForTarget::removeGuards(Module &M, BasicBlock &BB)
679{
680 ///////////////////////////////////////////////////////
681 // Eliminate any reference to guard variables found.
682 //
683
Sean Callanan02fbafa2010-07-27 21:39:39 +0000684 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000685
Sean Callanan02fbafa2010-07-27 21:39:39 +0000686 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000687 typedef InstrList::iterator InstrIterator;
688
689 InstrList guard_loads;
690 InstrList guard_stores;
691
692 for (ii = BB.begin();
693 ii != BB.end();
694 ++ii)
695 {
696 Instruction &inst = *ii;
697
698 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
699 if (isGuardVariableRef(load->getPointerOperand()))
700 guard_loads.push_back(&inst);
701
702 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
703 if (isGuardVariableRef(store->getPointerOperand()))
704 guard_stores.push_back(&inst);
705 }
706
707 InstrIterator iter;
708
709 for (iter = guard_loads.begin();
710 iter != guard_loads.end();
711 ++iter)
712 TurnGuardLoadIntoZero(*iter, M);
713
714 for (iter = guard_stores.begin();
715 iter != guard_stores.end();
716 ++iter)
717 ExciseGuardStore(*iter);
718
719 return true;
720}
721
Sean Callananbafd6852010-07-14 23:40:29 +0000722// UnfoldConstant operates on a constant [C] which has just been replaced with a value
723// [new_value]. We assume that new_value has been properly placed early in the function,
724// most likely somewhere in front of the first instruction in the entry basic block
725// [first_entry_instruction].
726//
727// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
728// Where those uses are constants, the function generates new instructions to compute the
729// result of the new, non-constant expression and places them before first_entry_instruction.
730// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
731// for those.
732
733static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000734UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000735{
736 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
737
738 Value::use_iterator ui;
739
Sean Callanana48fe162010-08-11 03:57:18 +0000740 SmallVector<User*, 16> users;
741
742 // We do this because the use list might change, invalidating our iterator.
743 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000744 for (ui = C->use_begin();
745 ui != C->use_end();
746 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000747 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000748
Sean Callanana48fe162010-08-11 03:57:18 +0000749 for (int i = 0;
750 i < users.size();
751 ++i)
752 {
753 User *user = users[i];
754
Sean Callananbafd6852010-07-14 23:40:29 +0000755 if (Constant *constant = dyn_cast<Constant>(user))
756 {
757 // synthesize a new non-constant equivalent of the constant
758
759 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
760 {
761 switch (constant_expr->getOpcode())
762 {
763 default:
764 if (log)
765 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
766 return false;
767 case Instruction::BitCast:
768 {
769 // UnaryExpr
770 // OperandList[0] is value
771
772 Value *s = constant_expr->getOperand(0);
773
774 if (s == C)
775 s = new_value;
776
777 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
778
779 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
780 }
781 break;
782 case Instruction::GetElementPtr:
783 {
784 // GetElementPtrConstantExpr
785 // OperandList[0] is base
786 // OperandList[1]... are indices
787
788 Value *ptr = constant_expr->getOperand(0);
789
790 if (ptr == C)
791 ptr = new_value;
792
793 SmallVector<Value*, 16> indices;
794
795 unsigned operand_index;
796 unsigned num_operands = constant_expr->getNumOperands();
797
798 for (operand_index = 1;
799 operand_index < num_operands;
800 ++operand_index)
801 {
802 Value *operand = constant_expr->getOperand(operand_index);
803
804 if (operand == C)
805 operand = new_value;
806
807 indices.push_back(operand);
808 }
809
810 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
811
812 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
813 }
814 break;
815 }
816 }
817 else
818 {
819 if (log)
820 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
821 return false;
822 }
823 }
824 else
825 {
826 // simple fall-through case for non-constants
827 user->replaceUsesOfWith(C, new_value);
828 }
829 }
830
831 return true;
832}
833
Sean Callanan8bce6652010-07-13 21:41:46 +0000834bool
Sean Callananf5857a02010-07-31 01:32:05 +0000835IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000836{
837 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
838
839 m_decl_map->DoStructLayout();
840
841 if (log)
842 log->Printf("Element arrangement:");
843
844 uint32_t num_elements;
845 uint32_t element_index;
846
847 size_t size;
848 off_t alignment;
849
850 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
851 return false;
852
Sean Callananf5857a02010-07-31 01:32:05 +0000853 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000854
Sean Callananf5857a02010-07-31 01:32:05 +0000855 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000856 return false;
857
Sean Callanan02fbafa2010-07-27 21:39:39 +0000858 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000859
860 if (!argument->getName().equals("___clang_arg"))
861 return false;
862
863 if (log)
864 log->Printf("Arg: %s", PrintValue(argument).c_str());
865
Sean Callananf5857a02010-07-31 01:32:05 +0000866 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000867 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000868
869 if (!first_entry_instruction)
870 return false;
871
872 LLVMContext &context(M.getContext());
873 const IntegerType *offset_type(Type::getInt32Ty(context));
874
875 if (!offset_type)
876 return false;
877
878 for (element_index = 0; element_index < num_elements; ++element_index)
879 {
880 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000881 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000882 off_t offset;
883
884 if (!m_decl_map->GetStructElement (decl, value, offset, element_index))
885 return false;
886
887 if (log)
888 log->Printf(" %s (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000889 value->getName().str().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +0000890 PrintValue(value, true).c_str(),
891 offset);
892
893 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
894 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
895 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
896
Sean Callananbafd6852010-07-14 23:40:29 +0000897 if (Constant *constant = dyn_cast<Constant>(value))
898 UnfoldConstant(constant, bit_cast, first_entry_instruction);
899 else
900 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000901 }
902
903 if (log)
904 log->Printf("Total structure [align %d, size %d]", alignment, size);
905
906 return true;
907}
908
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000909bool
910IRForTarget::runOnModule(Module &M)
911{
912 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
913
Sean Callanan02fbafa2010-07-27 21:39:39 +0000914 Function* function = M.getFunction(StringRef("___clang_expr"));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000915
916 if (!function)
917 {
918 if (log)
919 log->Printf("Couldn't find ___clang_expr() in the module");
920
921 return false;
922 }
923
Sean Callanan02fbafa2010-07-27 21:39:39 +0000924 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000925
Sean Callanan82b74c82010-08-12 01:56:52 +0000926 ////////////////////////////////////////////////////////////
927 // Replace __clang_expr_result with a persistent variable
928 //
929
930 if (!createResultVariable(M, *function))
931 return false;
932
Sean Callananf5857a02010-07-31 01:32:05 +0000933 //////////////////////////////////
934 // Run basic-block level passes
935 //
936
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000937 for (bbi = function->begin();
938 bbi != function->end();
939 ++bbi)
940 {
Sean Callanana48fe162010-08-11 03:57:18 +0000941 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000942 return false;
943
Sean Callanana48fe162010-08-11 03:57:18 +0000944 if (!rewriteObjCSelectors(M, *bbi))
945 return false;
946
Sean Callananf5857a02010-07-31 01:32:05 +0000947 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +0000948 return false;
Sean Callanan45839272010-07-24 01:37:44 +0000949
950 if (!removeGuards(M, *bbi))
951 return false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000952 }
953
Sean Callanan8bce6652010-07-13 21:41:46 +0000954 if (log)
955 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000956 std::string s;
957 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +0000958
Sean Callanan321fe9e2010-07-28 01:00:59 +0000959 M.print(oss, NULL);
960
961 oss.flush();
962
963 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000964 }
965
Sean Callanana48fe162010-08-11 03:57:18 +0000966 ///////////////////////////////
967 // Run function-level passes
968 //
969
970 if (!replaceVariables(M, *function))
971 return false;
972
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000973 return true;
974}
975
976void
977IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +0000978 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000979{
980}
981
982PassManagerType
983IRForTarget::getPotentialPassManagerType() const
984{
985 return PMT_ModulePassManager;
986}