LLDB mainline
IRForTarget.cpp
Go to the documentation of this file.
1//===-- IRForTarget.cpp ---------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "IRForTarget.h"
11
13#include "ClangUtil.h"
14
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/InstrTypes.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/Intrinsics.h"
21#include "llvm/IR/LegacyPassManager.h"
22#include "llvm/IR/Metadata.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
26#include "llvm/Support/ErrorExtras.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/IPO.h"
29
30#include "clang/AST/ASTContext.h"
31
32#include "lldb/Core/dwarf.h"
38#include "lldb/Utility/Endian.h"
40#include "lldb/Utility/Log.h"
41#include "lldb/Utility/Scalar.h"
43
44#include <map>
45#include <optional>
46
47using namespace llvm;
49
50typedef SmallVector<Instruction *, 2> InstrList;
51
54
56
57llvm::Value *
59 if (!m_values.count(function)) {
60 llvm::Value *ret = m_maker(function);
61 m_values[function] = ret;
62 return ret;
63 }
64 return m_values[function];
65}
66
67static llvm::Value *FindEntryInstruction(llvm::Function *function) {
68 if (function->empty())
69 return nullptr;
70
71 return &*function->getEntryBlock().getFirstNonPHIOrPseudoProbe();
72}
73
75 bool resolve_vars,
76 lldb_private::IRExecutionUnit &execution_unit,
77 lldb_private::Stream &error_stream,
78 lldb_private::ExecutionPolicy execution_policy,
79 const char *func_name)
80 : m_resolve_vars(resolve_vars), m_func_name(func_name),
81 m_decl_map(decl_map), m_error_stream(error_stream),
82 m_execution_unit(execution_unit), m_policy(execution_policy),
84
85/* Handy utility functions used at several places in the code */
86
87static std::string PrintValue(const Value *value) {
88 if (!value)
89 return {};
90 std::string s;
91 raw_string_ostream rso(s);
92 value->print(rso);
93 return s;
94}
95
96static std::string PrintType(const llvm::Type *type) {
97 if (!type)
98 return {};
99 std::string s;
100 raw_string_ostream rso(s);
101 type->print(rso);
102 return s;
103}
104
105bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) {
106 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
107
108 return true;
109}
110
111clang::NamedDecl *IRForTarget::DeclForGlobal(const GlobalValue *global_val,
112 Module *module) {
113 NamedMDNode *named_metadata =
114 module->getNamedMetadata("clang.global.decl.ptrs");
115
116 if (!named_metadata)
117 return nullptr;
118
119 unsigned num_nodes = named_metadata->getNumOperands();
120 unsigned node_index;
121
122 for (node_index = 0; node_index < num_nodes; ++node_index) {
123 llvm::MDNode *metadata_node =
124 dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
125 if (!metadata_node)
126 return nullptr;
127
128 if (metadata_node->getNumOperands() != 2)
129 continue;
130
131 if (mdconst::dyn_extract_or_null<GlobalValue>(
132 metadata_node->getOperand(0)) != global_val)
133 continue;
134
135 ConstantInt *constant_int =
136 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
137
138 if (!constant_int)
139 return nullptr;
140
141 uintptr_t ptr = constant_int->getZExtValue();
142
143 return reinterpret_cast<clang::NamedDecl *>(ptr);
144 }
145
146 return nullptr;
147}
148
149clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) {
150 return DeclForGlobal(global_val, m_module);
151}
152
153/// Returns true iff the mangled symbol is for a static guard variable.
154static bool isGuardVariableSymbol(llvm::StringRef mangled_symbol,
155 bool check_ms_abi = true) {
156 bool result =
157 mangled_symbol.starts_with("_ZGV"); // Itanium ABI guard variable
158 if (check_ms_abi)
159 result |= mangled_symbol.ends_with("@4IA"); // Microsoft ABI
160 return result;
161}
162
163bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) {
164 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
165
166 if (!m_resolve_vars)
167 return true;
168
169 // Find the result variable. If it doesn't exist, we can give up right here.
170
171 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
172
173 llvm::StringRef result_name;
174 bool found_result = false;
175
176 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
177 result_name = value_symbol.first();
178
179 // Check if this is a guard variable. It seems this causes some hiccups
180 // on Windows, so let's only check for Itanium guard variables.
181 bool is_guard_var = isGuardVariableSymbol(result_name, /*MS ABI*/ false);
182
183 // Skip non-globals, e.g. the MS ABI dynamic initializer function that
184 // shares a mangled name with the result variable.
185 if (!isa<GlobalVariable>(value_symbol.second))
186 continue;
187
188 if (result_name.contains("$__lldb_expr_result_ptr") && !is_guard_var) {
189 found_result = true;
190 m_result_is_pointer = true;
191 break;
192 }
193
194 if (result_name.contains("$__lldb_expr_result") && !is_guard_var) {
195 found_result = true;
196 m_result_is_pointer = false;
197 break;
198 }
199 }
200
201 if (!found_result) {
202 LLDB_LOG(log, "Couldn't find result variable");
203
204 return true;
205 }
206
207 LLDB_LOG(log, "Result name: \"{0}\"", result_name);
208
209 Value *result_value = m_module->getNamedValue(result_name);
210
211 if (!result_value) {
212 LLDB_LOG(log, "Result variable had no data");
213
214 m_error_stream.Format("Internal error [IRForTarget]: Result variable's "
215 "name ({0}) exists, but not its definition\n",
216 result_name);
217
218 return false;
219 }
220
221 LLDB_LOG(log, "Found result in the IR: \"{0}\"", PrintValue(result_value));
222
223 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
224
225 if (!result_global) {
226 LLDB_LOG(log, "Result variable isn't a GlobalVariable");
227
228 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) "
229 "is defined, but is not a global variable\n",
230 result_name);
231
232 return false;
233 }
234
235 clang::NamedDecl *result_decl = DeclForGlobal(result_global);
236 if (!result_decl) {
237 LLDB_LOG(log, "Result variable doesn't have a corresponding Decl");
238
239 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) "
240 "does not have a corresponding Clang entity\n",
241 result_name);
242
243 return false;
244 }
245
246 if (log) {
247 std::string decl_desc_str;
248 raw_string_ostream decl_desc_stream(decl_desc_str);
249 result_decl->print(decl_desc_stream);
250
251 LLDB_LOG(log, "Found result decl: \"{0}\"", decl_desc_str);
252 }
253
254 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
255 if (!result_var) {
256 LLDB_LOG(log, "Result variable Decl isn't a VarDecl");
257
258 m_error_stream.Format("Internal error [IRForTarget]: Result variable "
259 "({0})'s corresponding Clang entity isn't a "
260 "variable\n",
261 result_name);
262
263 return false;
264 }
265
266 // Get the next available result name from m_decl_map and create the
267 // persistent variable for it
268
269 // If the result is an Lvalue, it is emitted as a pointer; see
270 // ASTResultSynthesizer::SynthesizeBodyResult.
272 clang::QualType pointer_qual_type = result_var->getType();
273 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
274
275 const clang::PointerType *pointer_pointertype =
276 pointer_type->getAs<clang::PointerType>();
277 const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
278 pointer_type->getAs<clang::ObjCObjectPointerType>();
279
280 if (pointer_pointertype) {
281 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
282
284 m_decl_map->GetTypeSystem()->GetType(element_qual_type));
285 } else if (pointer_objcobjpointertype) {
286 clang::QualType element_qual_type =
287 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
288
290 m_decl_map->GetTypeSystem()->GetType(element_qual_type));
291 } else {
292 LLDB_LOG(log, "Expected result to have pointer type, but it did not");
293
294 m_error_stream.Format("Internal error [IRForTarget]: Lvalue result ({0}) "
295 "is not a pointer variable\n",
296 result_name);
297
298 return false;
299 }
300 } else {
302 m_decl_map->GetTypeSystem()->GetType(result_var->getType()));
303 }
304
305 lldb::TargetSP target_sp(m_execution_unit.GetTarget());
306 auto bit_size_or_err = m_result_type.GetBitSize(target_sp.get());
307 if (!bit_size_or_err) {
308 lldb_private::StreamString type_desc_stream;
309 m_result_type.DumpTypeDescription(&type_desc_stream);
310
311 LLDB_LOG(log, "Result type has unknown size");
312
313 m_error_stream.Printf("Error [IRForTarget]: Size of result type '%s' "
314 "couldn't be determined\n%s",
315 type_desc_stream.GetData(),
316 llvm::toString(bit_size_or_err.takeError()).c_str());
317 return false;
318 }
319
320 if (log) {
321 lldb_private::StreamString type_desc_stream;
322 m_result_type.DumpTypeDescription(&type_desc_stream);
323
324 LLDB_LOG(log, "Result decl type: \"{0}\"", type_desc_stream.GetData());
325 }
326
328
329 LLDB_LOG(log, "Creating a new result global: \"{0}\" with size {1}",
331 llvm::expectedToOptional(m_result_type.GetByteSize(target_sp.get()))
332 .value_or(0));
333
334 // Construct a new result global and set up its metadata
335
336 GlobalVariable *new_result_global = new GlobalVariable(
337 (*m_module), result_global->getValueType(), false, /* not constant */
338 GlobalValue::ExternalLinkage, nullptr, /* no initializer */
339 m_result_name.GetCString());
340
341 // It's too late in compilation to create a new VarDecl for this, but we
342 // don't need to. We point the metadata at the old VarDecl. This creates an
343 // odd anomaly: a variable with a Value whose name is something like $0 and a
344 // Decl whose name is $__lldb_expr_result. This condition is handled in
345 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
346 // fixed up.
347
348 ConstantInt *new_constant_int =
349 ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
350 reinterpret_cast<uintptr_t>(result_decl), false);
351
352 llvm::Metadata *values[2];
353 values[0] = ConstantAsMetadata::get(new_result_global);
354 values[1] = ConstantAsMetadata::get(new_constant_int);
355
356 ArrayRef<Metadata *> value_ref(values, 2);
357
358 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
359 NamedMDNode *named_metadata =
360 m_module->getNamedMetadata("clang.global.decl.ptrs");
361 named_metadata->addOperand(persistent_global_md);
362
363 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(result_global),
364 PrintValue(new_result_global));
365
366 if (result_global->use_empty()) {
367 // We need to synthesize a store for this variable, because otherwise
368 // there's nothing to put into its equivalent persistent variable.
369
370 BasicBlock &entry_block(llvm_function.getEntryBlock());
371 Instruction *first_entry_instruction(
372 &*entry_block.getFirstNonPHIOrPseudoProbe());
373
374 if (!first_entry_instruction)
375 return false;
376
377 if (!result_global->hasInitializer()) {
378 LLDB_LOG(log, "Couldn't find initializer for unused variable");
379
380 m_error_stream.Format("Internal error [IRForTarget]: Result variable "
381 "({0}) has no writes and no initializer\n",
382 result_name);
383
384 return false;
385 }
386
387 Constant *initializer = result_global->getInitializer();
388
389 StoreInst *synthesized_store = new StoreInst(
390 initializer, new_result_global, first_entry_instruction->getIterator());
391
392 LLDB_LOG(log, "Synthesized result store \"{0}\"\n",
393 PrintValue(synthesized_store));
394 } else {
395 result_global->replaceAllUsesWith(new_result_global);
396 }
397
398 if (!m_decl_map->AddPersistentVariable(
399 result_decl, m_result_name, m_result_type, true, m_result_is_pointer))
400 return false;
401
402 result_global->eraseFromParent();
403
404 return true;
405}
406
407bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str,
408 llvm::GlobalVariable *cstr) {
409 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
410
411 Type *ns_str_ty = ns_str->getType();
412
413 Type *i8_ptr_ty = PointerType::getUnqual(m_module->getContext());
414 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
415 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
416
418 lldb::addr_t CFStringCreateWithBytes_addr;
419
420 static lldb_private::ConstString g_CFStringCreateWithBytes_str(
421 "CFStringCreateWithBytes");
422
423 bool missing_weak = false;
424 CFStringCreateWithBytes_addr = m_execution_unit.FindSymbol(
425 g_CFStringCreateWithBytes_str, missing_weak);
426 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS || missing_weak) {
427 LLDB_LOG(log, "Couldn't find CFStringCreateWithBytes in the target");
428
429 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C "
430 "constant string requires "
431 "CFStringCreateWithBytes\n");
432
433 return false;
434 }
435
436 LLDB_LOG(log, "Found CFStringCreateWithBytes at {0:x}",
437 CFStringCreateWithBytes_addr);
438
439 // Build the function type:
440 //
441 // CFStringRef CFStringCreateWithBytes (
442 // CFAllocatorRef alloc,
443 // const UInt8 *bytes,
444 // CFIndex numBytes,
445 // CFStringEncoding encoding,
446 // Boolean isExternalRepresentation
447 // );
448 //
449 // We make the following substitutions:
450 //
451 // CFStringRef -> i8*
452 // CFAllocatorRef -> i8*
453 // UInt8 * -> i8*
454 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its
455 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8
456
457 Type *arg_type_array[5];
458
459 arg_type_array[0] = i8_ptr_ty;
460 arg_type_array[1] = i8_ptr_ty;
461 arg_type_array[2] = m_intptr_ty;
462 arg_type_array[3] = i32_ty;
463 arg_type_array[4] = i8_ty;
464
465 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
466
467 llvm::FunctionType *CFSCWB_ty =
468 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
469
470 // Build the constant containing the pointer to the function
471 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(m_module->getContext());
472 Constant *CFSCWB_addr_int =
473 ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
475 CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)};
476 }
477
478 ConstantDataSequential *string_array = nullptr;
479
480 if (cstr)
481 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
482
483 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
484 Constant *bytes_arg = cstr ? cstr : Constant::getNullValue(i8_ptr_ty);
485 Constant *numBytes_arg = ConstantInt::get(
486 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false);
487 int encoding_flags = 0;
488 switch (cstr ? string_array->getElementByteSize() : 1) {
489 case 1:
490 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */
491 break;
492 case 2:
493 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */
494 break;
495 case 4:
496 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */
497 break;
498 default:
499 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */
500 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual "
501 "element size {0}",
502 string_array->getElementByteSize());
503 }
504 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false);
505 Constant *isExternal_arg =
506 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
507
508 Value *argument_array[5];
509
510 argument_array[0] = alloc_arg;
511 argument_array[1] = bytes_arg;
512 argument_array[2] = numBytes_arg;
513 argument_array[3] = encoding_arg;
514 argument_array[4] = isExternal_arg;
515
516 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
517
518 FunctionValueCache CFSCWB_Caller(
519 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
520 return CallInst::Create(
521 m_CFStringCreateWithBytes, CFSCWB_arguments,
522 "CFStringCreateWithBytes",
523 llvm::cast<Instruction>(
524 m_entry_instruction_finder.GetValue(function))
525 ->getIterator());
526 });
527
528 if (auto err = UnfoldConstant(ns_str, nullptr, CFSCWB_Caller,
530 std::string error_msg = llvm::toString(std::move(err));
531 LLDB_LOG(log,
532 "Couldn't replace the NSString with the result of the call: {0}",
533 error_msg);
534
535 m_error_stream.Format("error [IRForTarget internal]: Couldn't replace an "
536 "Objective-C constant string with a dynamic "
537 "string\n{0}",
538 error_msg);
539
540 return false;
541 }
542
543 ns_str->eraseFromParent();
544
545 return true;
546}
547
549 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
550
551 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
552
553 std::vector<std::pair<GlobalVariable *, GlobalVariable *>>
554 nsstring_to_cstr_list;
555
556 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
557 llvm::StringRef value_name = value_symbol.first();
558
559 if (value_name.contains("_unnamed_cfstring_")) {
560 Value *nsstring_value = value_symbol.second;
561
562 GlobalVariable *nsstring_global =
563 dyn_cast<GlobalVariable>(nsstring_value);
564
565 if (!nsstring_global) {
566 LLDB_LOG(log, "NSString variable is not a GlobalVariable");
567
568 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
569 "constant string is not a global variable\n");
570
571 return false;
572 }
573
574 if (!nsstring_global->hasInitializer()) {
575 LLDB_LOG(log, "NSString variable does not have an initializer");
576
577 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
578 "constant string does not have an initializer\n");
579
580 return false;
581 }
582
583 ConstantStruct *nsstring_struct =
584 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
585
586 if (!nsstring_struct) {
587 LLDB_LOG(log,
588 "NSString variable's initializer is not a ConstantStruct");
589
590 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
591 "constant string is not a structure constant\n");
592
593 return false;
594 }
595
596 // We expect the following structure:
597 //
598 // struct {
599 // int *isa;
600 // int flags;
601 // char *str;
602 // long length;
603 // };
604
605 if (nsstring_struct->getNumOperands() != 4) {
606
607 LLDB_LOG(log,
608 "NSString variable's initializer structure has an "
609 "unexpected number of members. Should be 4, is {0}",
610 nsstring_struct->getNumOperands());
611
612 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an "
613 "Objective-C constant string is not as "
614 "expected\n");
615
616 return false;
617 }
618
619 Constant *nsstring_member = nsstring_struct->getOperand(2);
620
621 if (!nsstring_member) {
622 LLDB_LOG(log, "NSString initializer's str element was empty");
623
624 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
625 "constant string does not have a string "
626 "initializer\n");
627
628 return false;
629 }
630
631 auto *cstr_global = dyn_cast<GlobalVariable>(nsstring_member);
632 if (!cstr_global) {
633 LLDB_LOG(log,
634 "NSString initializer's str element is not a GlobalVariable");
635
636 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled"
637 "constant string initializer\n");
638
639 return false;
640 }
641
642 if (!cstr_global->hasInitializer()) {
643 LLDB_LOG(log, "NSString initializer's str element does not have an "
644 "initializer");
645
646 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
647 "constant string's string initializer doesn't "
648 "point to initialized data\n");
649
650 return false;
651 }
652
653 /*
654 if (!cstr_array)
655 {
656 if (log)
657 log->PutCString("NSString initializer's str element is not a
658 ConstantArray");
659
660 if (m_error_stream)
661 m_error_stream.Printf("Internal error [IRForTarget]: An
662 Objective-C constant string's string initializer doesn't point to an
663 array\n");
664
665 return false;
666 }
667
668 if (!cstr_array->isCString())
669 {
670 if (log)
671 log->PutCString("NSString initializer's str element is not a C
672 string array");
673
674 if (m_error_stream)
675 m_error_stream.Printf("Internal error [IRForTarget]: An
676 Objective-C constant string's string initializer doesn't point to a C
677 string\n");
678
679 return false;
680 }
681 */
682
683 ConstantDataArray *cstr_array =
684 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
685
686 if (cstr_array)
687 LLDB_LOG(log, "Found NSString constant {0}, which contains \"{1}\"",
688 value_name, cstr_array->getAsString());
689 else
690 LLDB_LOG(log, "Found NSString constant {0}, which contains \"\"",
691 value_name);
692
693 if (!cstr_array)
694 cstr_global = nullptr;
695
696 // Queue up replacing the string as we are currently iterating
697 // over the module.
698 nsstring_to_cstr_list.emplace_back(nsstring_global, cstr_global);
699 }
700 }
701
702 for (auto [nsstring_global, cstr_global] : nsstring_to_cstr_list) {
703 if (!RewriteObjCConstString(nsstring_global, cstr_global)) {
704 LLDB_LOG(log, "Error rewriting the constant string");
705 return false;
706 }
707 }
708
709 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
710 llvm::StringRef value_name = value_symbol.first();
711
712 if (value_name == "__CFConstantStringClassReference") {
713 GlobalVariable *gv = dyn_cast<GlobalVariable>(value_symbol.second);
714
715 if (!gv) {
716 LLDB_LOG(log,
717 "__CFConstantStringClassReference is not a global variable");
718
719 m_error_stream.Printf("Internal error [IRForTarget]: Found a "
720 "CFConstantStringClassReference, but it is not a "
721 "global object\n");
722
723 return false;
724 }
725
726 gv->eraseFromParent();
727
728 break;
729 }
730 }
731
732 return true;
733}
734
735static bool IsObjCSelectorRef(Value *value) {
736 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
737
738 return !(
739 !global_variable || !global_variable->hasName() ||
740 !global_variable->getName().starts_with("OBJC_SELECTOR_REFERENCES_"));
741}
742
743// This function does not report errors; its callers are responsible.
744bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) {
745 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
746
747 LoadInst *load = dyn_cast<LoadInst>(selector_load);
748
749 if (!load)
750 return false;
751
752 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend
753 // gets represented as
754 //
755 // %sel = load ptr, ptr @OBJC_SELECTOR_REFERENCES_, align 8
756 // call i8 @objc_msgSend(ptr %obj, ptr %sel, ...)
757 //
758 // where %obj is the object pointer and %sel is the selector.
759 //
760 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called
761 // @"\01L_OBJC_METH_VAR_NAME_".
762 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
763
764 // Find the pointer's initializer and get the string from its target.
765
766 GlobalVariable *_objc_selector_references_ =
767 dyn_cast<GlobalVariable>(load->getPointerOperand());
768
769 if (!_objc_selector_references_ ||
770 !_objc_selector_references_->hasInitializer())
771 return false;
772
773 Constant *osr_initializer = _objc_selector_references_->getInitializer();
774 if (!osr_initializer)
775 return false;
776
777 // Find the string's initializer (a ConstantArray) and get the string from it
778
779 GlobalVariable *_objc_meth_var_name_ =
780 dyn_cast<GlobalVariable>(osr_initializer);
781
782 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
783 return false;
784
785 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
786
787 ConstantDataArray *omvn_initializer_array =
788 dyn_cast<ConstantDataArray>(omvn_initializer);
789
790 if (!omvn_initializer_array->isString())
791 return false;
792
793 std::string omvn_initializer_string =
794 std::string(omvn_initializer_array->getAsString());
795
796 LLDB_LOG(log, "Found Objective-C selector reference \"{0}\"",
797 omvn_initializer_string);
798
799 // Construct a call to sel_registerName
800
801 if (!m_sel_registerName) {
802 lldb::addr_t sel_registerName_addr;
803
804 bool missing_weak = false;
805 static lldb_private::ConstString g_sel_registerName_str("sel_registerName");
806 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str,
807 missing_weak);
808 if (sel_registerName_addr == LLDB_INVALID_ADDRESS || missing_weak)
809 return false;
810
811 LLDB_LOG(log, "Found sel_registerName at {0:x}", sel_registerName_addr);
812
813 // Build the function type: struct objc_selector
814 // *sel_registerName(uint8_t*)
815
816 // The below code would be "more correct," but in actuality what's required
817 // is uint8_t*
818 // Type *sel_type = StructType::get(m_module->getContext());
819 // Type *sel_ptr_type = PointerType::getUnqual(sel_type);
820 Type *sel_ptr_type = PointerType::getUnqual(m_module->getContext());
821
822 Type *type_array[1];
823
824 type_array[0] = llvm::PointerType::getUnqual(m_module->getContext());
825
826 ArrayRef<Type *> srN_arg_types(type_array, 1);
827
828 llvm::FunctionType *srN_type =
829 FunctionType::get(sel_ptr_type, srN_arg_types, false);
830
831 // Build the constant containing the pointer to the function
832 PointerType *srN_ptr_ty = PointerType::getUnqual(m_module->getContext());
833 Constant *srN_addr_int =
834 ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
835 m_sel_registerName = {srN_type,
836 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)};
837 }
838
839 CallInst *srN_call =
840 CallInst::Create(m_sel_registerName, _objc_meth_var_name_,
841 "sel_registerName", selector_load->getIterator());
842
843 // Replace the load with the call in all users
844
845 selector_load->replaceAllUsesWith(srN_call);
846
847 selector_load->eraseFromParent();
848
849 return true;
850}
851
852bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) {
853 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
854
855 InstrList selector_loads;
856
857 for (Instruction &inst : basic_block) {
858 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
859 if (IsObjCSelectorRef(load->getPointerOperand()))
860 selector_loads.push_back(&inst);
861 }
862
863 for (Instruction *inst : selector_loads) {
864 if (!RewriteObjCSelector(inst)) {
865 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
866 "static reference to an Objective-C selector to a "
867 "dynamic reference\n");
868
869 LLDB_LOG(log, "Couldn't rewrite a reference to an Objective-C selector");
870
871 return false;
872 }
873 }
874
875 return true;
876}
877
878// This function does not report errors; its callers are responsible.
879bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) {
880 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
881
882 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
883
884 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
885
886 if (!alloc_md || !alloc_md->getNumOperands())
887 return false;
888
889 ConstantInt *constant_int =
890 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
891
892 if (!constant_int)
893 return false;
894
895 // We attempt to register this as a new persistent variable with the DeclMap.
896
897 uintptr_t ptr = constant_int->getZExtValue();
898
899 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
900
901 lldb_private::TypeFromParser result_decl_type(
902 m_decl_map->GetTypeSystem()->GetType(decl->getType()));
903
904 StringRef decl_name(decl->getName());
905 lldb_private::ConstString persistent_variable_name(decl_name);
906 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
907 result_decl_type, false, false))
908 return false;
909
910 GlobalVariable *persistent_global = new GlobalVariable(
911 (*m_module), alloc->getType(), false, /* not constant */
912 GlobalValue::ExternalLinkage, nullptr, /* no initializer */
913 alloc->getName().str());
914
915 // What we're going to do here is make believe this was a regular old
916 // external variable. That means we need to make the metadata valid.
917
918 NamedMDNode *named_metadata =
919 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
920
921 llvm::Metadata *values[2];
922 values[0] = ConstantAsMetadata::get(persistent_global);
923 values[1] = ConstantAsMetadata::get(constant_int);
924
925 ArrayRef<llvm::Metadata *> value_ref(values, 2);
926
927 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
928 named_metadata->addOperand(persistent_global_md);
929
930 // Now, since the variable is a pointer variable, we will drop in a load of
931 // that pointer variable.
932
933 LoadInst *persistent_load =
934 new LoadInst(persistent_global->getValueType(), persistent_global, "",
935 alloc->getIterator());
936
937 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(alloc),
938 PrintValue(persistent_load));
939
940 alloc->replaceAllUsesWith(persistent_load);
941 alloc->eraseFromParent();
942
943 return true;
944}
945
946bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) {
947 if (!m_resolve_vars)
948 return true;
949
950 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
951
952 InstrList pvar_allocs;
953
954 for (Instruction &inst : basic_block) {
955
956 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
957 llvm::StringRef alloc_name = alloc->getName();
958
959 if (alloc_name.starts_with("$") && !alloc_name.starts_with("$__lldb")) {
960 if (alloc_name.find_first_of("0123456789") == 1) {
961 LLDB_LOG(log, "Rejecting a numeric persistent variable.");
962
963 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, "
964 "$1, ... are reserved for use as result "
965 "names\n");
966
967 return false;
968 }
969
970 pvar_allocs.push_back(alloc);
971 }
972 }
973 }
974
975 for (Instruction *inst : pvar_allocs) {
976 if (!RewritePersistentAlloc(inst)) {
977 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
978 "the creation of a persistent variable\n");
979
980 LLDB_LOG(log, "Couldn't rewrite the creation of a persistent variable");
981
982 return false;
983 }
984 }
985
986 return true;
987}
988
989// This function does not report errors; its callers are responsible.
990bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) {
991 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
992
993 LLDB_LOG(log, "MaybeHandleVariable ({0})", PrintValue(llvm_value_ptr));
994
995 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
996 switch (constant_expr->getOpcode()) {
997 default:
998 break;
999 case Instruction::GetElementPtr:
1000 case Instruction::BitCast:
1001 Value *s = constant_expr->getOperand(0);
1002 if (!MaybeHandleVariable(s))
1003 return false;
1004 }
1005 } else if (GlobalVariable *global_variable =
1006 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
1007 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1008 return true;
1009
1010 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1011
1012 if (!named_decl) {
1013 if (IsObjCSelectorRef(llvm_value_ptr))
1014 return true;
1015
1016 if (!global_variable->hasExternalLinkage())
1017 return true;
1018
1019 LLDB_LOG(log, "Found global variable \"{0}\" without metadata",
1020 global_variable->getName());
1021
1022 return false;
1023 }
1024
1025 llvm::StringRef name(named_decl->getName());
1026
1027 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1028 if (value_decl == nullptr)
1029 return false;
1030
1031 lldb_private::CompilerType compiler_type =
1032 m_decl_map->GetTypeSystem()->GetType(value_decl->getType());
1033
1034 const Type *value_type = nullptr;
1035
1036 if (name.starts_with("$")) {
1037 // The $__lldb_expr_result name indicates the return value has allocated
1038 // as a static variable. Per the comment at
1039 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static
1040 // variable need to be redirected to the result of dereferencing a
1041 // pointer that is passed in as one of the arguments.
1042 //
1043 // Consequently, when reporting the size of the type, we report a pointer
1044 // type pointing to the type of $__lldb_expr_result, not the type itself.
1045 //
1046 // We also do this for any user-declared persistent variables.
1047 compiler_type = compiler_type.GetPointerType();
1048 value_type = PointerType::getUnqual(global_variable->getContext());
1049 } else {
1050 value_type = global_variable->getType();
1051 }
1052
1053 auto *target = m_execution_unit.GetTarget().get();
1054 std::optional<uint64_t> value_size =
1055 llvm::expectedToOptional(compiler_type.GetByteSize(target));
1056 if (!value_size)
1057 return false;
1058 std::optional<size_t> opt_alignment = compiler_type.GetTypeBitAlign(target);
1059 if (!opt_alignment)
1060 return false;
1061 lldb::offset_t value_alignment = (*opt_alignment + 7ull) / 8ull;
1062
1063 LLDB_LOG(log,
1064 "Type of \"{0}\" is [clang \"{1}\", llvm \"{2}\"] [size {3}, "
1065 "align {4}]",
1066 name,
1067 lldb_private::ClangUtil::GetQualType(compiler_type).getAsString(),
1068 PrintType(value_type), *value_size, value_alignment);
1069
1070 if (named_decl)
1071 m_decl_map->AddValueToStruct(named_decl, lldb_private::ConstString(name),
1072 llvm_value_ptr, *value_size,
1073 value_alignment);
1074 } else if (isa<llvm::Function>(llvm_value_ptr)) {
1075 LLDB_LOG(log, "Function pointers aren't handled right now");
1076
1077 return false;
1078 }
1079
1080 return true;
1081}
1082
1083// This function does not report errors; its callers are responsible.
1084bool IRForTarget::HandleSymbol(Value *symbol) {
1085 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1086
1087 lldb_private::ConstString name(symbol->getName());
1088
1089 lldb::addr_t symbol_addr =
1090 m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny);
1091
1092 if (symbol_addr == LLDB_INVALID_ADDRESS) {
1093 LLDB_LOG(log, "Symbol \"{0}\" had no address", name);
1094
1095 return false;
1096 }
1097
1098 LLDB_LOG(log, "Found \"{0}\" at {1:x}", name, symbol_addr);
1099
1100 Type *symbol_type = symbol->getType();
1101
1102 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1103
1104 Value *symbol_addr_ptr =
1105 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1106
1107 LLDB_LOG(log, "Replacing {0} with {1}", PrintValue(symbol),
1108 PrintValue(symbol_addr_ptr));
1109
1110 symbol->replaceAllUsesWith(symbol_addr_ptr);
1111
1112 return true;
1113}
1114
1116 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1117
1118 LLDB_LOG(log, "MaybeHandleCallArguments({0})", PrintValue(Old));
1119
1120 for (unsigned op_index = 0, num_ops = Old->arg_size();
1121 op_index < num_ops; ++op_index)
1122 // conservatively believe that this is a store
1123 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) {
1124 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1125 "one of the arguments of a function call.\n");
1126
1127 return false;
1128 }
1129
1130 return true;
1131}
1132
1133bool IRForTarget::HandleObjCClass(Value *classlist_reference) {
1134 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1135
1136 GlobalVariable *global_variable =
1137 dyn_cast<GlobalVariable>(classlist_reference);
1138
1139 if (!global_variable)
1140 return false;
1141
1142 Constant *initializer = global_variable->getInitializer();
1143
1144 if (!initializer)
1145 return false;
1146
1147 if (!initializer->hasName())
1148 return false;
1149
1150 StringRef name(initializer->getName());
1151 lldb_private::ConstString name_cstr(name);
1152 lldb::addr_t class_ptr =
1153 m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1154
1155 LLDB_LOG(log, "Found reference to Objective-C class {0} ({1:x})", name,
1156 (unsigned long long)class_ptr);
1157
1158 if (class_ptr == LLDB_INVALID_ADDRESS)
1159 return false;
1160
1161 if (global_variable->use_empty())
1162 return false;
1163
1164 SmallVector<LoadInst *, 2> load_instructions;
1165
1166 for (llvm::User *u : global_variable->users()) {
1167 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1168 load_instructions.push_back(load_instruction);
1169 }
1170
1171 if (load_instructions.empty())
1172 return false;
1173
1174 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1175
1176 for (LoadInst *load_instruction : load_instructions) {
1177 Constant *class_bitcast =
1178 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1179
1180 load_instruction->replaceAllUsesWith(class_bitcast);
1181
1182 load_instruction->eraseFromParent();
1183 }
1184
1185 return true;
1186}
1187
1188bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) {
1189 std::vector<CallInst *> calls_to_remove;
1190 llvm::SmallVector<llvm::Function *, 2> dead_atexit_callbacks;
1191
1192 for (Instruction &inst : basic_block) {
1193 CallInst *call = dyn_cast<CallInst>(&inst);
1194
1195 // MaybeHandleCallArguments handles error reporting; we are silent here
1196 if (!call)
1197 continue;
1198
1199 bool remove = false;
1200
1201 llvm::Function *func = call->getCalledFunction();
1202
1203 // Itanium ABI uses __cxa_atexit; MS ABI uses plain atexit.
1204 if (func &&
1205 (func->getName() == "__cxa_atexit" || func->getName() == "atexit"))
1206 remove = true;
1207
1208 llvm::Value *val = call->getCalledOperand();
1209
1210 if (val && (val->getName() == "__cxa_atexit" || val->getName() == "atexit"))
1211 remove = true;
1212
1213 if (remove) {
1214 // MS ABI destructor thunks (mangled "??__F...") reference the static
1215 // they destroy; track them to clear once the call is gone.
1216 if (call->arg_size() > 0)
1217 if (auto *cb = dyn_cast<llvm::Function>(
1218 call->getArgOperand(0)->stripPointerCasts()))
1219 if (cb->hasInternalLinkage() && cb->getName().starts_with("??__F"))
1220 dead_atexit_callbacks.push_back(cb);
1221 calls_to_remove.push_back(call);
1222 }
1223 }
1224
1225 for (CallInst *ci : calls_to_remove)
1226 ci->eraseFromParent();
1227
1228 // Clear the body of any orphaned atexit-destructor thunk so it no longer
1229 // references the statics it used to destroy.
1230 for (llvm::Function *cb : dead_atexit_callbacks) {
1231 if (!cb->use_empty())
1232 continue;
1233 cb->deleteBody();
1234 llvm::BasicBlock *entry =
1235 llvm::BasicBlock::Create(cb->getContext(), "", cb);
1236 llvm::ReturnInst::Create(cb->getContext(), entry);
1237 }
1238
1239 return true;
1240}
1241
1242bool IRForTarget::ResolveCalls(BasicBlock &basic_block) {
1243 // Prepare the current basic block for execution in the remote process
1244
1245 for (Instruction &inst : basic_block) {
1246 CallInst *call = dyn_cast<CallInst>(&inst);
1247
1248 // MaybeHandleCallArguments handles error reporting; we are silent here
1249 if (call && !MaybeHandleCallArguments(call))
1250 return false;
1251 }
1252
1253 return true;
1254}
1255
1256bool IRForTarget::ResolveExternals(Function &llvm_function) {
1257 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1258
1259 for (GlobalVariable &global_var : m_module->globals()) {
1260 llvm::StringRef global_name = global_var.getName();
1261
1262 LLDB_LOG(log, "Examining {0}, DeclForGlobalValue returns {1}", global_name,
1263 static_cast<void *>(DeclForGlobal(&global_var)));
1264
1265 if (global_name.starts_with("OBJC_IVAR")) {
1266 if (!HandleSymbol(&global_var)) {
1267 m_error_stream.Format("Error [IRForTarget]: Couldn't find Objective-C "
1268 "indirect ivar symbol {0}\n",
1269 global_name);
1270
1271 return false;
1272 }
1273 } else if (global_name.contains("OBJC_CLASSLIST_REFERENCES_$")) {
1274 if (!HandleObjCClass(&global_var)) {
1275 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1276 "for an Objective-C static method call\n");
1277
1278 return false;
1279 }
1280 } else if (global_name.contains("OBJC_CLASSLIST_SUP_REFS_$")) {
1281 if (!HandleObjCClass(&global_var)) {
1282 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1283 "for an Objective-C static method call\n");
1284
1285 return false;
1286 }
1287 } else if (DeclForGlobal(&global_var)) {
1288 if (!MaybeHandleVariable(&global_var)) {
1289 m_error_stream.Format("Internal error [IRForTarget]: Couldn't rewrite "
1290 "external variable {0}\n",
1291 global_name);
1292
1293 return false;
1294 }
1295 }
1296 }
1297
1298 return true;
1299}
1300
1301static bool isGuardVariableRef(Value *V) {
1302 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1303
1304 if (!GV || !GV->hasName() || !isGuardVariableSymbol(GV->getName()))
1305 return false;
1306
1307 return true;
1308}
1309
1310void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) {
1311 Constant *zero(Constant::getNullValue(guard_load->getType()));
1312 guard_load->replaceAllUsesWith(zero);
1313 guard_load->eraseFromParent();
1314}
1315
1316static void ExciseGuardStore(Instruction *guard_store) {
1317 guard_store->eraseFromParent();
1318}
1319
1320bool IRForTarget::RemoveGuards(BasicBlock &basic_block) {
1321 // Eliminate any reference to guard variables found.
1322
1323 InstrList guard_loads;
1324 InstrList guard_stores;
1325
1326 for (Instruction &inst : basic_block) {
1327
1328 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1329 if (isGuardVariableRef(load->getPointerOperand()))
1330 guard_loads.push_back(&inst);
1331
1332 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1333 if (isGuardVariableRef(store->getPointerOperand()))
1334 guard_stores.push_back(&inst);
1335 }
1336
1337 for (Instruction *inst : guard_loads)
1339
1340 for (Instruction *inst : guard_stores)
1341 ExciseGuardStore(inst);
1342
1343 return true;
1344}
1345
1346llvm::Error
1347IRForTarget::UnfoldConstant(Constant *old_constant,
1348 llvm::Function *llvm_function,
1349 FunctionValueCache &value_maker,
1350 FunctionValueCache &entry_instruction_finder,
1351 lldb_private::Stream &error_stream) {
1352 SmallVector<User *, 16> users;
1353
1354 // We do this because the use list might change, invalidating our iterator.
1355 // Much better to keep a work list ourselves.
1356 for (llvm::User *u : old_constant->users())
1357 users.push_back(u);
1358
1359 for (User *user : users) {
1360 if (Constant *constant = dyn_cast<Constant>(user)) {
1361 // synthesize a new non-constant equivalent of the constant
1362
1363 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1364 switch (constant_expr->getOpcode()) {
1365 default:
1366 return llvm::createStringErrorV(
1367 "unhandled constant expression type: \"{0}\".",
1368 PrintValue(constant_expr));
1369
1370 case Instruction::BitCast: {
1371 FunctionValueCache bit_cast_maker(
1372 [&value_maker, &entry_instruction_finder, old_constant,
1373 constant_expr](llvm::Function *function) -> llvm::Value * {
1374 // UnaryExpr
1375 // OperandList[0] is value
1376
1377 if (constant_expr->getOperand(0) != old_constant)
1378 return constant_expr;
1379
1380 return new BitCastInst(
1381 value_maker.GetValue(function), constant_expr->getType(),
1382 "",
1383 llvm::cast<Instruction>(
1384 entry_instruction_finder.GetValue(function))
1385 ->getIterator());
1386 });
1387
1388 if (auto err =
1389 UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1390 entry_instruction_finder, error_stream))
1391 return err;
1392 } break;
1393 case Instruction::GetElementPtr: {
1394 // GetElementPtrConstantExpr
1395 // OperandList[0] is base
1396 // OperandList[1]... are indices
1397
1398 FunctionValueCache get_element_pointer_maker(
1399 [&value_maker, &entry_instruction_finder, old_constant,
1400 constant_expr](llvm::Function *function) -> llvm::Value * {
1401 auto *gep = cast<llvm::GEPOperator>(constant_expr);
1402 Value *ptr = gep->getPointerOperand();
1403
1404 if (ptr == old_constant)
1405 ptr = value_maker.GetValue(function);
1406
1407 std::vector<Value *> index_vector;
1408 for (Value *operand : gep->indices()) {
1409 if (operand == old_constant)
1410 operand = value_maker.GetValue(function);
1411
1412 index_vector.push_back(operand);
1413 }
1414
1415 ArrayRef<Value *> indices(index_vector);
1416
1417 return GetElementPtrInst::Create(
1418 gep->getSourceElementType(), ptr, indices, "",
1419 llvm::cast<Instruction>(
1420 entry_instruction_finder.GetValue(function))
1421 ->getIterator());
1422 });
1423
1424 if (auto err = UnfoldConstant(constant_expr, llvm_function,
1425 get_element_pointer_maker,
1426 entry_instruction_finder, error_stream))
1427 return err;
1428 } break;
1429 }
1430 } else if (ConstantPtrAuth *constant_ptr_auth =
1431 dyn_cast<ConstantPtrAuth>(constant)) {
1432 // No need to handle ConstantPtrAuth users if old_constant is an address
1433 // discriminator.
1434 if (constant_ptr_auth->hasAddressDiscriminator() &&
1435 constant_ptr_auth->getAddrDiscriminator() == old_constant)
1436 continue;
1437
1438 return llvm::createStringErrorV("unhandled constant type \"{0}\".",
1439 PrintValue(constant_ptr_auth));
1440 } else {
1441 return llvm::createStringErrorV("unhandled constant type \"{0}\".",
1442 PrintValue(constant));
1443 }
1444 } else if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1445 if (llvm_function && inst->getParent()->getParent() != llvm_function)
1446 return llvm::createStringError(
1447 "capturing non-local variables in expressions is unsupported.");
1448
1449 inst->replaceUsesOfWith(
1450 old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1451 } else {
1452 return llvm::createStringErrorV("unhandled non-constant type: \"{0}\".",
1453 PrintValue(user));
1454 }
1455 }
1456
1457 if (!isa<GlobalValue>(old_constant)) {
1458 old_constant->destroyConstant();
1459 }
1460
1461 return llvm::Error::success();
1462}
1463
1464bool IRForTarget::ReplaceVariables(Function &llvm_function) {
1465 if (!m_resolve_vars)
1466 return true;
1467
1468 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1469
1470 m_decl_map->DoStructLayout();
1471
1472 LLDB_LOG(log, "Element arrangement:");
1473
1474 uint32_t num_elements;
1475 uint32_t element_index;
1476
1477 size_t size;
1478 lldb::offset_t alignment;
1479
1480 if (!m_decl_map->GetStructInfo(num_elements, size, alignment))
1481 return false;
1482
1483 Function::arg_iterator iter(llvm_function.arg_begin());
1484
1485 if (iter == llvm_function.arg_end()) {
1486 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes no "
1487 "arguments (should take at least a struct pointer)");
1488
1489 return false;
1490 }
1491
1492 Argument *argument = &*iter;
1493
1494 if (argument->getName() == "this") {
1495 ++iter;
1496
1497 if (iter == llvm_function.arg_end()) {
1498 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1499 "'this' argument (should take a struct pointer "
1500 "too)");
1501
1502 return false;
1503 }
1504
1505 argument = &*iter;
1506 } else if (argument->getName() == "self") {
1507 ++iter;
1508
1509 if (iter == llvm_function.arg_end()) {
1510 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1511 "'self' argument (should take '_cmd' and a struct "
1512 "pointer too)");
1513
1514 return false;
1515 }
1516
1517 if (iter->getName() != "_cmd") {
1518 m_error_stream.Format("Internal error [IRForTarget]: Wrapper takes '{0}' "
1519 "after 'self' argument (should take '_cmd')",
1520 iter->getName());
1521
1522 return false;
1523 }
1524
1525 ++iter;
1526
1527 if (iter == llvm_function.arg_end()) {
1528 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1529 "'self' and '_cmd' arguments (should take a struct "
1530 "pointer too)");
1531
1532 return false;
1533 }
1534
1535 argument = &*iter;
1536 }
1537
1538 if (argument->getName() != "$__lldb_arg") {
1539 m_error_stream.Format("Internal error [IRForTarget]: Wrapper takes an "
1540 "argument named '{0}' instead of the struct pointer",
1541 argument->getName());
1542
1543 return false;
1544 }
1545
1546 LLDB_LOG(log, "Arg: \"{0}\"", PrintValue(argument));
1547
1548 BasicBlock &entry_block(llvm_function.getEntryBlock());
1549 Instruction *FirstEntryInstruction(
1550 &*entry_block.getFirstNonPHIOrPseudoProbe());
1551
1552 if (!FirstEntryInstruction) {
1553 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the "
1554 "first instruction in the wrapper for use in "
1555 "rewriting");
1556
1557 return false;
1558 }
1559
1560 LLVMContext &context(m_module->getContext());
1561 IntegerType *offset_type(Type::getInt32Ty(context));
1562
1563 if (!offset_type) {
1564 m_error_stream.Printf(
1565 "Internal error [IRForTarget]: Couldn't produce an offset type");
1566
1567 return false;
1568 }
1569
1570 for (element_index = 0; element_index < num_elements; ++element_index) {
1571 const clang::NamedDecl *decl = nullptr;
1572 Value *value = nullptr;
1573 lldb::offset_t offset;
1575
1576 if (!m_decl_map->GetStructElement(decl, value, offset, name,
1577 element_index)) {
1578 m_error_stream.Printf(
1579 "Internal error [IRForTarget]: Structure information is incomplete");
1580
1581 return false;
1582 }
1583
1584 LLDB_LOG(log, " \"{0}\" (\"{1}\") placed at {2}", name,
1585 decl->getNameAsString(), offset);
1586
1587 if (value) {
1588 LLDB_LOG(log, " Replacing [{0}]", PrintValue(value));
1589
1590 FunctionValueCache body_result_maker(
1591 [this, name, offset_type, offset, argument,
1592 value](llvm::Function *function) -> llvm::Value * {
1593 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1594 // in cases where the result variable is an rvalue, we have to
1595 // synthesize a dereference of the appropriate structure entry in
1596 // order to produce the static variable that the AST thinks it is
1597 // accessing.
1598
1599 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1600 m_entry_instruction_finder.GetValue(function));
1601
1602 Type *int8Ty = Type::getInt8Ty(function->getContext());
1603 ConstantInt *offset_int(
1604 ConstantInt::get(offset_type, offset, true));
1605 GetElementPtrInst *get_element_ptr =
1606 GetElementPtrInst::Create(int8Ty, argument, offset_int, "",
1607 entry_instruction->getIterator());
1608
1609 if (name == m_result_name && !m_result_is_pointer) {
1610 LoadInst *load =
1611 new LoadInst(value->getType(), get_element_ptr, "",
1612 entry_instruction->getIterator());
1613
1614 return load;
1615 } else {
1616 return get_element_ptr;
1617 }
1618 });
1619
1620 if (Constant *constant = dyn_cast<Constant>(value)) {
1621 if (auto err =
1622 UnfoldConstant(constant, &llvm_function, body_result_maker,
1624 m_error_stream.Format("{0}", llvm::toString(std::move(err)));
1625 return false;
1626 }
1627 } else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1628 if (instruction->getParent()->getParent() != &llvm_function) {
1629 m_error_stream.PutCString("error: Capturing non-local variables in "
1630 "expressions is unsupported.\n");
1631 return false;
1632 }
1633 value->replaceAllUsesWith(
1634 body_result_maker.GetValue(instruction->getParent()->getParent()));
1635 } else {
1636 LLDB_LOG(log, "Unhandled non-constant type: \"{0}\"",
1637 PrintValue(value));
1638 return false;
1639 }
1640
1641 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1642 var->eraseFromParent();
1643 }
1644 }
1645
1646 LLDB_LOG(log, "Total structure [align {0}, size {1}]", (int64_t)alignment,
1647 (uint64_t)size);
1648
1649 return true;
1650}
1651
1652bool IRForTarget::runOnModule(Module &llvm_module) {
1653 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1654
1655 m_module = &llvm_module;
1656 m_target_data = &m_module->getDataLayout();
1657 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(),
1658 m_target_data->getPointerSizeInBits());
1659
1660 if (log) {
1661 std::string s;
1662 raw_string_ostream oss(s);
1663
1664 m_module->print(oss, nullptr);
1665
1666 LLDB_LOG(log, "Module as passed in to IRForTarget: \n\"{0}\"", s);
1667 }
1668
1669 Function *const main_function =
1670 m_func_name.IsEmpty() ? nullptr
1671 : m_module->getFunction(m_func_name.GetStringRef());
1672
1673 if (!m_func_name.IsEmpty() && !main_function) {
1674 LLDB_LOG(log, "Couldn't find \"{0}()\" in the module", m_func_name);
1675
1676 m_error_stream.Format("Internal error [IRForTarget]: Couldn't find wrapper "
1677 "'{0}' in the module",
1678 m_func_name);
1679
1680 return false;
1681 }
1682
1683 if (main_function) {
1684 if (!FixFunctionLinkage(*main_function)) {
1685 LLDB_LOG(log, "Couldn't fix the linkage for the function");
1686
1687 return false;
1688 }
1689 }
1690
1691 // Replace $__lldb_expr_result with a persistent variable.
1692 if (main_function) {
1693 if (!CreateResultVariable(*main_function)) {
1694 LLDB_LOG(log, "CreateResultVariable() failed");
1695
1696 // CreateResultVariable() reports its own errors, so we don't do so here
1697
1698 return false;
1699 }
1700 }
1701
1702 if (log && log->GetVerbose()) {
1703 std::string s;
1704 raw_string_ostream oss(s);
1705
1706 m_module->print(oss, nullptr);
1707
1708 LLDB_LOG(log, "Module after creating the result variable: \n\"{0}\"", s);
1709 }
1710
1711 for (llvm::Function &function : *m_module) {
1712 for (BasicBlock &bb : function) {
1713 if (!RemoveGuards(bb)) {
1714 LLDB_LOG(log, "RemoveGuards() failed");
1715
1716 // RemoveGuards() reports its own errors, so we don't do so here
1717
1718 return false;
1719 }
1720
1721 if (!RewritePersistentAllocs(bb)) {
1722 LLDB_LOG(log, "RewritePersistentAllocs() failed");
1723
1724 // RewritePersistentAllocs() reports its own errors, so we don't do so
1725 // here
1726
1727 return false;
1728 }
1729
1730 if (!RemoveCXAAtExit(bb)) {
1731 LLDB_LOG(log, "RemoveCXAAtExit() failed");
1732
1733 // RemoveCXAAtExit() reports its own errors, so we don't do so here
1734
1735 return false;
1736 }
1737 }
1738 }
1739
1740 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
1741 if (!RewriteObjCConstStrings()) {
1742 LLDB_LOG(log, "RewriteObjCConstStrings() failed");
1743
1744 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
1745
1746 return false;
1747 }
1748
1749 for (llvm::Function &function : *m_module) {
1750 for (llvm::BasicBlock &bb : function) {
1751 if (!RewriteObjCSelectors(bb)) {
1752 LLDB_LOG(log, "RewriteObjCSelectors() failed");
1753
1754 // RewriteObjCSelectors() reports its own errors, so we don't do so
1755 // here
1756
1757 return false;
1758 }
1759 }
1760 }
1761
1762 for (llvm::Function &function : *m_module) {
1763 for (BasicBlock &bb : function) {
1764 if (!ResolveCalls(bb)) {
1765 LLDB_LOG(log, "ResolveCalls() failed");
1766
1767 // ResolveCalls() reports its own errors, so we don't do so here
1768
1769 return false;
1770 }
1771 }
1772 }
1773
1774 // Run function-level passes that only make sense on the main function.
1775 if (main_function) {
1776 if (!ResolveExternals(*main_function)) {
1777 LLDB_LOG(log, "ResolveExternals() failed");
1778
1779 // ResolveExternals() reports its own errors, so we don't do so here
1780
1781 return false;
1782 }
1783
1784 if (!ReplaceVariables(*main_function)) {
1785 LLDB_LOG(log, "ReplaceVariables() failed");
1786
1787 // ReplaceVariables() reports its own errors, so we don't do so here
1788
1789 return false;
1790 }
1791 }
1792
1793 // Run architecture specific module-level passes.
1794 if (llvm::Error error =
1796 LLDB_LOG_ERROR(log, std::move(error),
1797 "InsertPointerSigningFixups() failed: {0}");
1798 return false;
1799 }
1800
1801 if (log && log->GetVerbose()) {
1802 std::string s;
1803 raw_string_ostream oss(s);
1804
1805 m_module->print(oss, nullptr);
1806
1807 LLDB_LOG(log, "Module after preparing for execution: \n\"{0}\"", s);
1808 }
1809
1810 return true;
1811}
static llvm::raw_ostream & error(Stream &strm)
static std::string PrintValue(const Value *value)
static bool isGuardVariableSymbol(llvm::StringRef mangled_symbol, bool check_ms_abi=true)
Returns true iff the mangled symbol is for a static guard variable.
static void ExciseGuardStore(Instruction *guard_store)
static llvm::Value * FindEntryInstruction(llvm::Function *function)
static bool IsObjCSelectorRef(Value *value)
SmallVector< Instruction *, 2 > InstrList
static bool isGuardVariableRef(Value *V)
static std::string PrintType(const llvm::Type *type)
static std::string PrintValue(const Value *value, bool truncate=false)
static std::string PrintType(const Type *type, bool truncate=false)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
FunctionValueCache(Maker const &maker)
llvm::Value * GetValue(llvm::Function *function)
std::function< llvm::Value *(llvm::Function *)> Maker
static llvm::Error UnfoldConstant(llvm::Constant *old_constant, llvm::Function *llvm_function, FunctionValueCache &value_maker, FunctionValueCache &entry_instruction_finder, lldb_private::Stream &error_stream)
UnfoldConstant operates on a constant [Old] which has just been replaced with a value [New].
lldb_private::ConstString m_func_name
The name of the function to translate.
IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Stream &error_stream, lldb_private::ExecutionPolicy execution_policy, const char *func_name="$__lldb_expr")
Constructor.
bool MaybeHandleVariable(llvm::Value *value)
A function-level pass to find all external variables and functions used in the IR.
bool FixFunctionLinkage(llvm::Function &llvm_function)
Ensures that the current function's linkage is set to external.
lldb_private::IRExecutionUnit & m_execution_unit
The execution unit containing the IR being created.
bool CreateResultVariable(llvm::Function &llvm_function)
The top-level pass implementation.
llvm::Module * m_module
The module being processed, or NULL if that has not been determined yet.
bool HandleSymbol(llvm::Value *symbol)
Handle a single externally-defined symbol.
bool RewriteObjCConstStrings()
The top-level pass implementation.
bool ResolveCalls(llvm::BasicBlock &basic_block)
Resolve variable references in calls to external functions.
bool m_result_is_pointer
True if the function's result in the AST is a pointer (see comments in ASTResultSynthesizer::Synthesi...
bool RewriteObjCConstString(llvm::GlobalVariable *NSStr, llvm::GlobalVariable *CStr)
A module-level pass to find Objective-C constant strings and transform them to calls to CFStringCreat...
bool RemoveGuards(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::Stream & m_error_stream
The stream on which errors should be printed.
bool HandleObjCClass(llvm::Value *classlist_reference)
Handle a single externally-defined Objective-C class.
bool m_resolve_vars
True if external variable references and persistent variable references should be resolved.
static clang::NamedDecl * DeclForGlobal(const llvm::GlobalValue *global_val, llvm::Module *module)
A function-level pass to take the generated global value $__lldb_expr_result and make it into a persi...
lldb_private::TypeFromParser m_result_type
The type of the result variable.
llvm::FunctionCallee m_CFStringCreateWithBytes
The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type.
bool MaybeHandleCallArguments(llvm::CallInst *call_inst)
Handle all the arguments to a function call.
lldb_private::ExecutionPolicy m_policy
bool runOnModule(llvm::Module &llvm_module)
Run this IR transformer on a single module.
bool RewriteObjCSelectors(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::ConstString m_result_name
The name of the result variable ($0, $1, ...)
lldb_private::ClangExpressionDeclMap * m_decl_map
The DeclMap containing the Decls.
bool RemoveCXAAtExit(llvm::BasicBlock &basic_block)
Remove calls to __cxa_atexit, which should never be generated by expressions.
bool RewritePersistentAllocs(llvm::BasicBlock &basic_block)
The top-level pass implementation.
bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc)
A basic block-level pass to find all newly-declared persistent variables and register them with the C...
void TurnGuardLoadIntoZero(llvm::Instruction *guard_load)
A basic block-level pass to excise guard variables from the code.
FunctionValueCache m_entry_instruction_finder
const llvm::DataLayout * m_target_data
The target data for the module being processed, or nullptr if there is no module.
llvm::FunctionCallee m_sel_registerName
The address of the function sel_registerName, cast to the appropriate function pointer type.
llvm::IntegerType * m_intptr_ty
The type of an integer large enough to hold a pointer.
bool RewriteObjCSelector(llvm::Instruction *selector_load)
A basic block-level pass to find all Objective-C method calls and rewrite them to use sel_registerNam...
bool ResolveExternals(llvm::Function &llvm_function)
The top-level pass implementation.
bool ReplaceVariables(llvm::Function &llvm_function)
A function-level pass to make all external variable references point at the correct offsets from the ...
"lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are defined in LLDB's debug in...
Generic representation of a type in a programming language.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
std::optional< size_t > GetTypeBitAlign(ExecutionContextScope *exe_scope) const
A uniqued constant string class.
Definition ConstString.h:40
"lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT- compiled code for a module.
bool GetVerbose() const
Definition Log.cpp:329
const char * GetData() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
#define LLDB_INVALID_ADDRESS
Error InjectPointerSigningFixupCode(llvm::Module &M, ExecutionPolicy execution_policy)
TaggedASTType< 0 > TypeFromParser
ExecutionPolicy
Expression execution policies.
uint64_t offset_t
Definition lldb-types.h:86
@ eSymbolTypeObjCClass
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
static clang::QualType GetQualType(const CompilerType &ct)
Definition ClangUtil.cpp:36