blob: 6ffc7b977d81fb841cfce5f02e576baffdbd5e16 [file] [log] [blame]
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001//===-- IRForTarget.cpp -------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
13#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000014#include "llvm/Instructions.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000015#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000016#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000017#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000018
19#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000020
21#include "lldb/Core/dwarf.h"
22#include "lldb/Core/Log.h"
23#include "lldb/Core/Scalar.h"
24#include "lldb/Core/StreamString.h"
25#include "lldb/Expression/ClangExpressionDeclMap.h"
26
27#include <map>
28
29using namespace llvm;
30
Sean Callanan3351dac2010-08-18 18:50:51 +000031static char ID;
32
33IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
Sean Callanan65dafa82010-08-27 01:01:44 +000034 const TargetData *target_data,
35 const char *func_name) :
Sean Callanana6223432010-08-20 01:02:30 +000036 ModulePass(&ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000037 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000038 m_target_data(target_data),
Sean Callanan65dafa82010-08-27 01:01:44 +000039 m_sel_registerName(NULL),
40 m_func_name(func_name)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000041{
42}
43
Sean Callanana48fe162010-08-11 03:57:18 +000044/* A handy utility function used at several places in the code */
45
46static std::string
47PrintValue(Value *V, bool truncate = false)
48{
49 std::string s;
50 raw_string_ostream rso(s);
51 V->print(rso);
52 rso.flush();
53 if (truncate)
54 s.resize(s.length() - 1);
55 return s;
56}
57
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000058IRForTarget::~IRForTarget()
59{
60}
61
Sean Callanan82b74c82010-08-12 01:56:52 +000062bool
63IRForTarget::createResultVariable(llvm::Module &M,
64 llvm::Function &F)
65{
66 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
67
68 // Find the result variable
69
70 Value *result_value = M.getNamedValue("___clang_expr_result");
71
72 if (!result_value)
73 {
74 if (log)
75 log->PutCString("Couldn't find result variable");
76 return false;
77 }
78
79 if (log)
80 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
81
82 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
83
84 if (!result_global)
85 {
86 if (log)
87 log->PutCString("Result variable isn't a GlobalVariable");
88 return false;
89 }
90
91 // Find the metadata and follow it to the VarDecl
92
93 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
94
95 if (!named_metadata)
96 {
97 if (log)
98 log->PutCString("No global metadata");
99
100 return false;
101 }
102
103 unsigned num_nodes = named_metadata->getNumOperands();
104 unsigned node_index;
105
106 MDNode *metadata_node = NULL;
107
108 for (node_index = 0;
109 node_index < num_nodes;
110 ++node_index)
111 {
112 metadata_node = named_metadata->getOperand(node_index);
113
114 if (metadata_node->getNumOperands() != 2)
115 continue;
116
117 if (metadata_node->getOperand(0) == result_global)
118 break;
119 }
120
121 if (!metadata_node)
122 {
123 if (log)
124 log->PutCString("Couldn't find result metadata");
125 return false;
126 }
127
128 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
129
130 uint64_t result_decl_intptr = constant_int->getZExtValue();
131
132 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
133
134 // Get the next available result name from m_decl_map and create the persistent
135 // variable for it
136
137 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
138 &result_decl->getASTContext());
139 std::string new_result_name;
140
141 m_decl_map->GetPersistentResultName(new_result_name);
Sean Callanan8c127202010-08-23 23:09:38 +0000142 m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000143
144 if (log)
145 log->Printf("Creating a new result global: %s", new_result_name.c_str());
146
147 // Construct a new result global and set up its metadata
148
149 GlobalVariable *new_result_global = new GlobalVariable(M,
150 result_global->getType()->getElementType(),
151 false, /* not constant */
152 GlobalValue::ExternalLinkage,
153 NULL, /* no initializer */
154 new_result_name.c_str());
155
156 // It's too late in compilation to create a new VarDecl for this, but we don't
157 // need to. We point the metadata at the old VarDecl. This creates an odd
158 // anomaly: a variable with a Value whose name is something like $0 and a
159 // Decl whose name is ___clang_expr_result. This condition is handled in
160 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
161 // fixed up.
162
163 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
164 result_decl_intptr,
165 false);
166
167 llvm::Value* values[2];
168 values[0] = new_result_global;
169 values[1] = new_constant_int;
170
171 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
172 named_metadata->addOperand(persistent_global_md);
173
174 if (log)
175 log->Printf("Replacing %s with %s",
176 PrintValue(result_global).c_str(),
177 PrintValue(new_result_global).c_str());
178
179 result_global->replaceAllUsesWith(new_result_global);
180 result_global->eraseFromParent();
181
182 return true;
183}
184
Sean Callananf5857a02010-07-31 01:32:05 +0000185static bool isObjCSelectorRef(Value *V)
186{
187 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
188
189 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
190 return false;
191
192 return true;
193}
194
195bool
196IRForTarget::RewriteObjCSelector(Instruction* selector_load,
197 Module &M)
198{
199 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
200
201 LoadInst *load = dyn_cast<LoadInst>(selector_load);
202
203 if (!load)
204 return false;
205
206 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
207 //
208 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
209 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
210 //
211 // where %obj is the object pointer and %tmp is the selector.
212 //
213 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
214 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
215
216 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
217
218 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
219
220 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
221 return false;
222
223 Constant *osr_initializer = _objc_selector_references_->getInitializer();
224
225 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
226
227 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
228 return false;
229
230 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
231
232 if (!osr_initializer_base)
233 return false;
234
235 // Find the string's initializer (a ConstantArray) and get the string from it
236
237 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
238
239 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
240 return false;
241
242 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
243
244 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
245
246 if (!omvn_initializer_array->isString())
247 return false;
248
249 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
250
251 if (log)
252 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
253
254 // Construct a call to sel_registerName
255
256 if (!m_sel_registerName)
257 {
258 uint64_t srN_addr;
259
260 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
261 return false;
262
263 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
264
265 // The below code would be "more correct," but in actuality what's required is uint8_t*
266 //Type *sel_type = StructType::get(M.getContext());
267 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
268 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
269
270 std::vector <const Type *> srN_arg_types;
271 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
272 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
273
274 // Build the constant containing the pointer to the function
275 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
276 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
277 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
278 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
279 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
280 }
281
282 SmallVector <Value*, 1> srN_arguments;
283
284 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
285
286 srN_arguments.push_back(omvn_pointer);
287
288 CallInst *srN_call = CallInst::Create(m_sel_registerName,
289 srN_arguments.begin(),
290 srN_arguments.end(),
291 "srN",
292 selector_load);
293
294 // Replace the load with the call in all users
295
296 selector_load->replaceAllUsesWith(srN_call);
297
298 selector_load->eraseFromParent();
299
300 return true;
301}
302
303bool
304IRForTarget::rewriteObjCSelectors(Module &M,
305 BasicBlock &BB)
306{
307 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
308
309 BasicBlock::iterator ii;
310
311 typedef SmallVector <Instruction*, 2> InstrList;
312 typedef InstrList::iterator InstrIterator;
313
314 InstrList selector_loads;
315
316 for (ii = BB.begin();
317 ii != BB.end();
318 ++ii)
319 {
320 Instruction &inst = *ii;
321
322 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
323 if (isObjCSelectorRef(load->getPointerOperand()))
324 selector_loads.push_back(&inst);
325 }
326
327 InstrIterator iter;
328
329 for (iter = selector_loads.begin();
330 iter != selector_loads.end();
331 ++iter)
332 {
333 if (!RewriteObjCSelector(*iter, M))
334 {
335 if(log)
336 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
337 return false;
338 }
339 }
340
341 return true;
342}
343
Sean Callanana48fe162010-08-11 03:57:18 +0000344bool
345IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
346 llvm::Module &M)
347{
348 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
349
350 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
351
352 if (!alloc_md || !alloc_md->getNumOperands())
353 return false;
354
355 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
356
357 if (!constant_int)
358 return false;
359
360 // We attempt to register this as a new persistent variable with the DeclMap.
361
362 uintptr_t ptr = constant_int->getZExtValue();
363
Sean Callanan82b74c82010-08-12 01:56:52 +0000364 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000365
Sean Callanan82b74c82010-08-12 01:56:52 +0000366 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
367 &decl->getASTContext());
368
Sean Callanan8c127202010-08-23 23:09:38 +0000369 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000370 return false;
371
372 GlobalVariable *persistent_global = new GlobalVariable(M,
373 alloc->getType()->getElementType(),
374 false, /* not constant */
375 GlobalValue::ExternalLinkage,
376 NULL, /* no initializer */
377 alloc->getName().str().c_str());
378
379 // What we're going to do here is make believe this was a regular old external
380 // variable. That means we need to make the metadata valid.
381
382 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
383
384 llvm::Value* values[2];
385 values[0] = persistent_global;
386 values[1] = constant_int;
387
388 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
389 named_metadata->addOperand(persistent_global_md);
390
391 alloc->replaceAllUsesWith(persistent_global);
392 alloc->eraseFromParent();
393
394 return true;
395}
396
397bool
398IRForTarget::rewritePersistentAllocs(llvm::Module &M,
399 llvm::BasicBlock &BB)
400{
401 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
402
403 BasicBlock::iterator ii;
404
405 typedef SmallVector <Instruction*, 2> InstrList;
406 typedef InstrList::iterator InstrIterator;
407
408 InstrList pvar_allocs;
409
410 for (ii = BB.begin();
411 ii != BB.end();
412 ++ii)
413 {
414 Instruction &inst = *ii;
415
416 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
417 if (alloc->getName().startswith("$"))
418 pvar_allocs.push_back(alloc);
419 }
420
421 InstrIterator iter;
422
423 for (iter = pvar_allocs.begin();
424 iter != pvar_allocs.end();
425 ++iter)
426 {
427 if (!RewritePersistentAlloc(*iter, M))
428 {
429 if(log)
430 log->PutCString("Couldn't rewrite the creation of a persistent variable");
431 return false;
432 }
433 }
434
435 return true;
436}
437
Sean Callanan8bce6652010-07-13 21:41:46 +0000438static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000439DeclForGlobalValue(Module &module,
440 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000441{
442 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
443
444 if (!named_metadata)
445 return NULL;
446
447 unsigned num_nodes = named_metadata->getNumOperands();
448 unsigned node_index;
449
450 for (node_index = 0;
451 node_index < num_nodes;
452 ++node_index)
453 {
454 MDNode *metadata_node = named_metadata->getOperand(node_index);
455
456 if (!metadata_node)
457 return NULL;
458
459 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000460 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000461
462 if (metadata_node->getOperand(0) != global_value)
463 continue;
464
465 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
466
467 if (!constant_int)
468 return NULL;
469
470 uintptr_t ptr = constant_int->getZExtValue();
471
472 return reinterpret_cast<clang::NamedDecl *>(ptr);
473 }
474
475 return NULL;
476}
477
478bool
479IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000480 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000481 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000482{
Sean Callananf5857a02010-07-31 01:32:05 +0000483 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
484
Sean Callananbc2928a2010-08-03 00:23:29 +0000485 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
486 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000487 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000488 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000489 default:
490 break;
491 case Instruction::GetElementPtr:
492 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000493 Value *s = constant_expr->getOperand(0);
494 MaybeHandleVariable(M, s, Store);
495 }
496 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000497 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000498 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000499 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000500
Sean Callananf5857a02010-07-31 01:32:05 +0000501 if (!named_decl)
502 {
503 if (isObjCSelectorRef(V))
504 return true;
505
506 if (log)
507 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
508 return false;
509 }
510
Sean Callanan810f22d2010-07-16 00:09:46 +0000511 std::string name = named_decl->getName().str();
512
513 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000514 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000515
516 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000517 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000518 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000519 ast_context = &value_decl->getASTContext();
520 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000521 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000522 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000523 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000524 }
525
Sean Callanan02fbafa2010-07-27 21:39:39 +0000526 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000527
528 size_t value_size = m_target_data->getTypeStoreSize(value_type);
529 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
530
Sean Callanan8c127202010-08-23 23:09:38 +0000531 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Sean Callanan45690fe2010-08-30 22:17:16 +0000532 name.c_str(),
Sean Callanan8c127202010-08-23 23:09:38 +0000533 V,
Sean Callananba992c52010-07-27 02:07:53 +0000534 value_size,
535 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000536 return false;
537 }
538
539 return true;
540}
541
542bool
Sean Callananba992c52010-07-27 02:07:53 +0000543IRForTarget::MaybeHandleCall(Module &M,
544 CallInst *C)
545{
546 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
547
Sean Callanan02fbafa2010-07-27 21:39:39 +0000548 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000549
550 if (fun == NULL)
551 return true;
552
553 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000554 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000555 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000556
Sean Callananf5857a02010-07-31 01:32:05 +0000557 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000558 {
Sean Callananf5857a02010-07-31 01:32:05 +0000559 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
560 {
Sean Callanan92aa6662010-09-07 21:49:41 +0000561 fun_value_ptr = NULL;
562
563 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
564 {
565 if (log)
566 log->Printf("Function %s had no address", fun->getName().str().c_str());
567
568 return false;
569 }
Sean Callananf5857a02010-07-31 01:32:05 +0000570 }
571 }
572 else
573 {
574 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
575 {
576 if (log)
577 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
578 return false;
579 }
Sean Callananba992c52010-07-27 02:07:53 +0000580 }
581
582 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000583 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000584
Sean Callananf5857a02010-07-31 01:32:05 +0000585 Value *fun_addr_ptr;
586
587 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000588 {
Sean Callanan02fbafa2010-07-27 21:39:39 +0000589 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
590 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +0000591 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +0000592 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
593 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000594 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
595
596 if (fun_value_ptr)
597 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000598 }
Sean Callananf5857a02010-07-31 01:32:05 +0000599
600 if (fun_value_ptr)
601 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000602
Sean Callananf5857a02010-07-31 01:32:05 +0000603 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000604
Sean Callananba992c52010-07-27 02:07:53 +0000605 return true;
606}
607
608bool
Sean Callananf5857a02010-07-31 01:32:05 +0000609IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000610{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000611 /////////////////////////////////////////////////////////////////////////
612 // Prepare the current basic block for execution in the remote process
613 //
614
Sean Callanan02fbafa2010-07-27 21:39:39 +0000615 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000616
617 for (ii = BB.begin();
618 ii != BB.end();
619 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000620 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000621 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000622
Sean Callanan8bce6652010-07-13 21:41:46 +0000623 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000624 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000625 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000626
Sean Callanan8bce6652010-07-13 21:41:46 +0000627 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000628 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
629 return false;
630
631 if (CallInst *call = dyn_cast<CallInst>(&inst))
632 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000633 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000634 }
635
636 return true;
637}
638
Sean Callanan02fbafa2010-07-27 21:39:39 +0000639static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000640{
641 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
642
643 if (!C || C->getOpcode() != Instruction::BitCast)
644 return false;
645
646 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
647
648 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
649 return false;
650
651 return true;
652}
653
654static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
655{
656 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
657
658 Value::use_iterator ui;
659
660 for (ui = guard_load->use_begin();
661 ui != guard_load->use_end();
662 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000663 {
Greg Clayton6e713402010-07-30 20:30:44 +0000664 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000665 {
666 // do nothing for the moment
667 }
668 else
669 {
670 ui->replaceUsesOfWith(guard_load, zero);
671 }
672 }
Sean Callanan45839272010-07-24 01:37:44 +0000673
674 guard_load->eraseFromParent();
675}
676
677static void ExciseGuardStore(Instruction* guard_store)
678{
679 guard_store->eraseFromParent();
680}
681
682bool
683IRForTarget::removeGuards(Module &M, BasicBlock &BB)
684{
685 ///////////////////////////////////////////////////////
686 // Eliminate any reference to guard variables found.
687 //
688
Sean Callanan02fbafa2010-07-27 21:39:39 +0000689 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000690
Sean Callanan02fbafa2010-07-27 21:39:39 +0000691 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000692 typedef InstrList::iterator InstrIterator;
693
694 InstrList guard_loads;
695 InstrList guard_stores;
696
697 for (ii = BB.begin();
698 ii != BB.end();
699 ++ii)
700 {
701 Instruction &inst = *ii;
702
703 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
704 if (isGuardVariableRef(load->getPointerOperand()))
705 guard_loads.push_back(&inst);
706
707 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
708 if (isGuardVariableRef(store->getPointerOperand()))
709 guard_stores.push_back(&inst);
710 }
711
712 InstrIterator iter;
713
714 for (iter = guard_loads.begin();
715 iter != guard_loads.end();
716 ++iter)
717 TurnGuardLoadIntoZero(*iter, M);
718
719 for (iter = guard_stores.begin();
720 iter != guard_stores.end();
721 ++iter)
722 ExciseGuardStore(*iter);
723
724 return true;
725}
726
Sean Callananbafd6852010-07-14 23:40:29 +0000727// UnfoldConstant operates on a constant [C] which has just been replaced with a value
728// [new_value]. We assume that new_value has been properly placed early in the function,
729// most likely somewhere in front of the first instruction in the entry basic block
730// [first_entry_instruction].
731//
732// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
733// Where those uses are constants, the function generates new instructions to compute the
734// result of the new, non-constant expression and places them before first_entry_instruction.
735// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
736// for those.
737
738static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000739UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000740{
741 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
742
743 Value::use_iterator ui;
744
Sean Callanana48fe162010-08-11 03:57:18 +0000745 SmallVector<User*, 16> users;
746
747 // We do this because the use list might change, invalidating our iterator.
748 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000749 for (ui = C->use_begin();
750 ui != C->use_end();
751 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000752 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000753
Sean Callanana48fe162010-08-11 03:57:18 +0000754 for (int i = 0;
755 i < users.size();
756 ++i)
757 {
758 User *user = users[i];
759
Sean Callananbafd6852010-07-14 23:40:29 +0000760 if (Constant *constant = dyn_cast<Constant>(user))
761 {
762 // synthesize a new non-constant equivalent of the constant
763
764 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
765 {
766 switch (constant_expr->getOpcode())
767 {
768 default:
769 if (log)
770 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
771 return false;
772 case Instruction::BitCast:
773 {
774 // UnaryExpr
775 // OperandList[0] is value
776
777 Value *s = constant_expr->getOperand(0);
778
779 if (s == C)
780 s = new_value;
781
782 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
783
784 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
785 }
786 break;
787 case Instruction::GetElementPtr:
788 {
789 // GetElementPtrConstantExpr
790 // OperandList[0] is base
791 // OperandList[1]... are indices
792
793 Value *ptr = constant_expr->getOperand(0);
794
795 if (ptr == C)
796 ptr = new_value;
797
798 SmallVector<Value*, 16> indices;
799
800 unsigned operand_index;
801 unsigned num_operands = constant_expr->getNumOperands();
802
803 for (operand_index = 1;
804 operand_index < num_operands;
805 ++operand_index)
806 {
807 Value *operand = constant_expr->getOperand(operand_index);
808
809 if (operand == C)
810 operand = new_value;
811
812 indices.push_back(operand);
813 }
814
815 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
816
817 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
818 }
819 break;
820 }
821 }
822 else
823 {
824 if (log)
825 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
826 return false;
827 }
828 }
829 else
830 {
831 // simple fall-through case for non-constants
832 user->replaceUsesOfWith(C, new_value);
833 }
834 }
835
836 return true;
837}
838
Sean Callanan8bce6652010-07-13 21:41:46 +0000839bool
Sean Callananf5857a02010-07-31 01:32:05 +0000840IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000841{
842 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
843
844 m_decl_map->DoStructLayout();
845
846 if (log)
847 log->Printf("Element arrangement:");
848
849 uint32_t num_elements;
850 uint32_t element_index;
851
852 size_t size;
853 off_t alignment;
854
855 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
856 return false;
857
Sean Callananf5857a02010-07-31 01:32:05 +0000858 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000859
Sean Callananf5857a02010-07-31 01:32:05 +0000860 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000861 return false;
862
Sean Callanan02fbafa2010-07-27 21:39:39 +0000863 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000864
865 if (!argument->getName().equals("___clang_arg"))
866 return false;
867
868 if (log)
869 log->Printf("Arg: %s", PrintValue(argument).c_str());
870
Sean Callananf5857a02010-07-31 01:32:05 +0000871 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000872 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000873
874 if (!first_entry_instruction)
875 return false;
876
877 LLVMContext &context(M.getContext());
878 const IntegerType *offset_type(Type::getInt32Ty(context));
879
880 if (!offset_type)
881 return false;
882
883 for (element_index = 0; element_index < num_elements; ++element_index)
884 {
885 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000886 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000887 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +0000888 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +0000889
Sean Callanan45690fe2010-08-30 22:17:16 +0000890 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +0000891 return false;
892
893 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +0000894 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000895 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +0000896 name,
Sean Callanan8bce6652010-07-13 21:41:46 +0000897 PrintValue(value, true).c_str(),
898 offset);
899
900 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
901 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
902 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
903
Sean Callananbafd6852010-07-14 23:40:29 +0000904 if (Constant *constant = dyn_cast<Constant>(value))
905 UnfoldConstant(constant, bit_cast, first_entry_instruction);
906 else
907 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000908 }
909
910 if (log)
911 log->Printf("Total structure [align %d, size %d]", alignment, size);
912
913 return true;
914}
915
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000916bool
917IRForTarget::runOnModule(Module &M)
918{
919 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
920
Sean Callanan65dafa82010-08-27 01:01:44 +0000921 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000922
923 if (!function)
924 {
925 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000926 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000927
928 return false;
929 }
930
Sean Callanan02fbafa2010-07-27 21:39:39 +0000931 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000932
Sean Callanan82b74c82010-08-12 01:56:52 +0000933 ////////////////////////////////////////////////////////////
934 // Replace __clang_expr_result with a persistent variable
935 //
936
937 if (!createResultVariable(M, *function))
938 return false;
939
Sean Callananf5857a02010-07-31 01:32:05 +0000940 //////////////////////////////////
941 // Run basic-block level passes
942 //
943
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000944 for (bbi = function->begin();
945 bbi != function->end();
946 ++bbi)
947 {
Sean Callanan8c127202010-08-23 23:09:38 +0000948 if (!removeGuards(M, *bbi))
949 return false;
950
Sean Callanana48fe162010-08-11 03:57:18 +0000951 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000952 return false;
953
Sean Callanana48fe162010-08-11 03:57:18 +0000954 if (!rewriteObjCSelectors(M, *bbi))
955 return false;
956
Sean Callananf5857a02010-07-31 01:32:05 +0000957 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +0000958 return false;
959 }
960
Sean Callanan8bce6652010-07-13 21:41:46 +0000961 if (log)
962 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000963 std::string s;
964 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +0000965
Sean Callanan321fe9e2010-07-28 01:00:59 +0000966 M.print(oss, NULL);
967
968 oss.flush();
969
970 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000971 }
972
Sean Callanana48fe162010-08-11 03:57:18 +0000973 ///////////////////////////////
974 // Run function-level passes
975 //
976
977 if (!replaceVariables(M, *function))
978 return false;
979
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000980 return true;
981}
982
983void
984IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +0000985 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000986{
987}
988
989PassManagerType
990IRForTarget::getPotentialPassManagerType() const
991{
992 return PMT_ModulePassManager;
993}