rustc_codegen_llvm/coverageinfo/mapgen.rs
1use std::assert_matches::assert_matches;
2use std::sync::Arc;
3
4use itertools::Itertools;
5use rustc_abi::Align;
6use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods};
7use rustc_data_structures::fx::FxIndexMap;
8use rustc_index::IndexVec;
9use rustc_middle::ty::TyCtxt;
10use rustc_session::RemapFileNameExt;
11use rustc_session::config::RemapPathScopeComponents;
12use rustc_span::{SourceFile, StableSourceFileId};
13use tracing::debug;
14
15use crate::common::CodegenCx;
16use crate::coverageinfo::llvm_cov;
17use crate::coverageinfo::mapgen::covfun::prepare_covfun_record;
18use crate::{TryFromU32, llvm};
19
20mod covfun;
21mod spans;
22mod unused;
23
24/// Version number that will be included the `__llvm_covmap` section header.
25/// Corresponds to LLVM's `llvm::coverage::CovMapVersion` (in `CoverageMapping.h`),
26/// or at least the subset that we know and care about.
27///
28/// Note that version `n` is encoded as `(n-1)`.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, TryFromU32)]
30enum CovmapVersion {
31 /// Used by LLVM 18 onwards.
32 Version7 = 6,
33}
34
35impl CovmapVersion {
36 fn to_u32(self) -> u32 {
37 self as u32
38 }
39}
40
41/// Generates and exports the coverage map, which is embedded in special
42/// linker sections in the final binary.
43///
44/// Those sections are then read and understood by LLVM's `llvm-cov` tool,
45/// which is distributed in the `llvm-tools` rustup component.
46pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) {
47 let tcx = cx.tcx;
48
49 // Ensure that LLVM is using a version of the coverage mapping format that
50 // agrees with our Rust-side code. Expected versions are:
51 // - `Version7` (6) used by LLVM 18 onwards.
52 let covmap_version =
53 CovmapVersion::try_from(llvm_cov::mapping_version()).unwrap_or_else(|raw_version: u32| {
54 panic!("unknown coverage mapping version reported by `llvm-wrapper`: {raw_version}")
55 });
56 assert_matches!(covmap_version, CovmapVersion::Version7);
57
58 debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
59
60 // FIXME(#132395): Can this be none even when coverage is enabled?
61 let Some(ref coverage_cx) = cx.coverage_cx else { return };
62
63 let mut covfun_records = coverage_cx
64 .instances_used()
65 .into_iter()
66 // Sort by symbol name, so that the global file table is built in an
67 // order that doesn't depend on the stable-hash-based order in which
68 // instances were visited during codegen.
69 .sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name)
70 .filter_map(|instance| prepare_covfun_record(tcx, instance, true))
71 .collect::<Vec<_>>();
72
73 // In a single designated CGU, also prepare covfun records for functions
74 // in this crate that were instrumented for coverage, but are unused.
75 if cx.codegen_unit.is_code_coverage_dead_code_cgu() {
76 unused::prepare_covfun_records_for_unused_functions(cx, &mut covfun_records);
77 }
78
79 // If there are no covfun records for this CGU, don't generate a covmap record.
80 // Emitting a covmap record without any covfun records causes `llvm-cov` to
81 // fail when generating coverage reports, and if there are no covfun records
82 // then the covmap record isn't useful anyway.
83 // This should prevent a repeat of <https://github.com/rust-lang/rust/issues/133606>.
84 if covfun_records.is_empty() {
85 return;
86 }
87
88 // Prepare the global file table for this CGU, containing all paths needed
89 // by one or more covfun records.
90 let global_file_table =
91 GlobalFileTable::build(tcx, covfun_records.iter().flat_map(|c| c.all_source_files()));
92
93 for covfun in &covfun_records {
94 covfun::generate_covfun_record(cx, &global_file_table, covfun)
95 }
96
97 // Generate the coverage map header, which contains the filenames used by
98 // this CGU's coverage mappings, and store it in a well-known global.
99 // (This is skipped if we returned early due to having no covfun records.)
100 generate_covmap_record(cx, covmap_version, &global_file_table.filenames_buffer);
101}
102
103/// Maps "global" (per-CGU) file ID numbers to their underlying source file paths.
104#[derive(Debug)]
105struct GlobalFileTable {
106 /// This "raw" table doesn't include the working dir, so a file's
107 /// global ID is its index in this set **plus one**.
108 raw_file_table: FxIndexMap<StableSourceFileId, String>,
109
110 /// The file table in encoded form (possibly compressed), which can be
111 /// included directly in this CGU's `__llvm_covmap` record.
112 filenames_buffer: Vec<u8>,
113
114 /// Truncated hash of the bytes in `filenames_buffer`.
115 ///
116 /// The `llvm-cov` tool uses this hash to associate each covfun record with
117 /// its corresponding filenames table, since the final binary will typically
118 /// contain multiple covmap records from different compilation units.
119 filenames_hash: u64,
120}
121
122impl GlobalFileTable {
123 /// Builds a "global file table" for this CGU, mapping numeric IDs to
124 /// path strings.
125 fn build<'a>(tcx: TyCtxt<'_>, all_files: impl Iterator<Item = &'a SourceFile>) -> Self {
126 let mut raw_file_table = FxIndexMap::default();
127
128 for file in all_files {
129 raw_file_table.entry(file.stable_id).or_insert_with(|| {
130 file.name
131 .for_scope(tcx.sess, RemapPathScopeComponents::MACRO)
132 .to_string_lossy()
133 .into_owned()
134 });
135 }
136
137 // FIXME(Zalathar): Consider sorting the file table here, but maybe
138 // only after adding filename support to coverage-dump, so that the
139 // table order isn't directly visible in `.coverage-map` snapshots.
140
141 let mut table = Vec::with_capacity(raw_file_table.len() + 1);
142
143 // Since version 6 of the LLVM coverage mapping format, the first entry
144 // in the global file table is treated as a base directory, used to
145 // resolve any other entries that are stored as relative paths.
146 let base_dir = tcx
147 .sess
148 .opts
149 .working_dir
150 .for_scope(tcx.sess, RemapPathScopeComponents::MACRO)
151 .to_string_lossy();
152 table.push(base_dir.as_ref());
153
154 // Add the regular entries after the base directory.
155 table.extend(raw_file_table.values().map(|name| name.as_str()));
156
157 // Encode the file table into a buffer, and get the hash of its encoded
158 // bytes, so that we can embed that hash in `__llvm_covfun` records.
159 let filenames_buffer = llvm_cov::write_filenames_to_buffer(&table);
160 let filenames_hash = llvm_cov::hash_bytes(&filenames_buffer);
161
162 Self { raw_file_table, filenames_buffer, filenames_hash }
163 }
164
165 fn get_existing_id(&self, file: &SourceFile) -> Option<GlobalFileId> {
166 let raw_id = self.raw_file_table.get_index_of(&file.stable_id)?;
167 // The raw file table doesn't include an entry for the base dir
168 // (which has ID 0), so add 1 to get the correct ID.
169 Some(GlobalFileId::from_usize(raw_id + 1))
170 }
171}
172
173rustc_index::newtype_index! {
174 /// An index into the CGU's overall list of file paths. The underlying paths
175 /// will be embedded in the `__llvm_covmap` linker section.
176 struct GlobalFileId {}
177}
178rustc_index::newtype_index! {
179 /// An index into a function's list of global file IDs. That underlying list
180 /// of local-to-global mappings will be embedded in the function's record in
181 /// the `__llvm_covfun` linker section.
182 struct LocalFileId {}
183}
184
185/// Holds a mapping from "local" (per-function) file IDs to their corresponding
186/// source files.
187#[derive(Debug, Default)]
188struct VirtualFileMapping {
189 local_file_table: IndexVec<LocalFileId, Arc<SourceFile>>,
190}
191
192impl VirtualFileMapping {
193 fn push_file(&mut self, source_file: &Arc<SourceFile>) -> LocalFileId {
194 self.local_file_table.push(Arc::clone(source_file))
195 }
196
197 /// Resolves all of the filenames in this local file mapping to a list of
198 /// global file IDs in its CGU, for inclusion in this function's
199 /// `__llvm_covfun` record.
200 ///
201 /// The global file IDs are returned as `u32` to make FFI easier.
202 fn resolve_all(&self, global_file_table: &GlobalFileTable) -> Option<Vec<u32>> {
203 self.local_file_table
204 .iter()
205 .map(|file| try {
206 let id = global_file_table.get_existing_id(file)?;
207 GlobalFileId::as_u32(id)
208 })
209 .collect::<Option<Vec<_>>>()
210 }
211}
212
213/// Generates the contents of the covmap record for this CGU, which mostly
214/// consists of a header and a list of filenames. The record is then stored
215/// as a global variable in the `__llvm_covmap` section.
216fn generate_covmap_record<'ll>(
217 cx: &mut CodegenCx<'ll, '_>,
218 version: CovmapVersion,
219 filenames_buffer: &[u8],
220) {
221 // A covmap record consists of four target-endian u32 values, followed by
222 // the encoded filenames table. Two of the header fields are unused in
223 // modern versions of the LLVM coverage mapping format, and are always 0.
224 // <https://llvm.org/docs/CoverageMappingFormat.html#llvm-ir-representation>
225 // See also `src/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp`.
226 let covmap_header = cx.const_struct(
227 &[
228 cx.const_u32(0), // (unused)
229 cx.const_u32(filenames_buffer.len() as u32),
230 cx.const_u32(0), // (unused)
231 cx.const_u32(version.to_u32()),
232 ],
233 /* packed */ false,
234 );
235 let covmap_record = cx
236 .const_struct(&[covmap_header, cx.const_bytes(filenames_buffer)], /* packed */ false);
237
238 let covmap_global =
239 llvm::add_global(cx.llmod, cx.val_ty(covmap_record), &llvm_cov::covmap_var_name());
240 llvm::set_initializer(covmap_global, covmap_record);
241 llvm::set_global_constant(covmap_global, true);
242 llvm::set_linkage(covmap_global, llvm::Linkage::PrivateLinkage);
243 llvm::set_section(covmap_global, &llvm_cov::covmap_section_name(cx.llmod));
244 // LLVM's coverage mapping format specifies 8-byte alignment for items in this section.
245 // <https://llvm.org/docs/CoverageMappingFormat.html>
246 llvm::set_alignment(covmap_global, Align::EIGHT);
247
248 cx.add_used_global(covmap_global);
249}