blob: c7933d69b6451a7a192fdc377df77d8509a88e88 [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,
Sean Callanane8a59a82010-09-13 21:34:21 +000035 bool resolve_vars,
Sean Callanan65dafa82010-08-27 01:01:44 +000036 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000037 ModulePass(ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000038 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000039 m_target_data(target_data),
Sean Callanan65dafa82010-08-27 01:01:44 +000040 m_sel_registerName(NULL),
Sean Callanane8a59a82010-09-13 21:34:21 +000041 m_func_name(func_name),
42 m_resolve_vars(resolve_vars)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000043{
44}
45
Sean Callanana48fe162010-08-11 03:57:18 +000046/* A handy utility function used at several places in the code */
47
48static std::string
49PrintValue(Value *V, bool truncate = false)
50{
51 std::string s;
52 raw_string_ostream rso(s);
53 V->print(rso);
54 rso.flush();
55 if (truncate)
56 s.resize(s.length() - 1);
57 return s;
58}
59
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000060IRForTarget::~IRForTarget()
61{
62}
63
Sean Callanan82b74c82010-08-12 01:56:52 +000064bool
65IRForTarget::createResultVariable(llvm::Module &M,
66 llvm::Function &F)
67{
68 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
69
Sean Callanane8a59a82010-09-13 21:34:21 +000070 if (!m_resolve_vars)
71 return true;
72
73 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000074
75 ValueSymbolTable& value_symbol_table = M.getValueSymbolTable();
76
77 const char *result_name = NULL;
78
79 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
80 vi != ve;
81 ++vi)
82 {
Sean Callananc04743d2010-09-28 21:13:03 +000083 if (strstr(vi->first(), "___clang_expr_result") &&
84 !strstr(vi->first(), "GV"))
85 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000086 result_name = vi->first();
Sean Callananc04743d2010-09-28 21:13:03 +000087 break;
88 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000089 }
90
91 if (!result_name)
92 {
93 if (log)
94 log->PutCString("Couldn't find result variable");
95
96 return true;
97 }
98
Sean Callananc04743d2010-09-28 21:13:03 +000099 if (log)
100 log->Printf("Result name: %s", result_name);
101
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000102 Value *result_value = M.getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000103
104 if (!result_value)
105 {
106 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000107 log->PutCString("Result variable had no data");
Sean Callanane8a59a82010-09-13 21:34:21 +0000108
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000109 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000110 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000111
Sean Callanan82b74c82010-08-12 01:56:52 +0000112 if (log)
113 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
114
115 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
116
117 if (!result_global)
118 {
119 if (log)
120 log->PutCString("Result variable isn't a GlobalVariable");
121 return false;
122 }
123
124 // Find the metadata and follow it to the VarDecl
125
126 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
127
128 if (!named_metadata)
129 {
130 if (log)
131 log->PutCString("No global metadata");
132
133 return false;
134 }
135
136 unsigned num_nodes = named_metadata->getNumOperands();
137 unsigned node_index;
138
139 MDNode *metadata_node = NULL;
140
141 for (node_index = 0;
142 node_index < num_nodes;
143 ++node_index)
144 {
145 metadata_node = named_metadata->getOperand(node_index);
146
147 if (metadata_node->getNumOperands() != 2)
148 continue;
149
150 if (metadata_node->getOperand(0) == result_global)
151 break;
152 }
153
154 if (!metadata_node)
155 {
156 if (log)
157 log->PutCString("Couldn't find result metadata");
158 return false;
159 }
160
161 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
162
163 uint64_t result_decl_intptr = constant_int->getZExtValue();
164
165 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
166
167 // Get the next available result name from m_decl_map and create the persistent
168 // variable for it
169
170 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
171 &result_decl->getASTContext());
172 std::string new_result_name;
173
174 m_decl_map->GetPersistentResultName(new_result_name);
Sean Callanan8c127202010-08-23 23:09:38 +0000175 m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000176
177 if (log)
178 log->Printf("Creating a new result global: %s", new_result_name.c_str());
179
180 // Construct a new result global and set up its metadata
181
182 GlobalVariable *new_result_global = new GlobalVariable(M,
183 result_global->getType()->getElementType(),
184 false, /* not constant */
185 GlobalValue::ExternalLinkage,
186 NULL, /* no initializer */
187 new_result_name.c_str());
188
189 // It's too late in compilation to create a new VarDecl for this, but we don't
190 // need to. We point the metadata at the old VarDecl. This creates an odd
191 // anomaly: a variable with a Value whose name is something like $0 and a
192 // Decl whose name is ___clang_expr_result. This condition is handled in
193 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
194 // fixed up.
195
196 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
197 result_decl_intptr,
198 false);
199
200 llvm::Value* values[2];
201 values[0] = new_result_global;
202 values[1] = new_constant_int;
203
204 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
205 named_metadata->addOperand(persistent_global_md);
206
207 if (log)
Sean Callanan2e2db532010-09-07 22:43:19 +0000208 log->Printf("Replacing %s with %s",
209 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000210 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000211
212 if (result_global->hasNUses(0))
213 {
214 // We need to synthesize a store for this variable, because otherwise
215 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000216
Sean Callanan2e2db532010-09-07 22:43:19 +0000217 BasicBlock &entry_block(F.getEntryBlock());
218 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
219
220 if (!first_entry_instruction)
221 return false;
222
223 if (!result_global->hasInitializer())
224 {
225 if (log)
226 log->Printf("Couldn't find initializer for unused variable");
227 return false;
228 }
229
230 Constant *initializer = result_global->getInitializer();
231
232 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
233 new_result_global,
234 first_entry_instruction);
235
236 if (log)
237 log->Printf("Synthesized result store %s\n", PrintValue(synthesized_store).c_str());
238 }
239 else
240 {
241 result_global->replaceAllUsesWith(new_result_global);
242 }
243
Sean Callanan82b74c82010-08-12 01:56:52 +0000244 result_global->eraseFromParent();
245
246 return true;
247}
248
Sean Callananf5857a02010-07-31 01:32:05 +0000249static bool isObjCSelectorRef(Value *V)
250{
251 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
252
253 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
254 return false;
255
256 return true;
257}
258
259bool
260IRForTarget::RewriteObjCSelector(Instruction* selector_load,
261 Module &M)
262{
263 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
264
265 LoadInst *load = dyn_cast<LoadInst>(selector_load);
266
267 if (!load)
268 return false;
269
270 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
271 //
272 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
273 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
274 //
275 // where %obj is the object pointer and %tmp is the selector.
276 //
277 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
278 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
279
280 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
281
282 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
283
284 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
285 return false;
286
287 Constant *osr_initializer = _objc_selector_references_->getInitializer();
288
289 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
290
291 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
292 return false;
293
294 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
295
296 if (!osr_initializer_base)
297 return false;
298
299 // Find the string's initializer (a ConstantArray) and get the string from it
300
301 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
302
303 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
304 return false;
305
306 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
307
308 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
309
310 if (!omvn_initializer_array->isString())
311 return false;
312
313 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
314
315 if (log)
316 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
317
318 // Construct a call to sel_registerName
319
320 if (!m_sel_registerName)
321 {
322 uint64_t srN_addr;
323
324 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
325 return false;
326
327 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
328
329 // The below code would be "more correct," but in actuality what's required is uint8_t*
330 //Type *sel_type = StructType::get(M.getContext());
331 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
332 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
333
334 std::vector <const Type *> srN_arg_types;
335 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
336 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
337
338 // Build the constant containing the pointer to the function
339 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
340 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
341 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
342 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
343 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
344 }
345
346 SmallVector <Value*, 1> srN_arguments;
347
348 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
349
350 srN_arguments.push_back(omvn_pointer);
351
352 CallInst *srN_call = CallInst::Create(m_sel_registerName,
353 srN_arguments.begin(),
354 srN_arguments.end(),
355 "srN",
356 selector_load);
357
358 // Replace the load with the call in all users
359
360 selector_load->replaceAllUsesWith(srN_call);
361
362 selector_load->eraseFromParent();
363
364 return true;
365}
366
367bool
368IRForTarget::rewriteObjCSelectors(Module &M,
369 BasicBlock &BB)
370{
371 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
372
373 BasicBlock::iterator ii;
374
375 typedef SmallVector <Instruction*, 2> InstrList;
376 typedef InstrList::iterator InstrIterator;
377
378 InstrList selector_loads;
379
380 for (ii = BB.begin();
381 ii != BB.end();
382 ++ii)
383 {
384 Instruction &inst = *ii;
385
386 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
387 if (isObjCSelectorRef(load->getPointerOperand()))
388 selector_loads.push_back(&inst);
389 }
390
391 InstrIterator iter;
392
393 for (iter = selector_loads.begin();
394 iter != selector_loads.end();
395 ++iter)
396 {
397 if (!RewriteObjCSelector(*iter, M))
398 {
399 if(log)
400 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
401 return false;
402 }
403 }
404
405 return true;
406}
407
Sean Callanana48fe162010-08-11 03:57:18 +0000408bool
409IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
410 llvm::Module &M)
411{
412 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
413
414 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
415
416 if (!alloc_md || !alloc_md->getNumOperands())
417 return false;
418
419 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
420
421 if (!constant_int)
422 return false;
423
424 // We attempt to register this as a new persistent variable with the DeclMap.
425
426 uintptr_t ptr = constant_int->getZExtValue();
427
Sean Callanan82b74c82010-08-12 01:56:52 +0000428 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000429
Sean Callanan82b74c82010-08-12 01:56:52 +0000430 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
431 &decl->getASTContext());
432
Sean Callanan8c127202010-08-23 23:09:38 +0000433 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000434 return false;
435
436 GlobalVariable *persistent_global = new GlobalVariable(M,
437 alloc->getType()->getElementType(),
438 false, /* not constant */
439 GlobalValue::ExternalLinkage,
440 NULL, /* no initializer */
441 alloc->getName().str().c_str());
442
443 // What we're going to do here is make believe this was a regular old external
444 // variable. That means we need to make the metadata valid.
445
446 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
447
448 llvm::Value* values[2];
449 values[0] = persistent_global;
450 values[1] = constant_int;
451
452 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
453 named_metadata->addOperand(persistent_global_md);
454
455 alloc->replaceAllUsesWith(persistent_global);
456 alloc->eraseFromParent();
457
458 return true;
459}
460
461bool
462IRForTarget::rewritePersistentAllocs(llvm::Module &M,
463 llvm::BasicBlock &BB)
464{
Sean Callanane8a59a82010-09-13 21:34:21 +0000465 if (!m_resolve_vars)
466 return true;
467
Sean Callanana48fe162010-08-11 03:57:18 +0000468 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
469
470 BasicBlock::iterator ii;
471
472 typedef SmallVector <Instruction*, 2> InstrList;
473 typedef InstrList::iterator InstrIterator;
474
475 InstrList pvar_allocs;
476
477 for (ii = BB.begin();
478 ii != BB.end();
479 ++ii)
480 {
481 Instruction &inst = *ii;
482
483 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
484 if (alloc->getName().startswith("$"))
485 pvar_allocs.push_back(alloc);
486 }
487
488 InstrIterator iter;
489
490 for (iter = pvar_allocs.begin();
491 iter != pvar_allocs.end();
492 ++iter)
493 {
494 if (!RewritePersistentAlloc(*iter, M))
495 {
496 if(log)
497 log->PutCString("Couldn't rewrite the creation of a persistent variable");
498 return false;
499 }
500 }
501
502 return true;
503}
504
Sean Callanan8bce6652010-07-13 21:41:46 +0000505static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000506DeclForGlobalValue(Module &module,
507 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000508{
509 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
510
511 if (!named_metadata)
512 return NULL;
513
514 unsigned num_nodes = named_metadata->getNumOperands();
515 unsigned node_index;
516
517 for (node_index = 0;
518 node_index < num_nodes;
519 ++node_index)
520 {
521 MDNode *metadata_node = named_metadata->getOperand(node_index);
522
523 if (!metadata_node)
524 return NULL;
525
526 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000527 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000528
529 if (metadata_node->getOperand(0) != global_value)
530 continue;
531
532 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
533
534 if (!constant_int)
535 return NULL;
536
537 uintptr_t ptr = constant_int->getZExtValue();
538
539 return reinterpret_cast<clang::NamedDecl *>(ptr);
540 }
541
542 return NULL;
543}
544
545bool
546IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000547 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000548 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000549{
Sean Callananf5857a02010-07-31 01:32:05 +0000550 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
551
Sean Callananbc2928a2010-08-03 00:23:29 +0000552 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
553 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000554 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000555 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000556 default:
557 break;
558 case Instruction::GetElementPtr:
559 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000560 Value *s = constant_expr->getOperand(0);
561 MaybeHandleVariable(M, s, Store);
562 }
563 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000564 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000565 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000566 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000567
Sean Callananf5857a02010-07-31 01:32:05 +0000568 if (!named_decl)
569 {
570 if (isObjCSelectorRef(V))
571 return true;
572
573 if (log)
574 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
575 return false;
576 }
577
Sean Callanan810f22d2010-07-16 00:09:46 +0000578 std::string name = named_decl->getName().str();
579
580 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000581 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000582
583 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000584 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000585 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000586 ast_context = &value_decl->getASTContext();
587 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000588 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000589 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000590 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000591 }
592
Sean Callanan02fbafa2010-07-27 21:39:39 +0000593 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000594
595 size_t value_size = m_target_data->getTypeStoreSize(value_type);
596 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
597
Sean Callanan8c127202010-08-23 23:09:38 +0000598 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Sean Callanan45690fe2010-08-30 22:17:16 +0000599 name.c_str(),
Sean Callanan8c127202010-08-23 23:09:38 +0000600 V,
Sean Callananba992c52010-07-27 02:07:53 +0000601 value_size,
602 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000603 return false;
604 }
605
606 return true;
607}
608
609bool
Sean Callananba992c52010-07-27 02:07:53 +0000610IRForTarget::MaybeHandleCall(Module &M,
611 CallInst *C)
612{
613 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
614
Sean Callanan02fbafa2010-07-27 21:39:39 +0000615 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000616
617 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +0000618 {
619 Value *val = C->getCalledValue();
620
621 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
622
623 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
624 {
625 fun = dyn_cast<Function>(const_expr->getOperand(0));
626
627 if (!fun)
628 return true;
629 }
630 else
631 {
632 return true;
633 }
634 }
Sean Callananba992c52010-07-27 02:07:53 +0000635
Sean Callananc04743d2010-09-28 21:13:03 +0000636 std::string str = fun->getName().str();
637
638 if (str.find("llvm.") == 0)
639 {
640 // Probably a LLVM built-in. Let's try again, but looking up the original.
641 //
642 // +- builtin_name_offset [in this case, 5]
643 // |
644 // |====| builtin_name_length [in this case, 6]
645 // 0 |
646 // | | +- builtin_name_end [in this case, 11]
647 // V V V
648 // llvm.______.i32.u8
649 // 012345678901234567
650 // 0 1
651
652 size_t builtin_name_offset = sizeof("llvm.") - 1;
653 size_t builtin_name_end = str.find('.', builtin_name_offset);
654
655 if (builtin_name_end == str.npos)
656 builtin_name_end = str.size() + 1;
657
658 size_t builtin_name_length = builtin_name_end - builtin_name_offset;
659
660 str = str.substr(builtin_name_offset, builtin_name_length);
661
662 if (log)
663 log->Printf("Extracted builtin function name %s", str.c_str());
664 }
665
Sean Callananba992c52010-07-27 02:07:53 +0000666 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000667 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000668 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000669
Sean Callananf5857a02010-07-31 01:32:05 +0000670 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000671 {
Sean Callananf5857a02010-07-31 01:32:05 +0000672 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
673 {
Sean Callanan92aa6662010-09-07 21:49:41 +0000674 fun_value_ptr = NULL;
675
Sean Callananc04743d2010-09-28 21:13:03 +0000676 if (!m_decl_map->GetFunctionAddress(str.c_str(), fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +0000677 {
678 if (log)
Sean Callananc04743d2010-09-28 21:13:03 +0000679 log->Printf("Function %s had no address", str.c_str());
Sean Callanan92aa6662010-09-07 21:49:41 +0000680
681 return false;
682 }
Sean Callananf5857a02010-07-31 01:32:05 +0000683 }
684 }
685 else
686 {
Sean Callananc04743d2010-09-28 21:13:03 +0000687 if (!m_decl_map->GetFunctionAddress(str.c_str(), fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +0000688 {
689 if (log)
Sean Callananc04743d2010-09-28 21:13:03 +0000690 log->Printf("Metadataless function %s had no address", str.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000691 }
Sean Callananba992c52010-07-27 02:07:53 +0000692 }
693
694 if (log)
Sean Callananc04743d2010-09-28 21:13:03 +0000695 log->Printf("Found %s at %llx", str.c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000696
Sean Callananf5857a02010-07-31 01:32:05 +0000697 Value *fun_addr_ptr;
698
699 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000700 {
Sean Callanan02fbafa2010-07-27 21:39:39 +0000701 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
702 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +0000703 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +0000704 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
705 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000706 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
707
708 if (fun_value_ptr)
709 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000710 }
Sean Callananf5857a02010-07-31 01:32:05 +0000711
712 if (fun_value_ptr)
713 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000714
Sean Callananf5857a02010-07-31 01:32:05 +0000715 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000716
Sean Callananc04743d2010-09-28 21:13:03 +0000717 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(M.getContext(), str);
Sean Callanane8a59a82010-09-13 21:34:21 +0000718
719 Value *values[1];
720 values[0] = func_name;
721 MDNode *func_metadata = MDNode::get(M.getContext(), values, 1);
722
723 C->setMetadata("lldb.call.realName", func_metadata);
724
725 if (log)
726 log->Printf("Set metadata for %p [%d, %s]", C, func_name->isString(), func_name->getAsString().c_str());
727
Sean Callananba992c52010-07-27 02:07:53 +0000728 return true;
729}
730
731bool
Sean Callananf5857a02010-07-31 01:32:05 +0000732IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000733{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000734 /////////////////////////////////////////////////////////////////////////
735 // Prepare the current basic block for execution in the remote process
736 //
737
Sean Callanan02fbafa2010-07-27 21:39:39 +0000738 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000739
740 for (ii = BB.begin();
741 ii != BB.end();
742 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000743 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000744 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000745
Sean Callanane8a59a82010-09-13 21:34:21 +0000746 if (m_resolve_vars)
747 {
748 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
749 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
750 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000751
Sean Callanane8a59a82010-09-13 21:34:21 +0000752 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
753 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
754 return false;
755 }
Sean Callananba992c52010-07-27 02:07:53 +0000756
757 if (CallInst *call = dyn_cast<CallInst>(&inst))
758 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000759 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000760 }
761
762 return true;
763}
764
Sean Callanan02fbafa2010-07-27 21:39:39 +0000765static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000766{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000767 Constant *C;
Sean Callanan45839272010-07-24 01:37:44 +0000768
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000769 if (!(C = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +0000770 return false;
771
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000772 ConstantExpr *CE;
773
774 if ((CE = dyn_cast<ConstantExpr>(V)))
775 {
776 if (CE->getOpcode() != Instruction::BitCast)
777 return false;
778
779 C = CE->getOperand(0);
780 }
781
782 GlobalVariable *GV = dyn_cast<GlobalVariable>(C);
Sean Callanan45839272010-07-24 01:37:44 +0000783
784 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
785 return false;
786
787 return true;
788}
789
790static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
791{
792 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
793
794 Value::use_iterator ui;
795
796 for (ui = guard_load->use_begin();
797 ui != guard_load->use_end();
798 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000799 {
Greg Clayton6e713402010-07-30 20:30:44 +0000800 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000801 {
802 // do nothing for the moment
803 }
804 else
805 {
806 ui->replaceUsesOfWith(guard_load, zero);
807 }
808 }
Sean Callanan45839272010-07-24 01:37:44 +0000809
810 guard_load->eraseFromParent();
811}
812
813static void ExciseGuardStore(Instruction* guard_store)
814{
815 guard_store->eraseFromParent();
816}
817
818bool
819IRForTarget::removeGuards(Module &M, BasicBlock &BB)
820{
821 ///////////////////////////////////////////////////////
822 // Eliminate any reference to guard variables found.
823 //
824
Sean Callanan02fbafa2010-07-27 21:39:39 +0000825 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000826
Sean Callanan02fbafa2010-07-27 21:39:39 +0000827 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000828 typedef InstrList::iterator InstrIterator;
829
830 InstrList guard_loads;
831 InstrList guard_stores;
832
833 for (ii = BB.begin();
834 ii != BB.end();
835 ++ii)
836 {
837 Instruction &inst = *ii;
838
839 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
840 if (isGuardVariableRef(load->getPointerOperand()))
841 guard_loads.push_back(&inst);
842
843 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
844 if (isGuardVariableRef(store->getPointerOperand()))
845 guard_stores.push_back(&inst);
846 }
847
848 InstrIterator iter;
849
850 for (iter = guard_loads.begin();
851 iter != guard_loads.end();
852 ++iter)
853 TurnGuardLoadIntoZero(*iter, M);
854
855 for (iter = guard_stores.begin();
856 iter != guard_stores.end();
857 ++iter)
858 ExciseGuardStore(*iter);
859
860 return true;
861}
862
Sean Callananbafd6852010-07-14 23:40:29 +0000863// UnfoldConstant operates on a constant [C] which has just been replaced with a value
864// [new_value]. We assume that new_value has been properly placed early in the function,
865// most likely somewhere in front of the first instruction in the entry basic block
866// [first_entry_instruction].
867//
868// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
869// Where those uses are constants, the function generates new instructions to compute the
870// result of the new, non-constant expression and places them before first_entry_instruction.
871// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
872// for those.
873
874static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000875UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000876{
877 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
878
879 Value::use_iterator ui;
880
Sean Callanana48fe162010-08-11 03:57:18 +0000881 SmallVector<User*, 16> users;
882
883 // We do this because the use list might change, invalidating our iterator.
884 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000885 for (ui = C->use_begin();
886 ui != C->use_end();
887 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000888 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000889
Sean Callanana48fe162010-08-11 03:57:18 +0000890 for (int i = 0;
891 i < users.size();
892 ++i)
893 {
894 User *user = users[i];
895
Sean Callananbafd6852010-07-14 23:40:29 +0000896 if (Constant *constant = dyn_cast<Constant>(user))
897 {
898 // synthesize a new non-constant equivalent of the constant
899
900 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
901 {
902 switch (constant_expr->getOpcode())
903 {
904 default:
905 if (log)
906 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
907 return false;
908 case Instruction::BitCast:
909 {
910 // UnaryExpr
911 // OperandList[0] is value
912
913 Value *s = constant_expr->getOperand(0);
914
915 if (s == C)
916 s = new_value;
917
918 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
919
920 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
921 }
922 break;
923 case Instruction::GetElementPtr:
924 {
925 // GetElementPtrConstantExpr
926 // OperandList[0] is base
927 // OperandList[1]... are indices
928
929 Value *ptr = constant_expr->getOperand(0);
930
931 if (ptr == C)
932 ptr = new_value;
933
934 SmallVector<Value*, 16> indices;
935
936 unsigned operand_index;
937 unsigned num_operands = constant_expr->getNumOperands();
938
939 for (operand_index = 1;
940 operand_index < num_operands;
941 ++operand_index)
942 {
943 Value *operand = constant_expr->getOperand(operand_index);
944
945 if (operand == C)
946 operand = new_value;
947
948 indices.push_back(operand);
949 }
950
951 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
952
953 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
954 }
955 break;
956 }
957 }
958 else
959 {
960 if (log)
961 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
962 return false;
963 }
964 }
965 else
966 {
967 // simple fall-through case for non-constants
968 user->replaceUsesOfWith(C, new_value);
969 }
970 }
971
972 return true;
973}
974
Sean Callanan8bce6652010-07-13 21:41:46 +0000975bool
Sean Callananf5857a02010-07-31 01:32:05 +0000976IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000977{
Sean Callanane8a59a82010-09-13 21:34:21 +0000978 if (!m_resolve_vars)
979 return true;
980
Sean Callanan8bce6652010-07-13 21:41:46 +0000981 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
982
983 m_decl_map->DoStructLayout();
984
985 if (log)
986 log->Printf("Element arrangement:");
987
988 uint32_t num_elements;
989 uint32_t element_index;
990
991 size_t size;
992 off_t alignment;
993
994 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
995 return false;
996
Sean Callananf5857a02010-07-31 01:32:05 +0000997 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000998
Sean Callananf5857a02010-07-31 01:32:05 +0000999 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +00001000 return false;
1001
Sean Callanan02fbafa2010-07-27 21:39:39 +00001002 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00001003
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001004 if (argument->getName().equals("this"))
1005 {
1006 ++iter;
1007
1008 if (iter == F.getArgumentList().end())
1009 return false;
1010
1011 argument = iter;
1012 }
1013
Sean Callanan8bce6652010-07-13 21:41:46 +00001014 if (!argument->getName().equals("___clang_arg"))
1015 return false;
1016
1017 if (log)
1018 log->Printf("Arg: %s", PrintValue(argument).c_str());
1019
Sean Callananf5857a02010-07-31 01:32:05 +00001020 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +00001021 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00001022
1023 if (!first_entry_instruction)
1024 return false;
1025
1026 LLVMContext &context(M.getContext());
1027 const IntegerType *offset_type(Type::getInt32Ty(context));
1028
1029 if (!offset_type)
1030 return false;
1031
1032 for (element_index = 0; element_index < num_elements; ++element_index)
1033 {
1034 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001035 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +00001036 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +00001037 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +00001038
Sean Callanan45690fe2010-08-30 22:17:16 +00001039 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +00001040 return false;
1041
1042 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +00001043 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00001044 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +00001045 name,
Sean Callanan8bce6652010-07-13 21:41:46 +00001046 PrintValue(value, true).c_str(),
1047 offset);
1048
1049 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
1050 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
1051 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
1052
Sean Callananbafd6852010-07-14 23:40:29 +00001053 if (Constant *constant = dyn_cast<Constant>(value))
1054 UnfoldConstant(constant, bit_cast, first_entry_instruction);
1055 else
1056 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +00001057 }
1058
1059 if (log)
1060 log->Printf("Total structure [align %d, size %d]", alignment, size);
1061
1062 return true;
1063}
1064
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001065bool
1066IRForTarget::runOnModule(Module &M)
1067{
1068 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
1069
Sean Callanan65dafa82010-08-27 01:01:44 +00001070 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001071
1072 if (!function)
1073 {
1074 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +00001075 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001076
1077 return false;
1078 }
1079
Sean Callanan02fbafa2010-07-27 21:39:39 +00001080 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001081
Sean Callanan82b74c82010-08-12 01:56:52 +00001082 ////////////////////////////////////////////////////////////
1083 // Replace __clang_expr_result with a persistent variable
1084 //
1085
1086 if (!createResultVariable(M, *function))
1087 return false;
1088
Sean Callananf5857a02010-07-31 01:32:05 +00001089 //////////////////////////////////
1090 // Run basic-block level passes
1091 //
1092
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001093 for (bbi = function->begin();
1094 bbi != function->end();
1095 ++bbi)
1096 {
Sean Callanan8c127202010-08-23 23:09:38 +00001097 if (!removeGuards(M, *bbi))
1098 return false;
1099
Sean Callanana48fe162010-08-11 03:57:18 +00001100 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +00001101 return false;
1102
Sean Callanana48fe162010-08-11 03:57:18 +00001103 if (!rewriteObjCSelectors(M, *bbi))
1104 return false;
1105
Sean Callananf5857a02010-07-31 01:32:05 +00001106 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001107 return false;
1108 }
1109
Sean Callanan8bce6652010-07-13 21:41:46 +00001110 if (log)
1111 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001112 std::string s;
1113 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001114
Sean Callanan321fe9e2010-07-28 01:00:59 +00001115 M.print(oss, NULL);
1116
1117 oss.flush();
1118
1119 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001120 }
1121
Sean Callanana48fe162010-08-11 03:57:18 +00001122 ///////////////////////////////
1123 // Run function-level passes
1124 //
1125
1126 if (!replaceVariables(M, *function))
1127 return false;
1128
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001129 return true;
1130}
1131
1132void
1133IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001134 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001135{
1136}
1137
1138PassManagerType
1139IRForTarget::getPotentialPassManagerType() const
1140{
1141 return PMT_ModulePassManager;
1142}