Skip to main content

rustc_codegen_llvm/coverageinfo/
mapgen.rs

1use std::assert_matches;
2
3use itertools::Itertools;
4use rustc_abi::Align;
5use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods};
6use rustc_data_structures::fx::FxIndexMap;
7use rustc_middle::ty::TyCtxt;
8use rustc_span::{FileName, RemapPathScopeComponents, SourceFile, StableSourceFileId};
9use tracing::debug;
10
11use crate::common::CodegenCx;
12use crate::coverageinfo::llvm_cov;
13use crate::coverageinfo::mapgen::covfun::prepare_covfun_record;
14use crate::llvm;
15use crate::macros::TryFromU32;
16
17mod covfun;
18mod spans;
19mod unused;
20
21/// Version number that will be included the `__llvm_covmap` section header.
22/// Corresponds to LLVM's `llvm::coverage::CovMapVersion` (in `CoverageMapping.h`),
23/// or at least the subset that we know and care about.
24///
25/// Note that version `n` is encoded as `(n-1)`.
26#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CovmapVersion { }
#[automatically_derived]
impl ::core::clone::Clone for CovmapVersion {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CovmapVersion { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for CovmapVersion {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "Version7")
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CovmapVersion { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CovmapVersion {
    #[inline]
    fn eq(&self, other: &Self) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CovmapVersion { }Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for CovmapVersion {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ordering::Equal)
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for CovmapVersion {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ordering::Equal
    }
}Ord, impl ::core::convert::TryFrom<u32> for CovmapVersion {
    type Error = u32;
    #[allow(deprecated)]
    fn try_from(value: u32)
        -> ::core::result::Result<CovmapVersion, Self::Error> {
        if value == const { CovmapVersion::Version7 as u32 } {
            return Ok(CovmapVersion::Version7)
        }
        Err(value)
    }
}TryFromU32)]
27enum CovmapVersion {
28    /// Used by LLVM 18 onwards.
29    Version7 = 6,
30}
31
32impl CovmapVersion {
33    fn to_u32(self) -> u32 {
34        self as u32
35    }
36}
37
38/// Generates and exports the coverage map, which is embedded in special
39/// linker sections in the final binary.
40///
41/// Those sections are then read and understood by LLVM's `llvm-cov` tool,
42/// which is distributed in the `llvm-tools` rustup component.
43pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) {
44    let tcx = cx.tcx;
45
46    // Ensure that LLVM is using a version of the coverage mapping format that
47    // agrees with our Rust-side code. Expected versions are:
48    // - `Version7` (6) used by LLVM 18 onwards.
49    let covmap_version =
50        CovmapVersion::try_from(llvm_cov::mapping_version()).unwrap_or_else(|raw_version: u32| {
51            {
    ::core::panicking::panic_fmt(format_args!("unknown coverage mapping version reported by `llvm-wrapper`: {0}",
            raw_version));
}panic!("unknown coverage mapping version reported by `llvm-wrapper`: {raw_version}")
52        });
53    {
    match covmap_version {
        CovmapVersion::Version7 => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "CovmapVersion::Version7", ::core::option::Option::None);
        }
    }
};assert_matches!(covmap_version, CovmapVersion::Version7);
54
55    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs:55",
                        "rustc_codegen_llvm::coverageinfo::mapgen",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs"),
                        ::tracing_core::__macro_support::Option::Some(55u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::coverageinfo::mapgen"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Generating coverage map for CodegenUnit: `{0}`",
                                                    cx.codegen_unit.name()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
56
57    // FIXME(#132395): Can this be none even when coverage is enabled?
58    let Some(ref coverage_cx) = cx.coverage_cx else { return };
59
60    let mut covfun_records = coverage_cx
61        .instances_used()
62        .into_iter()
63        // Sort by symbol name, so that the global file table is built in an
64        // order that doesn't depend on the stable-hash-based order in which
65        // instances were visited during codegen.
66        .sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name)
67        .filter_map(|instance| prepare_covfun_record(tcx, instance, true))
68        .collect::<Vec<_>>();
69
70    // In a single designated CGU, also prepare covfun records for functions
71    // in this crate that were instrumented for coverage, but are unused.
72    if cx.codegen_unit.is_code_coverage_dead_code_cgu() {
73        unused::prepare_covfun_records_for_unused_functions(cx, &mut covfun_records);
74    }
75
76    // If there are no covfun records for this CGU, don't emit a covmap record.
77    // Emitting a covmap record without any covfun records causes `llvm-cov` to
78    // fail when generating coverage reports, and if there are no covfun records
79    // then the covmap record isn't useful anyway.
80    // This should prevent a repeat of <https://github.com/rust-lang/rust/issues/133606>.
81    if covfun_records.is_empty() {
82        return;
83    }
84
85    // Prepare the global file table for this CGU, containing all paths needed
86    // by one or more covfun records.
87    let global_file_table =
88        GlobalFileTable::build(tcx, covfun_records.iter().flat_map(|c| c.all_source_files()));
89
90    for covfun in &covfun_records {
91        covfun::emit_covfun_record(cx, &global_file_table, covfun);
92    }
93
94    // Emit the coverage map header, which contains the filenames used by
95    // this CGU's coverage mappings, and store it in a well-known global.
96    // (This is skipped if we returned early due to having no covfun records.)
97    emit_covmap_record(cx, covmap_version, &global_file_table.filenames_buffer);
98}
99
100/// Maps "global" (per-CGU) file ID numbers to their underlying source file paths.
101#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GlobalFileTable {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "GlobalFileTable", "raw_file_table", &self.raw_file_table,
            "filenames_buffer", &self.filenames_buffer, "filenames_hash",
            &&self.filenames_hash)
    }
}Debug)]
102struct GlobalFileTable {
103    /// This "raw" table doesn't include the working dir, so a file's
104    /// global ID is its index in this set **plus one**.
105    raw_file_table: FxIndexMap<StableSourceFileId, String>,
106
107    /// The file table in encoded form (possibly compressed), which can be
108    /// included directly in this CGU's `__llvm_covmap` record.
109    filenames_buffer: Vec<u8>,
110
111    /// Truncated hash of the bytes in `filenames_buffer`.
112    ///
113    /// The `llvm-cov` tool uses this hash to associate each covfun record with
114    /// its corresponding filenames table, since the final binary will typically
115    /// contain multiple covmap records from different compilation units.
116    filenames_hash: u64,
117}
118
119impl GlobalFileTable {
120    /// Builds a "global file table" for this CGU, mapping numeric IDs to
121    /// path strings.
122    fn build<'a>(tcx: TyCtxt<'_>, all_files: impl Iterator<Item = &'a SourceFile>) -> Self {
123        let mut raw_file_table = FxIndexMap::default();
124
125        for file in all_files {
126            raw_file_table.entry(file.stable_id).or_insert_with(|| {
127                // Prefer using the embeddable filename as this filename is going to
128                // end-up in the coverage artifacts (see rust-lang/rust#150020).
129                if let FileName::Real(real) = &file.name {
130                    let (_work_dir, abs_name) =
131                        real.embeddable_name(RemapPathScopeComponents::COVERAGE);
132
133                    abs_name.to_string_lossy().into_owned()
134                } else {
135                    file.name
136                        .display(RemapPathScopeComponents::COVERAGE)
137                        .to_string_lossy()
138                        .into_owned()
139                }
140            });
141        }
142
143        // FIXME(Zalathar): Consider sorting the file table here, but maybe
144        // only after adding filename support to coverage-dump, so that the
145        // table order isn't directly visible in `.coverage-map` snapshots.
146
147        let mut table = Vec::with_capacity(raw_file_table.len() + 1);
148
149        // Since version 6 of the LLVM coverage mapping format, the first entry
150        // in the global file table is treated as a base directory, used to
151        // resolve any other entries that are stored as relative paths.
152        let base_dir = tcx
153            .sess
154            .psess
155            .source_map()
156            .working_dir()
157            .path(RemapPathScopeComponents::COVERAGE)
158            .to_string_lossy();
159        table.push(base_dir.as_ref());
160
161        // Add the regular entries after the base directory.
162        table.extend(raw_file_table.values().map(|name| name.as_str()));
163
164        // Encode the file table into a buffer, and get the hash of its encoded
165        // bytes, so that we can embed that hash in `__llvm_covfun` records.
166        let filenames_buffer = llvm_cov::write_filenames_to_buffer(&table);
167        let filenames_hash = llvm_cov::hash_bytes(&filenames_buffer);
168
169        Self { raw_file_table, filenames_buffer, filenames_hash }
170    }
171
172    fn get_existing_id(&self, file: &SourceFile) -> Option<GlobalFileId> {
173        let raw_id = self.raw_file_table.get_index_of(&file.stable_id)?;
174        // The raw file table doesn't include an entry for the base dir
175        // (which has ID 0), so add 1 to get the correct ID.
176        Some(GlobalFileId::from_usize(raw_id + 1))
177    }
178}
179
180#[automatically_derived]
impl ::core::marker::Copy for GlobalFileId { }
impl GlobalFileId {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for GlobalFileId {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for GlobalFileId {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for GlobalFileId {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl From<GlobalFileId> for u32 {
    #[inline]
    fn from(v: GlobalFileId) -> u32 { v.as_u32() }
}
impl From<GlobalFileId> for usize {
    #[inline]
    fn from(v: GlobalFileId) -> usize { v.as_usize() }
}
impl From<usize> for GlobalFileId {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for GlobalFileId {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for GlobalFileId {}
impl ::std::cmp::PartialEq for GlobalFileId {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for GlobalFileId {}
impl ::std::hash::Hash for GlobalFileId {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for GlobalFileId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
181    /// An index into the CGU's overall list of file paths. The underlying paths
182    /// will be embedded in the `__llvm_covmap` linker section.
183    struct GlobalFileId {}
184}
185#[automatically_derived]
impl ::core::marker::Copy for LocalFileId { }
impl LocalFileId {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for LocalFileId {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for LocalFileId {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for LocalFileId {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl From<LocalFileId> for u32 {
    #[inline]
    fn from(v: LocalFileId) -> u32 { v.as_u32() }
}
impl From<LocalFileId> for usize {
    #[inline]
    fn from(v: LocalFileId) -> usize { v.as_usize() }
}
impl From<usize> for LocalFileId {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for LocalFileId {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for LocalFileId {}
impl ::std::cmp::PartialEq for LocalFileId {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for LocalFileId {}
impl ::std::hash::Hash for LocalFileId {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for LocalFileId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
186    /// An index into a function's list of global file IDs. That underlying list
187    /// of local-to-global mappings will be embedded in the function's record in
188    /// the `__llvm_covfun` linker section.
189    struct LocalFileId {}
190}
191
192/// Generates and emits the covmap record for this CGU, which mostly
193/// consists of a header and a list of filenames. The record is emitted
194/// as a global variable in the `__llvm_covmap` section.
195fn emit_covmap_record<'ll>(
196    cx: &mut CodegenCx<'ll, '_>,
197    version: CovmapVersion,
198    filenames_buffer: &[u8],
199) {
200    // A covmap record consists of four target-endian u32 values, followed by
201    // the encoded filenames table. Two of the header fields are unused in
202    // modern versions of the LLVM coverage mapping format, and are always 0.
203    // <https://llvm.org/docs/CoverageMappingFormat.html#llvm-ir-representation>
204    // See also `src/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp`.
205    let covmap_header = cx.const_struct(
206        &[
207            cx.const_u32(0), // (unused)
208            cx.const_u32(filenames_buffer.len() as u32),
209            cx.const_u32(0), // (unused)
210            cx.const_u32(version.to_u32()),
211        ],
212        /* packed */ false,
213    );
214    let covmap_record = cx
215        .const_struct(&[covmap_header, cx.const_bytes(filenames_buffer)], /* packed */ false);
216
217    let covmap_global =
218        llvm::add_global(cx.llmod, cx.val_ty(covmap_record), &llvm_cov::covmap_var_name());
219    llvm::set_initializer(covmap_global, covmap_record);
220    llvm::set_global_constant(covmap_global, true);
221    llvm::set_linkage(covmap_global, llvm::Linkage::PrivateLinkage);
222    llvm::set_section(covmap_global, &llvm_cov::covmap_section_name(cx.llmod));
223    // LLVM's coverage mapping format specifies 8-byte alignment for items in this section.
224    // <https://llvm.org/docs/CoverageMappingFormat.html>
225    llvm::set_alignment(covmap_global, Align::EIGHT);
226
227    cx.add_used_global(covmap_global);
228}