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