1use std::borrow::Cow;
2use std::fmt::{self, Write};
3use std::hash::{Hash, Hasher};
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::{iter, ptr};
7
8use libc::{c_char, c_longlong, c_uint};
9use rustc_abi::{Align, Size};
10use rustc_codegen_ssa::debuginfo::type_names::{VTableNameKind, cpp_like_debuginfo};
11use rustc_codegen_ssa::traits::*;
12use rustc_hir::def::{CtorKind, DefKind};
13use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14use rustc_middle::bug;
15use rustc_middle::ty::layout::{
16 HasTypingEnv, LayoutOf, TyAndLayout, WIDE_PTR_ADDR, WIDE_PTR_EXTRA,
17};
18use rustc_middle::ty::{
19 self, AdtKind, CoroutineArgsExt, ExistentialTraitRef, Instance, Ty, TyCtxt, Visibility,
20};
21use rustc_session::config::{self, DebugInfo, Lto};
22use rustc_span::{DUMMY_SP, FileName, FileNameDisplayPreference, SourceFile, Symbol, hygiene};
23use rustc_symbol_mangling::typeid_for_trait_ref;
24use rustc_target::spec::DebuginfoKind;
25use smallvec::smallvec;
26use tracing::{debug, instrument};
27
28pub(crate) use self::type_map::TypeMap;
29use self::type_map::{DINodeCreationResult, Stub, UniqueTypeId};
30use super::CodegenUnitDebugContext;
31use super::namespace::mangled_name_of_instance;
32use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
33use super::utils::{
34 DIB, create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit,
35};
36use crate::common::{AsCCharPtr, CodegenCx};
37use crate::debuginfo::dwarf_const;
38use crate::debuginfo::metadata::type_map::build_type_with_children;
39use crate::debuginfo::utils::{WidePtrKind, wide_pointer_kind};
40use crate::llvm;
41use crate::llvm::debuginfo::{
42 DIBasicType, DIBuilder, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock,
43 DIScope, DIType, DebugEmissionKind, DebugNameTableKind,
44};
45use crate::value::Value;
46
47impl PartialEq for llvm::Metadata {
48 fn eq(&self, other: &Self) -> bool {
49 ptr::eq(self, other)
50 }
51}
52
53impl Eq for llvm::Metadata {}
54
55impl Hash for llvm::Metadata {
56 fn hash<H: Hasher>(&self, hasher: &mut H) {
57 (self as *const Self).hash(hasher);
58 }
59}
60
61impl fmt::Debug for llvm::Metadata {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 (self as *const Self).fmt(f)
64 }
65}
66
67pub(super) const UNKNOWN_LINE_NUMBER: c_uint = 0;
68pub(super) const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
69
70const NO_SCOPE_METADATA: Option<&DIScope> = None;
71const NO_GENERICS: for<'ll> fn(&CodegenCx<'ll, '_>) -> SmallVec<Option<&'ll DIType>> =
73 |_| SmallVec::new();
74
75type SmallVec<T> = smallvec::SmallVec<[T; 16]>;
78
79mod enums;
80mod type_map;
81
82macro_rules! return_if_di_node_created_in_meantime {
85 ($cx: expr, $unique_type_id: expr) => {
86 if let Some(di_node) = debug_context($cx).type_map.di_node_for_unique_id($unique_type_id) {
87 return DINodeCreationResult::new(di_node, true);
88 }
89 };
90}
91
92#[inline]
94fn size_and_align_of(ty_and_layout: TyAndLayout<'_>) -> (Size, Align) {
95 (ty_and_layout.size, ty_and_layout.align.abi)
96}
97
98fn build_fixed_size_array_di_node<'ll, 'tcx>(
101 cx: &CodegenCx<'ll, 'tcx>,
102 unique_type_id: UniqueTypeId<'tcx>,
103 array_type: Ty<'tcx>,
104) -> DINodeCreationResult<'ll> {
105 let ty::Array(element_type, len) = array_type.kind() else {
106 bug!("build_fixed_size_array_di_node() called with non-ty::Array type `{:?}`", array_type)
107 };
108
109 let element_type_di_node = type_di_node(cx, *element_type);
110
111 return_if_di_node_created_in_meantime!(cx, unique_type_id);
112
113 let (size, align) = cx.size_and_align_of(array_type);
114
115 let upper_bound = len
116 .try_to_target_usize(cx.tcx)
117 .expect("expected monomorphic const in codegen") as c_longlong;
118
119 let subrange =
120 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
121
122 let subscripts = create_DIArray(DIB(cx), &[subrange]);
123 let di_node = unsafe {
124 llvm::LLVMRustDIBuilderCreateArrayType(
125 DIB(cx),
126 size.bits(),
127 align.bits() as u32,
128 element_type_di_node,
129 subscripts,
130 )
131 };
132
133 DINodeCreationResult::new(di_node, false)
134}
135
136fn build_pointer_or_reference_di_node<'ll, 'tcx>(
145 cx: &CodegenCx<'ll, 'tcx>,
146 ptr_type: Ty<'tcx>,
147 pointee_type: Ty<'tcx>,
148 unique_type_id: UniqueTypeId<'tcx>,
149) -> DINodeCreationResult<'ll> {
150 assert_eq!(
153 cx.size_and_align_of(ptr_type),
154 cx.size_and_align_of(Ty::new_mut_ptr(cx.tcx, pointee_type))
155 );
156
157 let pointee_type_di_node = type_di_node(cx, pointee_type);
158
159 return_if_di_node_created_in_meantime!(cx, unique_type_id);
160
161 let data_layout = &cx.tcx.data_layout;
162 let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
163
164 match wide_pointer_kind(cx, pointee_type) {
165 None => {
166 assert_eq!(
168 (data_layout.pointer_size, data_layout.pointer_align.abi),
169 cx.size_and_align_of(ptr_type),
170 "ptr_type={ptr_type}, pointee_type={pointee_type}",
171 );
172
173 let di_node = unsafe {
174 llvm::LLVMRustDIBuilderCreatePointerType(
175 DIB(cx),
176 pointee_type_di_node,
177 data_layout.pointer_size.bits(),
178 data_layout.pointer_align.abi.bits() as u32,
179 0, ptr_type_debuginfo_name.as_c_char_ptr(),
181 ptr_type_debuginfo_name.len(),
182 )
183 };
184
185 DINodeCreationResult { di_node, already_stored_in_typemap: false }
186 }
187 Some(wide_pointer_kind) => {
188 type_map::build_type_with_children(
189 cx,
190 type_map::stub(
191 cx,
192 Stub::Struct,
193 unique_type_id,
194 &ptr_type_debuginfo_name,
195 None,
196 cx.size_and_align_of(ptr_type),
197 NO_SCOPE_METADATA,
198 DIFlags::FlagZero,
199 ),
200 |cx, owner| {
201 let layout_type = if ptr_type.is_box() {
209 Ty::new_mut_ptr(cx.tcx, pointee_type)
213 } else {
214 ptr_type
215 };
216
217 let layout = cx.layout_of(layout_type);
218 let addr_field = layout.field(cx, WIDE_PTR_ADDR);
219 let extra_field = layout.field(cx, WIDE_PTR_EXTRA);
220
221 let (addr_field_name, extra_field_name) = match wide_pointer_kind {
222 WidePtrKind::Dyn => ("pointer", "vtable"),
223 WidePtrKind::Slice => ("data_ptr", "length"),
224 };
225
226 assert_eq!(WIDE_PTR_ADDR, 0);
227 assert_eq!(WIDE_PTR_EXTRA, 1);
228
229 let data_ptr_type_di_node = unsafe {
232 llvm::LLVMRustDIBuilderCreatePointerType(
233 DIB(cx),
234 pointee_type_di_node,
235 addr_field.size.bits(),
236 addr_field.align.abi.bits() as u32,
237 0, std::ptr::null(),
239 0,
240 )
241 };
242
243 smallvec![
244 build_field_di_node(
245 cx,
246 owner,
247 addr_field_name,
248 addr_field,
249 layout.fields.offset(WIDE_PTR_ADDR),
250 DIFlags::FlagZero,
251 data_ptr_type_di_node,
252 None,
253 ),
254 build_field_di_node(
255 cx,
256 owner,
257 extra_field_name,
258 extra_field,
259 layout.fields.offset(WIDE_PTR_EXTRA),
260 DIFlags::FlagZero,
261 type_di_node(cx, extra_field.ty),
262 None,
263 ),
264 ]
265 },
266 NO_GENERICS,
267 )
268 }
269 }
270}
271
272fn build_subroutine_type_di_node<'ll, 'tcx>(
273 cx: &CodegenCx<'ll, 'tcx>,
274 unique_type_id: UniqueTypeId<'tcx>,
275) -> DINodeCreationResult<'ll> {
276 debug_context(cx)
289 .type_map
290 .unique_id_to_di_node
291 .borrow_mut()
292 .insert(unique_type_id, recursion_marker_type_di_node(cx));
293
294 let fn_ty = unique_type_id.expect_ty();
295 let signature =
296 cx.tcx.normalize_erasing_late_bound_regions(cx.typing_env(), fn_ty.fn_sig(cx.tcx));
297
298 let signature_di_nodes: SmallVec<_> = iter::once(
299 match signature.output().kind() {
301 ty::Tuple(tys) if tys.is_empty() => {
302 None
304 }
305 _ => Some(type_di_node(cx, signature.output())),
306 },
307 )
308 .chain(
309 signature.inputs().iter().map(|&argument_type| Some(type_di_node(cx, argument_type))),
311 )
312 .collect();
313
314 debug_context(cx).type_map.unique_id_to_di_node.borrow_mut().remove(&unique_type_id);
315
316 let fn_di_node = create_subroutine_type(cx, create_DIArray(DIB(cx), &signature_di_nodes[..]));
317
318 let name = compute_debuginfo_type_name(cx.tcx, fn_ty, false);
320 let (size, align) = match fn_ty.kind() {
321 ty::FnDef(..) => (Size::ZERO, Align::ONE),
322 ty::FnPtr(..) => (cx.tcx.data_layout.pointer_size, cx.tcx.data_layout.pointer_align.abi),
323 _ => unreachable!(),
324 };
325 let di_node = unsafe {
326 llvm::LLVMRustDIBuilderCreatePointerType(
327 DIB(cx),
328 fn_di_node,
329 size.bits(),
330 align.bits() as u32,
331 0, name.as_c_char_ptr(),
333 name.len(),
334 )
335 };
336
337 DINodeCreationResult::new(di_node, false)
338}
339
340pub(super) fn create_subroutine_type<'ll>(
341 cx: &CodegenCx<'ll, '_>,
342 signature: &'ll DICompositeType,
343) -> &'ll DICompositeType {
344 unsafe { llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), signature) }
345}
346
347fn build_dyn_type_di_node<'ll, 'tcx>(
350 cx: &CodegenCx<'ll, 'tcx>,
351 dyn_type: Ty<'tcx>,
352 unique_type_id: UniqueTypeId<'tcx>,
353) -> DINodeCreationResult<'ll> {
354 if let ty::Dynamic(..) = dyn_type.kind() {
355 let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
356 type_map::build_type_with_children(
357 cx,
358 type_map::stub(
359 cx,
360 Stub::Struct,
361 unique_type_id,
362 &type_name,
363 None,
364 cx.size_and_align_of(dyn_type),
365 NO_SCOPE_METADATA,
366 DIFlags::FlagZero,
367 ),
368 |_, _| smallvec![],
369 NO_GENERICS,
370 )
371 } else {
372 bug!(
373 "Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {:?} instead.",
374 dyn_type
375 )
376 }
377}
378
379fn build_slice_type_di_node<'ll, 'tcx>(
397 cx: &CodegenCx<'ll, 'tcx>,
398 slice_type: Ty<'tcx>,
399 unique_type_id: UniqueTypeId<'tcx>,
400) -> DINodeCreationResult<'ll> {
401 let element_type = match slice_type.kind() {
402 ty::Slice(element_type) => *element_type,
403 ty::Str => cx.tcx.types.u8,
404 _ => {
405 bug!(
406 "Only ty::Slice is valid for build_slice_type_di_node(). Found {:?} instead.",
407 slice_type
408 )
409 }
410 };
411
412 let element_type_di_node = type_di_node(cx, element_type);
413 return_if_di_node_created_in_meantime!(cx, unique_type_id);
414 DINodeCreationResult { di_node: element_type_di_node, already_stored_in_typemap: false }
415}
416
417pub(crate) fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
422 let unique_type_id = UniqueTypeId::for_ty(cx.tcx, t);
423
424 if let Some(existing_di_node) = debug_context(cx).type_map.di_node_for_unique_id(unique_type_id)
425 {
426 return existing_di_node;
427 }
428
429 debug!("type_di_node: {:?} kind: {:?}", t, t.kind());
430
431 let DINodeCreationResult { di_node, already_stored_in_typemap } = match *t.kind() {
432 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
433 build_basic_type_di_node(cx, t)
434 }
435 ty::Tuple(elements) if elements.is_empty() => build_basic_type_di_node(cx, t),
436 ty::Array(..) => build_fixed_size_array_di_node(cx, unique_type_id, t),
437 ty::Slice(_) | ty::Str => build_slice_type_di_node(cx, t, unique_type_id),
438 ty::Dynamic(..) => build_dyn_type_di_node(cx, t, unique_type_id),
439 ty::Foreign(..) => build_foreign_type_di_node(cx, t, unique_type_id),
440 ty::RawPtr(pointee_type, _) | ty::Ref(_, pointee_type, _) => {
441 build_pointer_or_reference_di_node(cx, t, pointee_type, unique_type_id)
442 }
443 ty::Adt(def, args)
447 if def.is_box()
448 && args.get(1).is_none_or(|arg| cx.layout_of(arg.expect_ty()).is_1zst()) =>
449 {
450 build_pointer_or_reference_di_node(cx, t, t.expect_boxed_ty(), unique_type_id)
451 }
452 ty::FnDef(..) | ty::FnPtr(..) => build_subroutine_type_di_node(cx, unique_type_id),
453 ty::Closure(..) => build_closure_env_di_node(cx, unique_type_id),
454 ty::CoroutineClosure(..) => build_closure_env_di_node(cx, unique_type_id),
455 ty::Coroutine(..) => enums::build_coroutine_di_node(cx, unique_type_id),
456 ty::Adt(def, ..) => match def.adt_kind() {
457 AdtKind::Struct => build_struct_type_di_node(cx, unique_type_id),
458 AdtKind::Union => build_union_type_di_node(cx, unique_type_id),
459 AdtKind::Enum => enums::build_enum_type_di_node(cx, unique_type_id),
460 },
461 ty::Tuple(_) => build_tuple_type_di_node(cx, unique_type_id),
462 _ => bug!("debuginfo: unexpected type in type_di_node(): {:?}", t),
463 };
464
465 {
466 if already_stored_in_typemap {
467 let di_node_for_uid =
469 match debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
470 Some(di_node) => di_node,
471 None => {
472 bug!(
473 "expected type debuginfo node for unique \
474 type ID '{:?}' to already be in \
475 the `debuginfo::TypeMap` but it \
476 was not.",
477 unique_type_id,
478 );
479 }
480 };
481
482 assert_eq!(di_node_for_uid as *const _, di_node as *const _);
483 } else {
484 debug_context(cx).type_map.insert(unique_type_id, di_node);
485 }
486 }
487
488 di_node
489}
490
491fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType {
493 *debug_context(cx).recursion_marker_type.get_or_init(move || {
494 create_basic_type(
505 cx,
506 "<recur_type>",
507 cx.tcx.data_layout.pointer_size,
508 dwarf_const::DW_ATE_unsigned,
509 )
510 })
511}
512
513fn hex_encode(data: &[u8]) -> String {
514 let mut hex_string = String::with_capacity(data.len() * 2);
515 for byte in data.iter() {
516 write!(&mut hex_string, "{byte:02x}").unwrap();
517 }
518 hex_string
519}
520
521pub(crate) fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
522 let cache_key = Some((source_file.stable_id, source_file.src_hash));
523 return debug_context(cx)
524 .created_files
525 .borrow_mut()
526 .entry(cache_key)
527 .or_insert_with(|| alloc_new_file_metadata(cx, source_file));
528
529 #[instrument(skip(cx, source_file), level = "debug")]
530 fn alloc_new_file_metadata<'ll>(
531 cx: &CodegenCx<'ll, '_>,
532 source_file: &SourceFile,
533 ) -> &'ll DIFile {
534 debug!(?source_file.name);
535
536 let filename_display_preference =
537 cx.sess().filename_display_preference(RemapPathScopeComponents::DEBUGINFO);
538
539 use rustc_session::config::RemapPathScopeComponents;
540 let (directory, file_name) = match &source_file.name {
541 FileName::Real(filename) => {
542 let working_directory = &cx.sess().opts.working_dir;
543 debug!(?working_directory);
544
545 if filename_display_preference == FileNameDisplayPreference::Remapped {
546 let filename = cx
547 .sess()
548 .source_map()
549 .path_mapping()
550 .to_embeddable_absolute_path(filename.clone(), working_directory);
551
552 let abs_path = filename.remapped_path_if_available();
554 debug!(?abs_path);
555
556 if let Ok(rel_path) =
557 abs_path.strip_prefix(working_directory.remapped_path_if_available())
558 {
559 (
575 working_directory.to_string_lossy(FileNameDisplayPreference::Remapped),
576 rel_path.to_string_lossy().into_owned(),
577 )
578 } else {
579 ("".into(), abs_path.to_string_lossy().into_owned())
580 }
581 } else {
582 let working_directory = working_directory.local_path_if_available();
583 let filename = filename.local_path_if_available();
584
585 debug!(?working_directory, ?filename);
586
587 let abs_path: Cow<'_, Path> = if filename.is_absolute() {
588 filename.into()
589 } else {
590 let mut p = PathBuf::new();
591 p.push(working_directory);
592 p.push(filename);
593 p.into()
594 };
595
596 if let Ok(rel_path) = abs_path.strip_prefix(working_directory) {
597 (
598 working_directory.to_string_lossy(),
599 rel_path.to_string_lossy().into_owned(),
600 )
601 } else {
602 ("".into(), abs_path.to_string_lossy().into_owned())
603 }
604 }
605 }
606 other => {
607 debug!(?other);
608 ("".into(), other.display(filename_display_preference).to_string())
609 }
610 };
611
612 let hash_kind = match source_file.src_hash.kind {
613 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
614 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
615 rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
616 rustc_span::SourceFileHashAlgorithm::Blake3 => llvm::ChecksumKind::None,
617 };
618 let hash_value = hex_encode(source_file.src_hash.hash_bytes());
619
620 let source =
621 cx.sess().opts.unstable_opts.embed_source.then_some(()).and(source_file.src.as_ref());
622
623 create_file(DIB(cx), &file_name, &directory, &hash_value, hash_kind, source)
624 }
625}
626
627fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
628 debug_context(cx).created_files.borrow_mut().entry(None).or_insert_with(|| {
629 create_file(DIB(cx), "<unknown>", "", "", llvm::ChecksumKind::None, None)
630 })
631}
632
633fn create_file<'ll>(
634 builder: &DIBuilder<'ll>,
635 file_name: &str,
636 directory: &str,
637 hash_value: &str,
638 hash_kind: llvm::ChecksumKind,
639 source: Option<&Arc<String>>,
640) -> &'ll DIFile {
641 unsafe {
642 llvm::LLVMRustDIBuilderCreateFile(
643 builder,
644 file_name.as_c_char_ptr(),
645 file_name.len(),
646 directory.as_c_char_ptr(),
647 directory.len(),
648 hash_kind,
649 hash_value.as_c_char_ptr(),
650 hash_value.len(),
651 source.map_or(ptr::null(), |x| x.as_c_char_ptr()),
652 source.map_or(0, |x| x.len()),
653 )
654 }
655}
656
657trait MsvcBasicName {
658 fn msvc_basic_name(self) -> &'static str;
659}
660
661impl MsvcBasicName for ty::IntTy {
662 fn msvc_basic_name(self) -> &'static str {
663 match self {
664 ty::IntTy::Isize => "ptrdiff_t",
665 ty::IntTy::I8 => "__int8",
666 ty::IntTy::I16 => "__int16",
667 ty::IntTy::I32 => "__int32",
668 ty::IntTy::I64 => "__int64",
669 ty::IntTy::I128 => "__int128",
670 }
671 }
672}
673
674impl MsvcBasicName for ty::UintTy {
675 fn msvc_basic_name(self) -> &'static str {
676 match self {
677 ty::UintTy::Usize => "size_t",
678 ty::UintTy::U8 => "unsigned __int8",
679 ty::UintTy::U16 => "unsigned __int16",
680 ty::UintTy::U32 => "unsigned __int32",
681 ty::UintTy::U64 => "unsigned __int64",
682 ty::UintTy::U128 => "unsigned __int128",
683 }
684 }
685}
686
687impl MsvcBasicName for ty::FloatTy {
688 fn msvc_basic_name(self) -> &'static str {
689 match self {
692 ty::FloatTy::F16 => {
693 bug!("`f16` should have been handled in `build_basic_type_di_node`")
694 }
695 ty::FloatTy::F32 => "float",
696 ty::FloatTy::F64 => "double",
697 ty::FloatTy::F128 => "fp128",
698 }
699 }
700}
701
702fn build_cpp_f16_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> DINodeCreationResult<'ll> {
703 let float_ty = cx.tcx.types.f16;
706 let bits_ty = cx.tcx.types.u16;
707 let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
708 match float_ty.kind() {
709 ty::Adt(def, _) => Some(file_metadata_from_def_id(cx, Some(def.did()))),
710 _ => None,
711 }
712 } else {
713 None
714 };
715 type_map::build_type_with_children(
716 cx,
717 type_map::stub(
718 cx,
719 Stub::Struct,
720 UniqueTypeId::for_ty(cx.tcx, float_ty),
721 "f16",
722 def_location,
723 cx.size_and_align_of(float_ty),
724 NO_SCOPE_METADATA,
725 DIFlags::FlagZero,
726 ),
727 |cx, float_di_node| {
729 let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
730 match bits_ty.kind() {
731 ty::Adt(def, _) => Some(def.did()),
732 _ => None,
733 }
734 } else {
735 None
736 };
737 smallvec![build_field_di_node(
738 cx,
739 float_di_node,
740 "bits",
741 cx.layout_of(bits_ty),
742 Size::ZERO,
743 DIFlags::FlagZero,
744 type_di_node(cx, bits_ty),
745 def_id,
746 )]
747 },
748 NO_GENERICS,
749 )
750}
751
752fn build_basic_type_di_node<'ll, 'tcx>(
753 cx: &CodegenCx<'ll, 'tcx>,
754 t: Ty<'tcx>,
755) -> DINodeCreationResult<'ll> {
756 debug!("build_basic_type_di_node: {:?}", t);
757
758 let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
761
762 use dwarf_const::{DW_ATE_UTF, DW_ATE_boolean, DW_ATE_float, DW_ATE_signed, DW_ATE_unsigned};
763
764 let (name, encoding) = match t.kind() {
765 ty::Never => ("!", DW_ATE_unsigned),
766 ty::Tuple(elements) if elements.is_empty() => {
767 if cpp_like_debuginfo {
768 return build_tuple_type_di_node(cx, UniqueTypeId::for_ty(cx.tcx, t));
769 } else {
770 ("()", DW_ATE_unsigned)
771 }
772 }
773 ty::Bool => ("bool", DW_ATE_boolean),
774 ty::Char => ("char", DW_ATE_UTF),
775 ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
776 ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
777 ty::Float(ty::FloatTy::F16) if cpp_like_debuginfo => {
778 return build_cpp_f16_di_node(cx);
779 }
780 ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
781 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
782 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
783 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
784 _ => bug!("debuginfo::build_basic_type_di_node - `t` is invalid type"),
785 };
786
787 let ty_di_node = create_basic_type(cx, name, cx.size_of(t), encoding);
788
789 if !cpp_like_debuginfo {
790 return DINodeCreationResult::new(ty_di_node, false);
791 }
792
793 let typedef_name = match t.kind() {
794 ty::Int(int_ty) => int_ty.name_str(),
795 ty::Uint(uint_ty) => uint_ty.name_str(),
796 ty::Float(float_ty) => float_ty.name_str(),
797 _ => return DINodeCreationResult::new(ty_di_node, false),
798 };
799
800 let typedef_di_node = unsafe {
801 llvm::LLVMRustDIBuilderCreateTypedef(
802 DIB(cx),
803 ty_di_node,
804 typedef_name.as_c_char_ptr(),
805 typedef_name.len(),
806 unknown_file_metadata(cx),
807 0,
808 None,
809 )
810 };
811
812 DINodeCreationResult::new(typedef_di_node, false)
813}
814
815fn create_basic_type<'ll, 'tcx>(
816 cx: &CodegenCx<'ll, 'tcx>,
817 name: &str,
818 size: Size,
819 encoding: u32,
820) -> &'ll DIBasicType {
821 unsafe {
822 llvm::LLVMRustDIBuilderCreateBasicType(
823 DIB(cx),
824 name.as_c_char_ptr(),
825 name.len(),
826 size.bits(),
827 encoding,
828 )
829 }
830}
831
832fn build_foreign_type_di_node<'ll, 'tcx>(
833 cx: &CodegenCx<'ll, 'tcx>,
834 t: Ty<'tcx>,
835 unique_type_id: UniqueTypeId<'tcx>,
836) -> DINodeCreationResult<'ll> {
837 debug!("build_foreign_type_di_node: {:?}", t);
838
839 let &ty::Foreign(def_id) = unique_type_id.expect_ty().kind() else {
840 bug!(
841 "build_foreign_type_di_node() called with unexpected type: {:?}",
842 unique_type_id.expect_ty()
843 );
844 };
845
846 build_type_with_children(
847 cx,
848 type_map::stub(
849 cx,
850 Stub::Struct,
851 unique_type_id,
852 &compute_debuginfo_type_name(cx.tcx, t, false),
853 None,
854 cx.size_and_align_of(t),
855 Some(get_namespace_for_item(cx, def_id)),
856 DIFlags::FlagZero,
857 ),
858 |_, _| smallvec![],
859 NO_GENERICS,
860 )
861}
862
863pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
864 tcx: TyCtxt<'tcx>,
865 codegen_unit_name: &str,
866 debug_context: &CodegenUnitDebugContext<'ll, 'tcx>,
867) -> &'ll DIDescriptor {
868 use rustc_session::RemapFileNameExt;
869 use rustc_session::config::RemapPathScopeComponents;
870 let mut name_in_debuginfo = tcx
871 .sess
872 .local_crate_source_file()
873 .map(|src| src.for_scope(&tcx.sess, RemapPathScopeComponents::DEBUGINFO).to_path_buf())
874 .unwrap_or_else(|| PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()));
875
876 name_in_debuginfo.push("@");
894 name_in_debuginfo.push(codegen_unit_name);
895
896 debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo);
897 let rustc_producer = format!("rustc version {}", tcx.sess.cfg_version);
898 let producer = format!("clang LLVM ({rustc_producer})");
900
901 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
902 let work_dir = tcx
903 .sess
904 .opts
905 .working_dir
906 .for_scope(tcx.sess, RemapPathScopeComponents::DEBUGINFO)
907 .to_string_lossy();
908 let output_filenames = tcx.output_filenames(());
909 let split_name = if tcx.sess.target_can_use_split_dwarf()
910 && let Some(f) = output_filenames.split_dwarf_path(
911 tcx.sess.split_debuginfo(),
912 tcx.sess.opts.unstable_opts.split_dwarf_kind,
913 codegen_unit_name,
914 tcx.sess.invocation_temp.as_deref(),
915 ) {
916 Some(tcx.sess.source_map().path_mapping().to_real_filename(f))
918 } else {
919 None
920 };
921 let split_name = split_name
922 .as_ref()
923 .map(|f| f.for_scope(tcx.sess, RemapPathScopeComponents::DEBUGINFO).to_string_lossy())
924 .unwrap_or_default();
925 let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
926
927 let dwarf_version = tcx.sess.dwarf_version();
928 let is_dwarf_kind =
929 matches!(tcx.sess.target.debuginfo_kind, DebuginfoKind::Dwarf | DebuginfoKind::DwarfDsym);
930 let debug_name_table_kind = if is_dwarf_kind && dwarf_version <= 4 {
932 DebugNameTableKind::None
933 } else {
934 DebugNameTableKind::Default
935 };
936
937 unsafe {
938 let compile_unit_file = create_file(
939 debug_context.builder.as_ref(),
940 &name_in_debuginfo,
941 &work_dir,
942 "",
943 llvm::ChecksumKind::None,
944 None,
945 );
946
947 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
948 debug_context.builder.as_ref(),
949 dwarf_const::DW_LANG_Rust,
950 compile_unit_file,
951 producer.as_c_char_ptr(),
952 producer.len(),
953 tcx.sess.opts.optimize != config::OptLevel::No,
954 c"".as_ptr(),
955 0,
956 split_name.as_c_char_ptr(),
960 split_name.len(),
961 kind,
962 0,
963 tcx.sess.opts.unstable_opts.split_dwarf_inlining,
964 debug_name_table_kind,
965 );
966
967 return unit_metadata;
968 };
969}
970
971fn build_field_di_node<'ll, 'tcx>(
973 cx: &CodegenCx<'ll, 'tcx>,
974 owner: &'ll DIScope,
975 name: &str,
976 layout: TyAndLayout<'tcx>,
977 offset: Size,
978 flags: DIFlags,
979 type_di_node: &'ll DIType,
980 def_id: Option<DefId>,
981) -> &'ll DIType {
982 let (file_metadata, line_number) = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers
983 {
984 file_metadata_from_def_id(cx, def_id)
985 } else {
986 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
987 };
988 create_member_type(
989 cx,
990 owner,
991 name,
992 file_metadata,
993 line_number,
994 layout,
995 offset,
996 flags,
997 type_di_node,
998 )
999}
1000
1001fn create_member_type<'ll, 'tcx>(
1002 cx: &CodegenCx<'ll, 'tcx>,
1003 owner: &'ll DIScope,
1004 name: &str,
1005 file_metadata: &'ll DIType,
1006 line_number: u32,
1007 layout: TyAndLayout<'tcx>,
1008 offset: Size,
1009 flags: DIFlags,
1010 type_di_node: &'ll DIType,
1011) -> &'ll DIType {
1012 unsafe {
1013 llvm::LLVMRustDIBuilderCreateMemberType(
1014 DIB(cx),
1015 owner,
1016 name.as_c_char_ptr(),
1017 name.len(),
1018 file_metadata,
1019 line_number,
1020 layout.size.bits(),
1021 layout.align.abi.bits() as u32,
1022 offset.bits(),
1023 flags,
1024 type_di_node,
1025 )
1026 }
1027}
1028
1029fn visibility_di_flags<'ll, 'tcx>(
1035 cx: &CodegenCx<'ll, 'tcx>,
1036 did: DefId,
1037 type_did: DefId,
1038) -> DIFlags {
1039 let parent_did = cx.tcx.parent(type_did);
1040 let visibility = cx.tcx.visibility(did);
1041 match visibility {
1042 Visibility::Public => DIFlags::FlagPublic,
1043 Visibility::Restricted(did) if did == parent_did => DIFlags::FlagPrivate,
1045 Visibility::Restricted(..) => DIFlags::FlagProtected,
1047 }
1048}
1049
1050fn build_struct_type_di_node<'ll, 'tcx>(
1052 cx: &CodegenCx<'ll, 'tcx>,
1053 unique_type_id: UniqueTypeId<'tcx>,
1054) -> DINodeCreationResult<'ll> {
1055 let struct_type = unique_type_id.expect_ty();
1056 let ty::Adt(adt_def, _) = struct_type.kind() else {
1057 bug!("build_struct_type_di_node() called with non-struct-type: {:?}", struct_type);
1058 };
1059 assert!(adt_def.is_struct());
1060 let containing_scope = get_namespace_for_item(cx, adt_def.did());
1061 let struct_type_and_layout = cx.layout_of(struct_type);
1062 let variant_def = adt_def.non_enum_variant();
1063 let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1064 Some(file_metadata_from_def_id(cx, Some(adt_def.did())))
1065 } else {
1066 None
1067 };
1068
1069 type_map::build_type_with_children(
1070 cx,
1071 type_map::stub(
1072 cx,
1073 Stub::Struct,
1074 unique_type_id,
1075 &compute_debuginfo_type_name(cx.tcx, struct_type, false),
1076 def_location,
1077 size_and_align_of(struct_type_and_layout),
1078 Some(containing_scope),
1079 visibility_di_flags(cx, adt_def.did(), adt_def.did()),
1080 ),
1081 |cx, owner| {
1083 variant_def
1084 .fields
1085 .iter()
1086 .enumerate()
1087 .map(|(i, f)| {
1088 let field_name = if variant_def.ctor_kind() == Some(CtorKind::Fn) {
1089 tuple_field_name(i)
1091 } else {
1092 Cow::Borrowed(f.name.as_str())
1094 };
1095 let field_layout = struct_type_and_layout.field(cx, i);
1096 let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1097 Some(f.did)
1098 } else {
1099 None
1100 };
1101 build_field_di_node(
1102 cx,
1103 owner,
1104 &field_name[..],
1105 field_layout,
1106 struct_type_and_layout.fields.offset(i),
1107 visibility_di_flags(cx, f.did, adt_def.did()),
1108 type_di_node(cx, field_layout.ty),
1109 def_id,
1110 )
1111 })
1112 .collect()
1113 },
1114 |cx| build_generic_type_param_di_nodes(cx, struct_type),
1115 )
1116}
1117
1118fn build_upvar_field_di_nodes<'ll, 'tcx>(
1125 cx: &CodegenCx<'ll, 'tcx>,
1126 closure_or_coroutine_ty: Ty<'tcx>,
1127 closure_or_coroutine_di_node: &'ll DIType,
1128) -> SmallVec<&'ll DIType> {
1129 let (&def_id, up_var_tys) = match closure_or_coroutine_ty.kind() {
1130 ty::Coroutine(def_id, args) => (def_id, args.as_coroutine().prefix_tys()),
1131 ty::Closure(def_id, args) => (def_id, args.as_closure().upvar_tys()),
1132 ty::CoroutineClosure(def_id, args) => (def_id, args.as_coroutine_closure().upvar_tys()),
1133 _ => {
1134 bug!(
1135 "build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {:?}",
1136 closure_or_coroutine_ty
1137 )
1138 }
1139 };
1140
1141 assert!(up_var_tys.iter().all(|t| t == cx.tcx.normalize_erasing_regions(cx.typing_env(), t)));
1142
1143 let capture_names = cx.tcx.closure_saved_names_of_captured_variables(def_id);
1144 let layout = cx.layout_of(closure_or_coroutine_ty);
1145
1146 up_var_tys
1147 .into_iter()
1148 .zip(capture_names.iter())
1149 .enumerate()
1150 .map(|(index, (up_var_ty, capture_name))| {
1151 build_field_di_node(
1152 cx,
1153 closure_or_coroutine_di_node,
1154 capture_name.as_str(),
1155 cx.layout_of(up_var_ty),
1156 layout.fields.offset(index),
1157 DIFlags::FlagZero,
1158 type_di_node(cx, up_var_ty),
1159 None,
1160 )
1161 })
1162 .collect()
1163}
1164
1165fn build_tuple_type_di_node<'ll, 'tcx>(
1167 cx: &CodegenCx<'ll, 'tcx>,
1168 unique_type_id: UniqueTypeId<'tcx>,
1169) -> DINodeCreationResult<'ll> {
1170 let tuple_type = unique_type_id.expect_ty();
1171 let &ty::Tuple(component_types) = tuple_type.kind() else {
1172 bug!("build_tuple_type_di_node() called with non-tuple-type: {:?}", tuple_type)
1173 };
1174
1175 let tuple_type_and_layout = cx.layout_of(tuple_type);
1176 let type_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1177
1178 type_map::build_type_with_children(
1179 cx,
1180 type_map::stub(
1181 cx,
1182 Stub::Struct,
1183 unique_type_id,
1184 &type_name,
1185 None,
1186 size_and_align_of(tuple_type_and_layout),
1187 NO_SCOPE_METADATA,
1188 DIFlags::FlagZero,
1189 ),
1190 |cx, tuple_di_node| {
1192 component_types
1193 .into_iter()
1194 .enumerate()
1195 .map(|(index, component_type)| {
1196 build_field_di_node(
1197 cx,
1198 tuple_di_node,
1199 &tuple_field_name(index),
1200 cx.layout_of(component_type),
1201 tuple_type_and_layout.fields.offset(index),
1202 DIFlags::FlagZero,
1203 type_di_node(cx, component_type),
1204 None,
1205 )
1206 })
1207 .collect()
1208 },
1209 NO_GENERICS,
1210 )
1211}
1212
1213fn build_closure_env_di_node<'ll, 'tcx>(
1215 cx: &CodegenCx<'ll, 'tcx>,
1216 unique_type_id: UniqueTypeId<'tcx>,
1217) -> DINodeCreationResult<'ll> {
1218 let closure_env_type = unique_type_id.expect_ty();
1219 let &(ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _)) = closure_env_type.kind()
1220 else {
1221 bug!("build_closure_env_di_node() called with non-closure-type: {:?}", closure_env_type)
1222 };
1223 let containing_scope = get_namespace_for_item(cx, def_id);
1224 let type_name = compute_debuginfo_type_name(cx.tcx, closure_env_type, false);
1225
1226 let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1227 Some(file_metadata_from_def_id(cx, Some(def_id)))
1228 } else {
1229 None
1230 };
1231
1232 type_map::build_type_with_children(
1233 cx,
1234 type_map::stub(
1235 cx,
1236 Stub::Struct,
1237 unique_type_id,
1238 &type_name,
1239 def_location,
1240 cx.size_and_align_of(closure_env_type),
1241 Some(containing_scope),
1242 DIFlags::FlagZero,
1243 ),
1244 |cx, owner| build_upvar_field_di_nodes(cx, closure_env_type, owner),
1246 NO_GENERICS,
1247 )
1248}
1249
1250fn build_union_type_di_node<'ll, 'tcx>(
1252 cx: &CodegenCx<'ll, 'tcx>,
1253 unique_type_id: UniqueTypeId<'tcx>,
1254) -> DINodeCreationResult<'ll> {
1255 let union_type = unique_type_id.expect_ty();
1256 let (union_def_id, variant_def) = match union_type.kind() {
1257 ty::Adt(def, _) => (def.did(), def.non_enum_variant()),
1258 _ => bug!("build_union_type_di_node on a non-ADT"),
1259 };
1260 let containing_scope = get_namespace_for_item(cx, union_def_id);
1261 let union_ty_and_layout = cx.layout_of(union_type);
1262 let type_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1263 let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1264 Some(file_metadata_from_def_id(cx, Some(union_def_id)))
1265 } else {
1266 None
1267 };
1268
1269 type_map::build_type_with_children(
1270 cx,
1271 type_map::stub(
1272 cx,
1273 Stub::Union,
1274 unique_type_id,
1275 &type_name,
1276 def_location,
1277 size_and_align_of(union_ty_and_layout),
1278 Some(containing_scope),
1279 DIFlags::FlagZero,
1280 ),
1281 |cx, owner| {
1283 variant_def
1284 .fields
1285 .iter()
1286 .enumerate()
1287 .map(|(i, f)| {
1288 let field_layout = union_ty_and_layout.field(cx, i);
1289 let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1290 Some(f.did)
1291 } else {
1292 None
1293 };
1294 build_field_di_node(
1295 cx,
1296 owner,
1297 f.name.as_str(),
1298 field_layout,
1299 Size::ZERO,
1300 DIFlags::FlagZero,
1301 type_di_node(cx, field_layout.ty),
1302 def_id,
1303 )
1304 })
1305 .collect()
1306 },
1307 |cx| build_generic_type_param_di_nodes(cx, union_type),
1309 )
1310}
1311
1312fn build_generic_type_param_di_nodes<'ll, 'tcx>(
1314 cx: &CodegenCx<'ll, 'tcx>,
1315 ty: Ty<'tcx>,
1316) -> SmallVec<Option<&'ll DIType>> {
1317 if let ty::Adt(def, args) = *ty.kind() {
1318 if args.types().next().is_some() {
1319 let generics = cx.tcx.generics_of(def.did());
1320 let names = get_parameter_names(cx, generics);
1321 let template_params: SmallVec<_> = iter::zip(args, names)
1322 .filter_map(|(kind, name)| {
1323 kind.as_type().map(|ty| {
1324 let actual_type = cx.tcx.normalize_erasing_regions(cx.typing_env(), ty);
1325 let actual_type_di_node = type_di_node(cx, actual_type);
1326 Some(cx.create_template_type_parameter(name.as_str(), actual_type_di_node))
1327 })
1328 })
1329 .collect();
1330
1331 return template_params;
1332 }
1333 }
1334
1335 return smallvec![];
1336
1337 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
1338 let mut names = generics
1339 .parent
1340 .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
1341 names.extend(generics.own_params.iter().map(|param| param.name));
1342 names
1343 }
1344}
1345
1346pub(crate) fn build_global_var_di_node<'ll>(
1350 cx: &CodegenCx<'ll, '_>,
1351 def_id: DefId,
1352 global: &'ll Value,
1353) {
1354 if cx.dbg_cx.is_none() {
1355 return;
1356 }
1357
1358 if cx.sess().opts.debuginfo != DebugInfo::Full {
1360 return;
1361 }
1362
1363 let tcx = cx.tcx;
1364
1365 let var_scope = get_namespace_for_item(cx, def_id);
1368 let (file_metadata, line_number) = file_metadata_from_def_id(cx, Some(def_id));
1369
1370 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
1371
1372 let DefKind::Static { nested, .. } = cx.tcx.def_kind(def_id) else { bug!() };
1373 if nested {
1374 return;
1375 }
1376 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, cx.typing_env());
1377 let type_di_node = type_di_node(cx, variable_type);
1378 let var_name = tcx.item_name(def_id);
1379 let var_name = var_name.as_str();
1380 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
1381 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
1384
1385 let global_align = cx.align_of(variable_type);
1386
1387 unsafe {
1388 llvm::LLVMRustDIBuilderCreateStaticVariable(
1389 DIB(cx),
1390 Some(var_scope),
1391 var_name.as_c_char_ptr(),
1392 var_name.len(),
1393 linkage_name.as_c_char_ptr(),
1394 linkage_name.len(),
1395 file_metadata,
1396 line_number,
1397 type_di_node,
1398 is_local_to_unit,
1399 global,
1400 None,
1401 global_align.bits() as u32,
1402 );
1403 }
1404}
1405
1406fn build_vtable_type_di_node<'ll, 'tcx>(
1416 cx: &CodegenCx<'ll, 'tcx>,
1417 ty: Ty<'tcx>,
1418 poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1419) -> &'ll DIType {
1420 let tcx = cx.tcx;
1421
1422 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
1423 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
1424 let trait_ref = tcx.erase_regions(trait_ref);
1425
1426 tcx.vtable_entries(trait_ref)
1427 } else {
1428 TyCtxt::COMMON_VTABLE_ENTRIES
1429 };
1430
1431 let void_pointer_ty = Ty::new_imm_ptr(tcx, tcx.types.unit);
1434 let void_pointer_type_di_node = type_di_node(cx, void_pointer_ty);
1435 let usize_di_node = type_di_node(cx, tcx.types.usize);
1436 let pointer_layout = cx.layout_of(void_pointer_ty);
1437 let pointer_size = pointer_layout.size;
1438 let pointer_align = pointer_layout.align.abi;
1439 assert_eq!(cx.size_and_align_of(tcx.types.usize), (pointer_size, pointer_align));
1443
1444 let vtable_type_name =
1445 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
1446 let unique_type_id = UniqueTypeId::for_vtable_ty(tcx, ty, poly_trait_ref);
1447 let size = pointer_size * vtable_entries.len() as u64;
1448
1449 let vtable_holder = type_di_node(cx, ty);
1452
1453 build_type_with_children(
1454 cx,
1455 type_map::stub(
1456 cx,
1457 Stub::VTableTy { vtable_holder },
1458 unique_type_id,
1459 &vtable_type_name,
1460 None,
1461 (size, pointer_align),
1462 NO_SCOPE_METADATA,
1463 DIFlags::FlagArtificial,
1464 ),
1465 |cx, vtable_type_di_node| {
1466 vtable_entries
1467 .iter()
1468 .enumerate()
1469 .filter_map(|(index, vtable_entry)| {
1470 let (field_name, field_type_di_node) = match vtable_entry {
1471 ty::VtblEntry::MetadataDropInPlace => {
1472 ("drop_in_place".to_string(), void_pointer_type_di_node)
1473 }
1474 ty::VtblEntry::Method(_) => {
1475 (format!("__method{index}"), void_pointer_type_di_node)
1479 }
1480 ty::VtblEntry::TraitVPtr(_) => {
1481 (format!("__super_trait_ptr{index}"), void_pointer_type_di_node)
1482 }
1483 ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_di_node),
1484 ty::VtblEntry::MetadataSize => ("size".to_string(), usize_di_node),
1485 ty::VtblEntry::Vacant => return None,
1486 };
1487
1488 let field_offset = pointer_size * index as u64;
1489
1490 Some(build_field_di_node(
1491 cx,
1492 vtable_type_di_node,
1493 &field_name,
1494 pointer_layout,
1495 field_offset,
1496 DIFlags::FlagZero,
1497 field_type_di_node,
1498 None,
1499 ))
1500 })
1501 .collect()
1502 },
1503 NO_GENERICS,
1504 )
1505 .di_node
1506}
1507
1508fn find_vtable_behind_cast<'ll>(vtable: &'ll Value) -> &'ll Value {
1517 unsafe {
1519 if let Some(c) = llvm::LLVMIsAConstantExpr(vtable) {
1520 if llvm::LLVMGetConstOpcode(c) == llvm::Opcode::AddrSpaceCast {
1521 return llvm::LLVMGetOperand(c, 0).unwrap();
1522 }
1523 }
1524 }
1525 vtable
1526}
1527
1528pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>(
1529 cx: &CodegenCx<'ll, 'tcx>,
1530 ty: Ty<'tcx>,
1531 trait_ref: Option<ExistentialTraitRef<'tcx>>,
1532 vtable: &'ll Value,
1533) {
1534 if !cx.sess().opts.unstable_opts.virtual_function_elimination || cx.sess().lto() != Lto::Fat {
1537 return;
1538 }
1539
1540 enum VCallVisibility {
1541 Public = 0,
1542 LinkageUnit = 1,
1543 TranslationUnit = 2,
1544 }
1545
1546 let Some(trait_ref) = trait_ref else { return };
1547
1548 let vtable = find_vtable_behind_cast(vtable);
1550 let trait_ref_self = trait_ref.with_self_ty(cx.tcx, ty);
1551 let trait_ref_self = cx.tcx.erase_regions(trait_ref_self);
1552 let trait_def_id = trait_ref_self.def_id;
1553 let trait_vis = cx.tcx.visibility(trait_def_id);
1554
1555 let cgus = cx.sess().codegen_units().as_usize();
1556 let single_cgu = cgus == 1;
1557
1558 let lto = cx.sess().lto();
1559
1560 let vcall_visibility = match (lto, trait_vis, single_cgu) {
1563 (Lto::No | Lto::ThinLocal, Visibility::Public, _)
1566 | (Lto::No, Visibility::Restricted(_), false) => VCallVisibility::Public,
1567 (Lto::Fat | Lto::Thin, Visibility::Public, _)
1572 | (Lto::ThinLocal | Lto::Thin | Lto::Fat, Visibility::Restricted(_), false) => {
1573 VCallVisibility::LinkageUnit
1574 }
1575 (_, Visibility::Restricted(_), true) => VCallVisibility::TranslationUnit,
1578 };
1579
1580 let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref);
1581
1582 unsafe {
1583 let typeid = llvm::LLVMMDStringInContext2(
1584 cx.llcx,
1585 trait_ref_typeid.as_ptr() as *const c_char,
1586 trait_ref_typeid.as_bytes().len(),
1587 );
1588 let v = [llvm::LLVMValueAsMetadata(cx.const_usize(0)), typeid];
1589 llvm::LLVMRustGlobalAddMetadata(
1590 vtable,
1591 llvm::MD_type as c_uint,
1592 llvm::LLVMMDNodeInContext2(cx.llcx, v.as_ptr(), v.len()),
1593 );
1594 let vcall_visibility = llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64));
1595 let vcall_visibility_metadata = llvm::LLVMMDNodeInContext2(cx.llcx, &vcall_visibility, 1);
1596 llvm::LLVMGlobalSetMetadata(
1597 vtable,
1598 llvm::MetadataType::MD_vcall_visibility as c_uint,
1599 vcall_visibility_metadata,
1600 );
1601 }
1602}
1603
1604pub(crate) fn create_vtable_di_node<'ll, 'tcx>(
1609 cx: &CodegenCx<'ll, 'tcx>,
1610 ty: Ty<'tcx>,
1611 poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1612 vtable: &'ll Value,
1613) {
1614 if cx.dbg_cx.is_none() {
1615 return;
1616 }
1617
1618 if cx.sess().opts.debuginfo != DebugInfo::Full {
1620 return;
1621 }
1622
1623 let vtable = find_vtable_behind_cast(vtable);
1625
1626 llvm::SetUnnamedAddress(vtable, llvm::UnnamedAddr::No);
1630
1631 let vtable_name =
1632 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
1633 let vtable_type_di_node = build_vtable_type_di_node(cx, ty, poly_trait_ref);
1634 let linkage_name = "";
1635
1636 unsafe {
1637 llvm::LLVMRustDIBuilderCreateStaticVariable(
1638 DIB(cx),
1639 NO_SCOPE_METADATA,
1640 vtable_name.as_c_char_ptr(),
1641 vtable_name.len(),
1642 linkage_name.as_c_char_ptr(),
1643 linkage_name.len(),
1644 unknown_file_metadata(cx),
1645 UNKNOWN_LINE_NUMBER,
1646 vtable_type_di_node,
1647 true,
1648 vtable,
1649 None,
1650 0,
1651 );
1652 }
1653}
1654
1655pub(crate) fn extend_scope_to_file<'ll>(
1657 cx: &CodegenCx<'ll, '_>,
1658 scope_metadata: &'ll DIScope,
1659 file: &SourceFile,
1660) -> &'ll DILexicalBlock {
1661 let file_metadata = file_metadata(cx, file);
1662 unsafe {
1663 llvm::LLVMDIBuilderCreateLexicalBlockFile(
1664 DIB(cx),
1665 scope_metadata,
1666 file_metadata,
1667 0u32,
1668 )
1669 }
1670}
1671
1672fn tuple_field_name(field_index: usize) -> Cow<'static, str> {
1673 const TUPLE_FIELD_NAMES: [&'static str; 16] = [
1674 "__0", "__1", "__2", "__3", "__4", "__5", "__6", "__7", "__8", "__9", "__10", "__11",
1675 "__12", "__13", "__14", "__15",
1676 ];
1677 TUPLE_FIELD_NAMES
1678 .get(field_index)
1679 .map(|s| Cow::from(*s))
1680 .unwrap_or_else(|| Cow::from(format!("__{field_index}")))
1681}
1682
1683pub(crate) type DefinitionLocation<'ll> = (&'ll DIFile, c_uint);
1684
1685pub(crate) fn file_metadata_from_def_id<'ll>(
1686 cx: &CodegenCx<'ll, '_>,
1687 def_id: Option<DefId>,
1688) -> DefinitionLocation<'ll> {
1689 if let Some(def_id) = def_id
1690 && let span = hygiene::walk_chain_collapsed(cx.tcx.def_span(def_id), DUMMY_SP)
1691 && !span.is_dummy()
1692 {
1693 let loc = cx.lookup_debug_loc(span.lo());
1694 (file_metadata(cx, &loc.file), loc.line)
1695 } else {
1696 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1697 }
1698}