1 use crate::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
3 use syntax::symbol::InternedString;
4 use crate::ty::{Instance, TyCtxt};
5 use crate::util::nodemap::FxHashMap;
6 use rustc_data_structures::base_n;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasherResult,
9 use crate::ich::{Fingerprint, StableHashingContext, NodeIdHashingMode};
13 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
14 pub enum MonoItem<'tcx> {
20 impl<'tcx> MonoItem<'tcx> {
21 pub fn size_estimate<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> usize {
23 MonoItem::Fn(instance) => {
24 // Estimate the size of a function based on how many statements
26 tcx.instance_def_size_estimate(instance.def)
28 // Conservatively estimate the size of a static declaration
29 // or assembly to be 1.
31 MonoItem::GlobalAsm(_) => 1,
36 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for MonoItem<'tcx> {
37 fn hash_stable<W: StableHasherResult>(&self,
38 hcx: &mut StableHashingContext<'a>,
39 hasher: &mut StableHasher<W>) {
40 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
43 MonoItem::Fn(ref instance) => {
44 instance.hash_stable(hcx, hasher);
46 MonoItem::Static(def_id) => {
47 def_id.hash_stable(hcx, hasher);
49 MonoItem::GlobalAsm(node_id) => {
50 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
51 node_id.hash_stable(hcx, hasher);
58 pub struct CodegenUnit<'tcx> {
59 /// A name for this CGU. Incremental compilation requires that
60 /// name be unique amongst **all** crates. Therefore, it should
61 /// contain something unique to this crate (e.g., a module path)
62 /// as well as the crate name and disambiguator.
64 items: FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>,
65 size_estimate: Option<usize>,
68 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
83 impl_stable_hash_for!(enum self::Linkage {
97 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
104 impl_stable_hash_for!(enum self::Visibility {
110 impl<'tcx> CodegenUnit<'tcx> {
111 pub fn new(name: InternedString) -> CodegenUnit<'tcx> {
114 items: Default::default(),
119 pub fn name(&self) -> &InternedString {
123 pub fn set_name(&mut self, name: InternedString) {
127 pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
131 pub fn items_mut(&mut self)
132 -> &mut FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>
137 pub fn mangle_name(human_readable_name: &str) -> String {
138 // We generate a 80 bit hash from the name. This should be enough to
139 // avoid collisions and is still reasonably short for filenames.
140 let mut hasher = StableHasher::new();
141 human_readable_name.hash(&mut hasher);
142 let hash: u128 = hasher.finish();
143 let hash = hash & ((1u128 << 80) - 1);
144 base_n::encode(hash, base_n::CASE_INSENSITIVE)
147 pub fn estimate_size<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>) {
148 // Estimate the size of a codegen unit as (approximately) the number of MIR
149 // statements it corresponds to.
150 self.size_estimate = Some(self.items.keys().map(|mi| mi.size_estimate(tcx)).sum());
153 pub fn size_estimate(&self) -> usize {
154 // Should only be called if `estimate_size` has previously been called.
155 self.size_estimate.expect("estimate_size must be called before getting a size_estimate")
158 pub fn modify_size_estimate(&mut self, delta: usize) {
159 assert!(self.size_estimate.is_some());
160 if let Some(size_estimate) = self.size_estimate {
161 self.size_estimate = Some(size_estimate + delta);
166 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for CodegenUnit<'tcx> {
167 fn hash_stable<W: StableHasherResult>(&self,
168 hcx: &mut StableHashingContext<'a>,
169 hasher: &mut StableHasher<W>) {
173 // The size estimate is not relevant to the hash
177 name.hash_stable(hcx, hasher);
179 let mut items: Vec<(Fingerprint, _)> = items.iter().map(|(mono_item, &attrs)| {
180 let mut hasher = StableHasher::new();
181 mono_item.hash_stable(hcx, &mut hasher);
182 let mono_item_fingerprint = hasher.finish();
183 (mono_item_fingerprint, attrs)
186 items.sort_unstable_by_key(|i| i.0);
187 items.hash_stable(hcx, hasher);
191 #[derive(Clone, Default)]
193 pub n_glues_created: usize,
194 pub n_null_glues: usize,
195 pub n_real_glues: usize,
197 pub n_inlines: usize,
198 pub n_closures: usize,
199 pub n_llvm_insns: usize,
200 pub llvm_insns: FxHashMap<String, usize>,
201 // (ident, llvm-instructions)
202 pub fn_stats: Vec<(String, usize)>,
205 impl_stable_hash_for!(struct self::Stats {
218 pub fn extend(&mut self, stats: Stats) {
219 self.n_glues_created += stats.n_glues_created;
220 self.n_null_glues += stats.n_null_glues;
221 self.n_real_glues += stats.n_real_glues;
222 self.n_fns += stats.n_fns;
223 self.n_inlines += stats.n_inlines;
224 self.n_closures += stats.n_closures;
225 self.n_llvm_insns += stats.n_llvm_insns;
227 for (k, v) in stats.llvm_insns {
228 *self.llvm_insns.entry(k).or_insert(0) += v;
230 self.fn_stats.extend(stats.fn_stats);
234 pub struct CodegenUnitNameBuilder<'a, 'gcx: 'tcx, 'tcx: 'a> {
235 tcx: TyCtxt<'a, 'gcx, 'tcx>,
236 cache: FxHashMap<CrateNum, String>,
239 impl<'a, 'gcx: 'tcx, 'tcx: 'a> CodegenUnitNameBuilder<'a, 'gcx, 'tcx> {
241 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
242 CodegenUnitNameBuilder {
244 cache: Default::default(),
248 /// CGU names should fulfill the following requirements:
249 /// - They should be able to act as a file name on any kind of file system
250 /// - They should not collide with other CGU names, even for different versions
251 /// of the same crate.
253 /// Consequently, we don't use special characters except for '.' and '-' and we
254 /// prefix each name with the crate-name and crate-disambiguator.
256 /// This function will build CGU names of the form:
259 /// <crate-name>.<crate-disambiguator>[-in-<local-crate-id>](-<component>)*[.<special-suffix>]
260 /// <local-crate-id> = <local-crate-name>.<local-crate-disambiguator>
263 /// The '.' before `<special-suffix>` makes sure that names with a special
264 /// suffix can never collide with a name built out of regular Rust
265 /// identifiers (e.g., module paths).
266 pub fn build_cgu_name<I, C, S>(&mut self,
269 special_suffix: Option<S>)
271 where I: IntoIterator<Item=C>,
275 let cgu_name = self.build_cgu_name_no_mangle(cnum,
279 if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
282 let cgu_name = &cgu_name.as_str()[..];
283 InternedString::intern(&CodegenUnit::mangle_name(cgu_name))
287 /// Same as `CodegenUnit::build_cgu_name()` but will never mangle the
289 pub fn build_cgu_name_no_mangle<I, C, S>(&mut self,
292 special_suffix: Option<S>)
294 where I: IntoIterator<Item=C>,
300 let mut cgu_name = String::with_capacity(64);
302 // Start out with the crate name and disambiguator
304 let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
305 // Whenever the cnum is not LOCAL_CRATE we also mix in the
306 // local crate's ID. Otherwise there can be collisions between CGUs
307 // instantiating stuff for upstream crates.
308 let local_crate_id = if cnum != LOCAL_CRATE {
309 let local_crate_disambiguator =
310 format!("{}", tcx.crate_disambiguator(LOCAL_CRATE));
312 tcx.crate_name(LOCAL_CRATE),
313 &local_crate_disambiguator[0 .. 8])
318 let crate_disambiguator = tcx.crate_disambiguator(cnum).to_string();
319 // Using a shortened disambiguator of about 40 bits
321 tcx.crate_name(cnum),
322 &crate_disambiguator[0 .. 8],
326 write!(cgu_name, "{}", crate_prefix).unwrap();
328 // Add the components
329 for component in components {
330 write!(cgu_name, "-{}", component).unwrap();
333 if let Some(special_suffix) = special_suffix {
334 // We add a dot in here so it cannot clash with anything in a regular
336 write!(cgu_name, ".{}", special_suffix).unwrap();
339 InternedString::intern(&cgu_name[..])