]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/coverageinfo/mapgen.rs
Auto merge of #74410 - mati865:mingw-no-self-contained-when-cross-compiling, r=petroc...
[rust.git] / src / librustc_codegen_llvm / coverageinfo / mapgen.rs
1 use crate::common::CodegenCx;
2 use crate::coverageinfo;
3 use crate::llvm;
4
5 use llvm::coverageinfo::CounterMappingRegion;
6 use log::debug;
7 use rustc_codegen_ssa::coverageinfo::map::{Counter, CounterExpression, Region};
8 use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods};
9 use rustc_data_structures::fx::FxIndexSet;
10 use rustc_llvm::RustString;
11
12 use std::ffi::CString;
13
14 /// Generates and exports the Coverage Map.
15 ///
16 /// This Coverage Map complies with Coverage Mapping Format version 3 (zero-based encoded as 2),
17 /// as defined at [LLVM Code Coverage Mapping Format](https://github.com/rust-lang/llvm-project/blob/llvmorg-8.0.0/llvm/docs/CoverageMappingFormat.rst#llvm-code-coverage-mapping-format)
18 /// and published in Rust's current (July 2020) fork of LLVM. This version is supported by the
19 /// LLVM coverage tools (`llvm-profdata` and `llvm-cov`) bundled with Rust's fork of LLVM.
20 ///
21 /// Consequently, Rust's bundled version of Clang also generates Coverage Maps compliant with
22 /// version 3. Clang's implementation of Coverage Map generation was referenced when implementing
23 /// this Rust version, and though the format documentation is very explicit and detailed, some
24 /// undocumented details in Clang's implementation (that may or may not be important) were also
25 /// replicated for Rust's Coverage Map.
26 pub fn finalize<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) {
27     let function_coverage_map = cx.coverage_context().take_function_coverage_map();
28     if function_coverage_map.is_empty() {
29         // This module has no functions with coverage instrumentation
30         return;
31     }
32
33     let mut mapgen = CoverageMapGenerator::new();
34
35     // Encode coverage mappings and generate function records
36     let mut function_records = Vec::<&'ll llvm::Value>::new();
37     let coverage_mappings_buffer = llvm::build_byte_buffer(|coverage_mappings_buffer| {
38         for (instance, function_coverage) in function_coverage_map.into_iter() {
39             debug!("Generate coverage map for: {:?}", instance);
40
41             let mangled_function_name = cx.tcx.symbol_name(instance).to_string();
42             let function_source_hash = function_coverage.source_hash();
43             let (expressions, counter_regions) =
44                 function_coverage.get_expressions_and_counter_regions();
45
46             let old_len = coverage_mappings_buffer.len();
47             mapgen.write_coverage_mappings(expressions, counter_regions, coverage_mappings_buffer);
48             let mapping_data_size = coverage_mappings_buffer.len() - old_len;
49             debug_assert!(
50                 mapping_data_size > 0,
51                 "Every `FunctionCoverage` should have at least one counter"
52             );
53
54             let function_record = mapgen.make_function_record(
55                 cx,
56                 mangled_function_name,
57                 function_source_hash,
58                 mapping_data_size,
59             );
60             function_records.push(function_record);
61         }
62     });
63
64     // Encode all filenames referenced by counters/expressions in this module
65     let filenames_buffer = llvm::build_byte_buffer(|filenames_buffer| {
66         coverageinfo::write_filenames_section_to_buffer(&mapgen.filenames, filenames_buffer);
67     });
68
69     // Generate the LLVM IR representation of the coverage map and store it in a well-known global
70     mapgen.save_generated_coverage_map(
71         cx,
72         function_records,
73         filenames_buffer,
74         coverage_mappings_buffer,
75     );
76 }
77
78 struct CoverageMapGenerator {
79     filenames: FxIndexSet<CString>,
80 }
81
82 impl CoverageMapGenerator {
83     fn new() -> Self {
84         Self { filenames: FxIndexSet::default() }
85     }
86
87     /// Using the `expressions` and `counter_regions` collected for the current function, generate
88     /// the `mapping_regions` and `virtual_file_mapping`, and capture any new filenames. Then use
89     /// LLVM APIs to encode the `virtual_file_mapping`, `expressions`, and `mapping_regions` into
90     /// the given `coverage_mappings` byte buffer, compliant with the LLVM Coverage Mapping format.
91     fn write_coverage_mappings(
92         &mut self,
93         expressions: Vec<CounterExpression>,
94         counter_regions: impl Iterator<Item = (Counter, &'tcx Region<'tcx>)>,
95         coverage_mappings_buffer: &RustString,
96     ) {
97         let mut counter_regions = counter_regions.collect::<Vec<_>>();
98         if counter_regions.is_empty() {
99             return;
100         }
101
102         let mut virtual_file_mapping = Vec::new();
103         let mut mapping_regions = Vec::new();
104         let mut current_file_name = None;
105         let mut current_file_id = 0;
106
107         // Convert the list of (Counter, Region) pairs to an array of `CounterMappingRegion`, sorted
108         // by filename and position. Capture any new files to compute the `CounterMappingRegion`s
109         // `file_id` (indexing files referenced by the current function), and construct the
110         // function-specific `virtual_file_mapping` from `file_id` to its index in the module's
111         // `filenames` array.
112         counter_regions.sort_unstable_by_key(|(_counter, region)| *region);
113         for (counter, region) in counter_regions {
114             let Region { file_name, start_line, start_col, end_line, end_col } = *region;
115             let same_file = current_file_name.as_ref().map_or(false, |p| p == file_name);
116             if !same_file {
117                 if current_file_name.is_some() {
118                     current_file_id += 1;
119                 }
120                 current_file_name = Some(file_name.to_string());
121                 let c_filename =
122                     CString::new(file_name).expect("null error converting filename to C string");
123                 debug!("  file_id: {} = '{:?}'", current_file_id, c_filename);
124                 let (filenames_index, _) = self.filenames.insert_full(c_filename);
125                 virtual_file_mapping.push(filenames_index as u32);
126             }
127             mapping_regions.push(CounterMappingRegion::code_region(
128                 counter,
129                 current_file_id,
130                 start_line,
131                 start_col,
132                 end_line,
133                 end_col,
134             ));
135         }
136
137         // Encode and append the current function's coverage mapping data
138         coverageinfo::write_mapping_to_buffer(
139             virtual_file_mapping,
140             expressions,
141             mapping_regions,
142             coverage_mappings_buffer,
143         );
144     }
145
146     /// Generate and return the function record `Value`
147     fn make_function_record(
148         &mut self,
149         cx: &CodegenCx<'ll, 'tcx>,
150         mangled_function_name: String,
151         function_source_hash: u64,
152         mapping_data_size: usize,
153     ) -> &'ll llvm::Value {
154         let name_ref = coverageinfo::compute_hash(&mangled_function_name);
155         let name_ref_val = cx.const_u64(name_ref);
156         let mapping_data_size_val = cx.const_u32(mapping_data_size as u32);
157         let func_hash_val = cx.const_u64(function_source_hash);
158         cx.const_struct(
159             &[name_ref_val, mapping_data_size_val, func_hash_val],
160             /*packed=*/ true,
161         )
162     }
163
164     /// Combine the filenames and coverage mappings buffers, construct coverage map header and the
165     /// array of function records, and combine everything into the complete coverage map. Save the
166     /// coverage map data into the LLVM IR as a static global using a specific, well-known section
167     /// and name.
168     fn save_generated_coverage_map(
169         self,
170         cx: &CodegenCx<'ll, 'tcx>,
171         function_records: Vec<&'ll llvm::Value>,
172         filenames_buffer: Vec<u8>,
173         mut coverage_mappings_buffer: Vec<u8>,
174     ) {
175         // Concatenate the encoded filenames and encoded coverage mappings, and add additional zero
176         // bytes as-needed to ensure 8-byte alignment.
177         let mut coverage_size = coverage_mappings_buffer.len();
178         let filenames_size = filenames_buffer.len();
179         let remaining_bytes =
180             (filenames_size + coverage_size) % coverageinfo::COVMAP_VAR_ALIGN_BYTES;
181         if remaining_bytes > 0 {
182             let pad = coverageinfo::COVMAP_VAR_ALIGN_BYTES - remaining_bytes;
183             coverage_mappings_buffer.append(&mut [0].repeat(pad));
184             coverage_size += pad;
185         }
186         let filenames_and_coverage_mappings = [filenames_buffer, coverage_mappings_buffer].concat();
187         let filenames_and_coverage_mappings_val =
188             cx.const_bytes(&filenames_and_coverage_mappings[..]);
189
190         debug!(
191             "cov map: n_records = {}, filenames_size = {}, coverage_size = {}, 0-based version = {}",
192             function_records.len(),
193             filenames_size,
194             coverage_size,
195             coverageinfo::mapping_version()
196         );
197
198         // Create the coverage data header
199         let n_records_val = cx.const_u32(function_records.len() as u32);
200         let filenames_size_val = cx.const_u32(filenames_size as u32);
201         let coverage_size_val = cx.const_u32(coverage_size as u32);
202         let version_val = cx.const_u32(coverageinfo::mapping_version());
203         let cov_data_header_val = cx.const_struct(
204             &[n_records_val, filenames_size_val, coverage_size_val, version_val],
205             /*packed=*/ false,
206         );
207
208         // Create the function records array
209         let name_ref_from_u64 = cx.type_i64();
210         let mapping_data_size_from_u32 = cx.type_i32();
211         let func_hash_from_u64 = cx.type_i64();
212         let function_record_ty = cx.type_struct(
213             &[name_ref_from_u64, mapping_data_size_from_u32, func_hash_from_u64],
214             /*packed=*/ true,
215         );
216         let function_records_val = cx.const_array(function_record_ty, &function_records[..]);
217
218         // Create the complete LLVM coverage data value to add to the LLVM IR
219         let cov_data_val = cx.const_struct(
220             &[cov_data_header_val, function_records_val, filenames_and_coverage_mappings_val],
221             /*packed=*/ false,
222         );
223
224         // Save the coverage data value to LLVM IR
225         coverageinfo::save_map_to_mod(cx, cov_data_val);
226     }
227 }