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