blob: e220b16f00caa509a9b7ce3e8810984b2efbcb79 [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)
Sean Callanan2e2db532010-09-07 22:43:19 +0000175 log->Printf("Replacing %s with %s",
176 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000177 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000178
179 if (result_global->hasNUses(0))
180 {
181 // We need to synthesize a store for this variable, because otherwise
182 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000183
Sean Callanan2e2db532010-09-07 22:43:19 +0000184 BasicBlock &entry_block(F.getEntryBlock());
185 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
186
187 if (!first_entry_instruction)
188 return false;
189
190 if (!result_global->hasInitializer())
191 {
192 if (log)
193 log->Printf("Couldn't find initializer for unused variable");
194 return false;
195 }
196
197 Constant *initializer = result_global->getInitializer();
198
199 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
200 new_result_global,
201 first_entry_instruction);
202
203 if (log)
204 log->Printf("Synthesized result store %s\n", PrintValue(synthesized_store).c_str());
205 }
206 else
207 {
208 result_global->replaceAllUsesWith(new_result_global);
209 }
210
Sean Callanan82b74c82010-08-12 01:56:52 +0000211 result_global->eraseFromParent();
212
213 return true;
214}
215
Sean Callananf5857a02010-07-31 01:32:05 +0000216static bool isObjCSelectorRef(Value *V)
217{
218 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
219
220 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
221 return false;
222
223 return true;
224}
225
226bool
227IRForTarget::RewriteObjCSelector(Instruction* selector_load,
228 Module &M)
229{
230 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
231
232 LoadInst *load = dyn_cast<LoadInst>(selector_load);
233
234 if (!load)
235 return false;
236
237 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
238 //
239 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
240 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
241 //
242 // where %obj is the object pointer and %tmp is the selector.
243 //
244 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
245 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
246
247 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
248
249 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
250
251 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
252 return false;
253
254 Constant *osr_initializer = _objc_selector_references_->getInitializer();
255
256 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
257
258 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
259 return false;
260
261 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
262
263 if (!osr_initializer_base)
264 return false;
265
266 // Find the string's initializer (a ConstantArray) and get the string from it
267
268 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
269
270 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
271 return false;
272
273 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
274
275 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
276
277 if (!omvn_initializer_array->isString())
278 return false;
279
280 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
281
282 if (log)
283 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
284
285 // Construct a call to sel_registerName
286
287 if (!m_sel_registerName)
288 {
289 uint64_t srN_addr;
290
291 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
292 return false;
293
294 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
295
296 // The below code would be "more correct," but in actuality what's required is uint8_t*
297 //Type *sel_type = StructType::get(M.getContext());
298 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
299 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
300
301 std::vector <const Type *> srN_arg_types;
302 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
303 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
304
305 // Build the constant containing the pointer to the function
306 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
307 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
308 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
309 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
310 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
311 }
312
313 SmallVector <Value*, 1> srN_arguments;
314
315 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
316
317 srN_arguments.push_back(omvn_pointer);
318
319 CallInst *srN_call = CallInst::Create(m_sel_registerName,
320 srN_arguments.begin(),
321 srN_arguments.end(),
322 "srN",
323 selector_load);
324
325 // Replace the load with the call in all users
326
327 selector_load->replaceAllUsesWith(srN_call);
328
329 selector_load->eraseFromParent();
330
331 return true;
332}
333
334bool
335IRForTarget::rewriteObjCSelectors(Module &M,
336 BasicBlock &BB)
337{
338 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
339
340 BasicBlock::iterator ii;
341
342 typedef SmallVector <Instruction*, 2> InstrList;
343 typedef InstrList::iterator InstrIterator;
344
345 InstrList selector_loads;
346
347 for (ii = BB.begin();
348 ii != BB.end();
349 ++ii)
350 {
351 Instruction &inst = *ii;
352
353 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
354 if (isObjCSelectorRef(load->getPointerOperand()))
355 selector_loads.push_back(&inst);
356 }
357
358 InstrIterator iter;
359
360 for (iter = selector_loads.begin();
361 iter != selector_loads.end();
362 ++iter)
363 {
364 if (!RewriteObjCSelector(*iter, M))
365 {
366 if(log)
367 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
368 return false;
369 }
370 }
371
372 return true;
373}
374
Sean Callanana48fe162010-08-11 03:57:18 +0000375bool
376IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
377 llvm::Module &M)
378{
379 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
380
381 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
382
383 if (!alloc_md || !alloc_md->getNumOperands())
384 return false;
385
386 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
387
388 if (!constant_int)
389 return false;
390
391 // We attempt to register this as a new persistent variable with the DeclMap.
392
393 uintptr_t ptr = constant_int->getZExtValue();
394
Sean Callanan82b74c82010-08-12 01:56:52 +0000395 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000396
Sean Callanan82b74c82010-08-12 01:56:52 +0000397 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
398 &decl->getASTContext());
399
Sean Callanan8c127202010-08-23 23:09:38 +0000400 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000401 return false;
402
403 GlobalVariable *persistent_global = new GlobalVariable(M,
404 alloc->getType()->getElementType(),
405 false, /* not constant */
406 GlobalValue::ExternalLinkage,
407 NULL, /* no initializer */
408 alloc->getName().str().c_str());
409
410 // What we're going to do here is make believe this was a regular old external
411 // variable. That means we need to make the metadata valid.
412
413 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
414
415 llvm::Value* values[2];
416 values[0] = persistent_global;
417 values[1] = constant_int;
418
419 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
420 named_metadata->addOperand(persistent_global_md);
421
422 alloc->replaceAllUsesWith(persistent_global);
423 alloc->eraseFromParent();
424
425 return true;
426}
427
428bool
429IRForTarget::rewritePersistentAllocs(llvm::Module &M,
430 llvm::BasicBlock &BB)
431{
432 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
433
434 BasicBlock::iterator ii;
435
436 typedef SmallVector <Instruction*, 2> InstrList;
437 typedef InstrList::iterator InstrIterator;
438
439 InstrList pvar_allocs;
440
441 for (ii = BB.begin();
442 ii != BB.end();
443 ++ii)
444 {
445 Instruction &inst = *ii;
446
447 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
448 if (alloc->getName().startswith("$"))
449 pvar_allocs.push_back(alloc);
450 }
451
452 InstrIterator iter;
453
454 for (iter = pvar_allocs.begin();
455 iter != pvar_allocs.end();
456 ++iter)
457 {
458 if (!RewritePersistentAlloc(*iter, M))
459 {
460 if(log)
461 log->PutCString("Couldn't rewrite the creation of a persistent variable");
462 return false;
463 }
464 }
465
466 return true;
467}
468
Sean Callanan8bce6652010-07-13 21:41:46 +0000469static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000470DeclForGlobalValue(Module &module,
471 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000472{
473 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
474
475 if (!named_metadata)
476 return NULL;
477
478 unsigned num_nodes = named_metadata->getNumOperands();
479 unsigned node_index;
480
481 for (node_index = 0;
482 node_index < num_nodes;
483 ++node_index)
484 {
485 MDNode *metadata_node = named_metadata->getOperand(node_index);
486
487 if (!metadata_node)
488 return NULL;
489
490 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000491 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000492
493 if (metadata_node->getOperand(0) != global_value)
494 continue;
495
496 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
497
498 if (!constant_int)
499 return NULL;
500
501 uintptr_t ptr = constant_int->getZExtValue();
502
503 return reinterpret_cast<clang::NamedDecl *>(ptr);
504 }
505
506 return NULL;
507}
508
509bool
510IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000511 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000512 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000513{
Sean Callananf5857a02010-07-31 01:32:05 +0000514 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
515
Sean Callananbc2928a2010-08-03 00:23:29 +0000516 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
517 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000518 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000519 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000520 default:
521 break;
522 case Instruction::GetElementPtr:
523 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000524 Value *s = constant_expr->getOperand(0);
525 MaybeHandleVariable(M, s, Store);
526 }
527 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000528 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000529 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000530 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000531
Sean Callananf5857a02010-07-31 01:32:05 +0000532 if (!named_decl)
533 {
534 if (isObjCSelectorRef(V))
535 return true;
536
537 if (log)
538 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
539 return false;
540 }
541
Sean Callanan810f22d2010-07-16 00:09:46 +0000542 std::string name = named_decl->getName().str();
543
544 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000545 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000546
547 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000548 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000549 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000550 ast_context = &value_decl->getASTContext();
551 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000552 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000553 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000554 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000555 }
556
Sean Callanan02fbafa2010-07-27 21:39:39 +0000557 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000558
559 size_t value_size = m_target_data->getTypeStoreSize(value_type);
560 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
561
Sean Callanan8c127202010-08-23 23:09:38 +0000562 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Sean Callanan45690fe2010-08-30 22:17:16 +0000563 name.c_str(),
Sean Callanan8c127202010-08-23 23:09:38 +0000564 V,
Sean Callananba992c52010-07-27 02:07:53 +0000565 value_size,
566 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000567 return false;
568 }
569
570 return true;
571}
572
573bool
Sean Callananba992c52010-07-27 02:07:53 +0000574IRForTarget::MaybeHandleCall(Module &M,
575 CallInst *C)
576{
577 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
578
Sean Callanan02fbafa2010-07-27 21:39:39 +0000579 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000580
581 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +0000582 {
583 Value *val = C->getCalledValue();
584
585 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
586
587 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
588 {
589 fun = dyn_cast<Function>(const_expr->getOperand(0));
590
591 if (!fun)
592 return true;
593 }
594 else
595 {
596 return true;
597 }
598 }
Sean Callananba992c52010-07-27 02:07:53 +0000599
600 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000601 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000602 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000603
Sean Callananf5857a02010-07-31 01:32:05 +0000604 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000605 {
Sean Callananf5857a02010-07-31 01:32:05 +0000606 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
607 {
Sean Callanan92aa6662010-09-07 21:49:41 +0000608 fun_value_ptr = NULL;
609
610 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
611 {
612 if (log)
613 log->Printf("Function %s had no address", fun->getName().str().c_str());
614
615 return false;
616 }
Sean Callananf5857a02010-07-31 01:32:05 +0000617 }
618 }
619 else
620 {
621 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
622 {
623 if (log)
624 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
625 return false;
626 }
Sean Callananba992c52010-07-27 02:07:53 +0000627 }
628
629 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000630 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000631
Sean Callananf5857a02010-07-31 01:32:05 +0000632 Value *fun_addr_ptr;
633
634 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000635 {
Sean Callanan02fbafa2010-07-27 21:39:39 +0000636 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
637 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +0000638 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +0000639 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
640 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000641 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
642
643 if (fun_value_ptr)
644 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000645 }
Sean Callananf5857a02010-07-31 01:32:05 +0000646
647 if (fun_value_ptr)
648 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000649
Sean Callananf5857a02010-07-31 01:32:05 +0000650 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000651
Sean Callananba992c52010-07-27 02:07:53 +0000652 return true;
653}
654
655bool
Sean Callananf5857a02010-07-31 01:32:05 +0000656IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000657{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000658 /////////////////////////////////////////////////////////////////////////
659 // Prepare the current basic block for execution in the remote process
660 //
661
Sean Callanan02fbafa2010-07-27 21:39:39 +0000662 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000663
664 for (ii = BB.begin();
665 ii != BB.end();
666 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000667 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000668 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000669
Sean Callanan8bce6652010-07-13 21:41:46 +0000670 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000671 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000672 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000673
Sean Callanan8bce6652010-07-13 21:41:46 +0000674 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000675 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
676 return false;
677
678 if (CallInst *call = dyn_cast<CallInst>(&inst))
679 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000680 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000681 }
682
683 return true;
684}
685
Sean Callanan02fbafa2010-07-27 21:39:39 +0000686static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000687{
688 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
689
690 if (!C || C->getOpcode() != Instruction::BitCast)
691 return false;
692
693 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
694
695 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
696 return false;
697
698 return true;
699}
700
701static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
702{
703 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
704
705 Value::use_iterator ui;
706
707 for (ui = guard_load->use_begin();
708 ui != guard_load->use_end();
709 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000710 {
Greg Clayton6e713402010-07-30 20:30:44 +0000711 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000712 {
713 // do nothing for the moment
714 }
715 else
716 {
717 ui->replaceUsesOfWith(guard_load, zero);
718 }
719 }
Sean Callanan45839272010-07-24 01:37:44 +0000720
721 guard_load->eraseFromParent();
722}
723
724static void ExciseGuardStore(Instruction* guard_store)
725{
726 guard_store->eraseFromParent();
727}
728
729bool
730IRForTarget::removeGuards(Module &M, BasicBlock &BB)
731{
732 ///////////////////////////////////////////////////////
733 // Eliminate any reference to guard variables found.
734 //
735
Sean Callanan02fbafa2010-07-27 21:39:39 +0000736 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000737
Sean Callanan02fbafa2010-07-27 21:39:39 +0000738 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000739 typedef InstrList::iterator InstrIterator;
740
741 InstrList guard_loads;
742 InstrList guard_stores;
743
744 for (ii = BB.begin();
745 ii != BB.end();
746 ++ii)
747 {
748 Instruction &inst = *ii;
749
750 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
751 if (isGuardVariableRef(load->getPointerOperand()))
752 guard_loads.push_back(&inst);
753
754 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
755 if (isGuardVariableRef(store->getPointerOperand()))
756 guard_stores.push_back(&inst);
757 }
758
759 InstrIterator iter;
760
761 for (iter = guard_loads.begin();
762 iter != guard_loads.end();
763 ++iter)
764 TurnGuardLoadIntoZero(*iter, M);
765
766 for (iter = guard_stores.begin();
767 iter != guard_stores.end();
768 ++iter)
769 ExciseGuardStore(*iter);
770
771 return true;
772}
773
Sean Callananbafd6852010-07-14 23:40:29 +0000774// UnfoldConstant operates on a constant [C] which has just been replaced with a value
775// [new_value]. We assume that new_value has been properly placed early in the function,
776// most likely somewhere in front of the first instruction in the entry basic block
777// [first_entry_instruction].
778//
779// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
780// Where those uses are constants, the function generates new instructions to compute the
781// result of the new, non-constant expression and places them before first_entry_instruction.
782// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
783// for those.
784
785static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000786UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000787{
788 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
789
790 Value::use_iterator ui;
791
Sean Callanana48fe162010-08-11 03:57:18 +0000792 SmallVector<User*, 16> users;
793
794 // We do this because the use list might change, invalidating our iterator.
795 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000796 for (ui = C->use_begin();
797 ui != C->use_end();
798 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000799 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000800
Sean Callanana48fe162010-08-11 03:57:18 +0000801 for (int i = 0;
802 i < users.size();
803 ++i)
804 {
805 User *user = users[i];
806
Sean Callananbafd6852010-07-14 23:40:29 +0000807 if (Constant *constant = dyn_cast<Constant>(user))
808 {
809 // synthesize a new non-constant equivalent of the constant
810
811 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
812 {
813 switch (constant_expr->getOpcode())
814 {
815 default:
816 if (log)
817 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
818 return false;
819 case Instruction::BitCast:
820 {
821 // UnaryExpr
822 // OperandList[0] is value
823
824 Value *s = constant_expr->getOperand(0);
825
826 if (s == C)
827 s = new_value;
828
829 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
830
831 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
832 }
833 break;
834 case Instruction::GetElementPtr:
835 {
836 // GetElementPtrConstantExpr
837 // OperandList[0] is base
838 // OperandList[1]... are indices
839
840 Value *ptr = constant_expr->getOperand(0);
841
842 if (ptr == C)
843 ptr = new_value;
844
845 SmallVector<Value*, 16> indices;
846
847 unsigned operand_index;
848 unsigned num_operands = constant_expr->getNumOperands();
849
850 for (operand_index = 1;
851 operand_index < num_operands;
852 ++operand_index)
853 {
854 Value *operand = constant_expr->getOperand(operand_index);
855
856 if (operand == C)
857 operand = new_value;
858
859 indices.push_back(operand);
860 }
861
862 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
863
864 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
865 }
866 break;
867 }
868 }
869 else
870 {
871 if (log)
872 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
873 return false;
874 }
875 }
876 else
877 {
878 // simple fall-through case for non-constants
879 user->replaceUsesOfWith(C, new_value);
880 }
881 }
882
883 return true;
884}
885
Sean Callanan8bce6652010-07-13 21:41:46 +0000886bool
Sean Callananf5857a02010-07-31 01:32:05 +0000887IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000888{
889 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
890
891 m_decl_map->DoStructLayout();
892
893 if (log)
894 log->Printf("Element arrangement:");
895
896 uint32_t num_elements;
897 uint32_t element_index;
898
899 size_t size;
900 off_t alignment;
901
902 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
903 return false;
904
Sean Callananf5857a02010-07-31 01:32:05 +0000905 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000906
Sean Callananf5857a02010-07-31 01:32:05 +0000907 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000908 return false;
909
Sean Callanan02fbafa2010-07-27 21:39:39 +0000910 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000911
912 if (!argument->getName().equals("___clang_arg"))
913 return false;
914
915 if (log)
916 log->Printf("Arg: %s", PrintValue(argument).c_str());
917
Sean Callananf5857a02010-07-31 01:32:05 +0000918 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000919 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000920
921 if (!first_entry_instruction)
922 return false;
923
924 LLVMContext &context(M.getContext());
925 const IntegerType *offset_type(Type::getInt32Ty(context));
926
927 if (!offset_type)
928 return false;
929
930 for (element_index = 0; element_index < num_elements; ++element_index)
931 {
932 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000933 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000934 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +0000935 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +0000936
Sean Callanan45690fe2010-08-30 22:17:16 +0000937 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +0000938 return false;
939
940 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +0000941 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000942 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +0000943 name,
Sean Callanan8bce6652010-07-13 21:41:46 +0000944 PrintValue(value, true).c_str(),
945 offset);
946
947 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
948 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
949 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
950
Sean Callananbafd6852010-07-14 23:40:29 +0000951 if (Constant *constant = dyn_cast<Constant>(value))
952 UnfoldConstant(constant, bit_cast, first_entry_instruction);
953 else
954 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000955 }
956
957 if (log)
958 log->Printf("Total structure [align %d, size %d]", alignment, size);
959
960 return true;
961}
962
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000963bool
964IRForTarget::runOnModule(Module &M)
965{
966 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
967
Sean Callanan65dafa82010-08-27 01:01:44 +0000968 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000969
970 if (!function)
971 {
972 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000973 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000974
975 return false;
976 }
977
Sean Callanan02fbafa2010-07-27 21:39:39 +0000978 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000979
Sean Callanan82b74c82010-08-12 01:56:52 +0000980 ////////////////////////////////////////////////////////////
981 // Replace __clang_expr_result with a persistent variable
982 //
983
984 if (!createResultVariable(M, *function))
985 return false;
986
Sean Callananf5857a02010-07-31 01:32:05 +0000987 //////////////////////////////////
988 // Run basic-block level passes
989 //
990
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000991 for (bbi = function->begin();
992 bbi != function->end();
993 ++bbi)
994 {
Sean Callanan8c127202010-08-23 23:09:38 +0000995 if (!removeGuards(M, *bbi))
996 return false;
997
Sean Callanana48fe162010-08-11 03:57:18 +0000998 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000999 return false;
1000
Sean Callanana48fe162010-08-11 03:57:18 +00001001 if (!rewriteObjCSelectors(M, *bbi))
1002 return false;
1003
Sean Callananf5857a02010-07-31 01:32:05 +00001004 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001005 return false;
1006 }
1007
Sean Callanan8bce6652010-07-13 21:41:46 +00001008 if (log)
1009 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001010 std::string s;
1011 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001012
Sean Callanan321fe9e2010-07-28 01:00:59 +00001013 M.print(oss, NULL);
1014
1015 oss.flush();
1016
1017 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001018 }
1019
Sean Callanana48fe162010-08-11 03:57:18 +00001020 ///////////////////////////////
1021 // Run function-level passes
1022 //
1023
1024 if (!replaceVariables(M, *function))
1025 return false;
1026
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001027 return true;
1028}
1029
1030void
1031IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001032 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001033{
1034}
1035
1036PassManagerType
1037IRForTarget::getPotentialPassManagerType() const
1038{
1039 return PMT_ModulePassManager;
1040}