use crate::dep_graph::{DepConstructor, DepNode, WorkProduct, WorkProductId};
use crate::ich::{NodeIdHashingMode, StableHashingContext};
use crate::ty::{subst::InternalSubsts, Instance, InstanceDef, SymbolName, TyCtxt};
use rustc_attr::InlineAttr;
use rustc_data_structures::base_n;
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
use rustc_hir::HirId;
use rustc_session::config::OptLevel;
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
use std::fmt;
use std::hash::Hash;
#[derive(PartialEq)]
pub enum InstantiationMode {
GloballyShared {
may_conflict: bool,
},
LocalCopy,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
pub enum MonoItem<'tcx> {
Fn(Instance<'tcx>),
Static(DefId),
GlobalAsm(HirId),
}
impl<'tcx> MonoItem<'tcx> {
pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize {
match *self {
MonoItem::Fn(instance) => {
tcx.instance_def_size_estimate(instance.def)
}
MonoItem::Static(_) | MonoItem::GlobalAsm(_) => 1,
}
}
pub fn is_generic_fn(&self) -> bool {
match *self {
MonoItem::Fn(ref instance) => instance.substs.non_erasable_generics().next().is_some(),
MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false,
}
}
pub fn symbol_name(&self, tcx: TyCtxt<'tcx>) -> SymbolName<'tcx> {
match *self {
MonoItem::Fn(instance) => tcx.symbol_name(instance),
MonoItem::Static(def_id) => tcx.symbol_name(Instance::mono(tcx, def_id)),
MonoItem::GlobalAsm(hir_id) => {
let def_id = tcx.hir().local_def_id(hir_id);
SymbolName::new(tcx, &format!("global_asm_{:?}", def_id))
}
}
}
pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
let generate_cgu_internal_copies = tcx
.sess
.opts
.debugging_opts
.inline_in_all_cgus
.unwrap_or_else(|| tcx.sess.opts.optimize != OptLevel::No)
&& !tcx.sess.link_dead_code();
match *self {
MonoItem::Fn(ref instance) => {
let entry_def_id = tcx.entry_fn(LOCAL_CRATE).map(|(id, _)| id);
if tcx.codegen_fn_attrs(instance.def_id()).contains_extern_indicator()
|| !instance.def.generates_cgu_internal_copy(tcx)
|| Some(instance.def_id()) == entry_def_id.map(LocalDefId::to_def_id)
{
return InstantiationMode::GloballyShared { may_conflict: false };
}
if generate_cgu_internal_copies {
return InstantiationMode::LocalCopy;
}
match tcx.codegen_fn_attrs(instance.def_id()).inline {
InlineAttr::Always => InstantiationMode::LocalCopy,
_ => InstantiationMode::GloballyShared { may_conflict: true },
}
}
MonoItem::Static(..) | MonoItem::GlobalAsm(..) => {
InstantiationMode::GloballyShared { may_conflict: false }
}
}
}
pub fn explicit_linkage(&self, tcx: TyCtxt<'tcx>) -> Option<Linkage> {
let def_id = match *self {
MonoItem::Fn(ref instance) => instance.def_id(),
MonoItem::Static(def_id) => def_id,
MonoItem::GlobalAsm(..) => return None,
};
let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
codegen_fn_attrs.linkage
}
pub fn is_instantiable(&self, tcx: TyCtxt<'tcx>) -> bool {
debug!("is_instantiable({:?})", self);
let (def_id, substs) = match *self {
MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
MonoItem::GlobalAsm(..) => return true,
};
!tcx.subst_and_check_impossible_predicates((def_id, &substs))
}
pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
match *self {
MonoItem::Fn(Instance { def, .. }) => {
def.def_id().as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
}
MonoItem::Static(def_id) => {
def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
}
MonoItem::GlobalAsm(hir_id) => Some(hir_id),
}
.map(|hir_id| tcx.hir().span(hir_id))
}
}
impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for MonoItem<'tcx> {
fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
::std::mem::discriminant(self).hash_stable(hcx, hasher);
match *self {
MonoItem::Fn(ref instance) => {
instance.hash_stable(hcx, hasher);
}
MonoItem::Static(def_id) => {
def_id.hash_stable(hcx, hasher);
}
MonoItem::GlobalAsm(node_id) => {
hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
node_id.hash_stable(hcx, hasher);
})
}
}
}
}
impl<'tcx> fmt::Display for MonoItem<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
MonoItem::Fn(instance) => write!(f, "fn {}", instance),
MonoItem::Static(def_id) => {
write!(f, "static {}", Instance::new(def_id, InternalSubsts::empty()))
}
MonoItem::GlobalAsm(..) => write!(f, "global_asm"),
}
}
}
pub struct CodegenUnit<'tcx> {
name: Symbol,
items: FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>,
size_estimate: Option<usize>,
}
#[derive(Copy, Clone, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
pub enum Linkage {
External,
AvailableExternally,
LinkOnceAny,
LinkOnceODR,
WeakAny,
WeakODR,
Appending,
Internal,
Private,
ExternalWeak,
Common,
}
#[derive(Copy, Clone, PartialEq, Debug, HashStable)]
pub enum Visibility {
Default,
Hidden,
Protected,
}
impl<'tcx> CodegenUnit<'tcx> {
pub fn new(name: Symbol) -> CodegenUnit<'tcx> {
CodegenUnit { name, items: Default::default(), size_estimate: None }
}
pub fn name(&self) -> Symbol {
self.name
}
pub fn set_name(&mut self, name: Symbol) {
self.name = name;
}
pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
&self.items
}
pub fn items_mut(&mut self) -> &mut FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
&mut self.items
}
pub fn mangle_name(human_readable_name: &str) -> String {
let mut hasher = StableHasher::new();
human_readable_name.hash(&mut hasher);
let hash: u128 = hasher.finish();
let hash = hash & ((1u128 << 80) - 1);
base_n::encode(hash, base_n::CASE_INSENSITIVE)
}
pub fn estimate_size(&mut self, tcx: TyCtxt<'tcx>) {
self.size_estimate = Some(self.items.keys().map(|mi| mi.size_estimate(tcx)).sum());
}
pub fn size_estimate(&self) -> usize {
self.size_estimate.expect("estimate_size must be called before getting a size_estimate")
}
pub fn modify_size_estimate(&mut self, delta: usize) {
assert!(self.size_estimate.is_some());
if let Some(size_estimate) = self.size_estimate {
self.size_estimate = Some(size_estimate + delta);
}
}
pub fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
self.items().contains_key(item)
}
pub fn work_product_id(&self) -> WorkProductId {
WorkProductId::from_cgu_name(&self.name().as_str())
}
pub fn work_product(&self, tcx: TyCtxt<'_>) -> WorkProduct {
let work_product_id = self.work_product_id();
tcx.dep_graph
.previous_work_product(&work_product_id)
.unwrap_or_else(|| panic!("Could not find work-product for CGU `{}`", self.name()))
}
pub fn items_in_deterministic_order(
&self,
tcx: TyCtxt<'tcx>,
) -> Vec<(MonoItem<'tcx>, (Linkage, Visibility))> {
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct ItemSortKey<'tcx>(Option<HirId>, SymbolName<'tcx>);
fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> {
ItemSortKey(
match item {
MonoItem::Fn(ref instance) => {
match instance.def {
InstanceDef::Item(def) => def
.did
.as_local()
.map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id)),
InstanceDef::VtableShim(..)
| InstanceDef::ReifyShim(..)
| InstanceDef::Intrinsic(..)
| InstanceDef::FnPtrShim(..)
| InstanceDef::Virtual(..)
| InstanceDef::ClosureOnceShim { .. }
| InstanceDef::DropGlue(..)
| InstanceDef::CloneShim(..) => None,
}
}
MonoItem::Static(def_id) => {
def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
}
MonoItem::GlobalAsm(hir_id) => Some(hir_id),
},
item.symbol_name(tcx),
)
}
let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
items
}
pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
DepConstructor::CompileCodegenUnit(tcx, self.name())
}
}
impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for CodegenUnit<'tcx> {
fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
let CodegenUnit {
ref items,
name,
size_estimate: _,
} = *self;
name.hash_stable(hcx, hasher);
let mut items: Vec<(Fingerprint, _)> = items
.iter()
.map(|(mono_item, &attrs)| {
let mut hasher = StableHasher::new();
mono_item.hash_stable(hcx, &mut hasher);
let mono_item_fingerprint = hasher.finish();
(mono_item_fingerprint, attrs)
})
.collect();
items.sort_unstable_by_key(|i| i.0);
items.hash_stable(hcx, hasher);
}
}
pub struct CodegenUnitNameBuilder<'tcx> {
tcx: TyCtxt<'tcx>,
cache: FxHashMap<CrateNum, String>,
}
impl CodegenUnitNameBuilder<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>) -> Self {
CodegenUnitNameBuilder { tcx, cache: Default::default() }
}
pub fn build_cgu_name<I, C, S>(
&mut self,
cnum: CrateNum,
components: I,
special_suffix: Option<S>,
) -> Symbol
where
I: IntoIterator<Item = C>,
C: fmt::Display,
S: fmt::Display,
{
let cgu_name = self.build_cgu_name_no_mangle(cnum, components, special_suffix);
if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
cgu_name
} else {
Symbol::intern(&CodegenUnit::mangle_name(&cgu_name.as_str()))
}
}
pub fn build_cgu_name_no_mangle<I, C, S>(
&mut self,
cnum: CrateNum,
components: I,
special_suffix: Option<S>,
) -> Symbol
where
I: IntoIterator<Item = C>,
C: fmt::Display,
S: fmt::Display,
{
use std::fmt::Write;
let mut cgu_name = String::with_capacity(64);
let tcx = self.tcx;
let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
let local_crate_id = if cnum != LOCAL_CRATE {
let local_crate_disambiguator = format!("{}", tcx.crate_disambiguator(LOCAL_CRATE));
format!("-in-{}.{}", tcx.crate_name(LOCAL_CRATE), &local_crate_disambiguator[0..8])
} else {
String::new()
};
let crate_disambiguator = tcx.crate_disambiguator(cnum).to_string();
format!("{}.{}{}", tcx.crate_name(cnum), &crate_disambiguator[0..8], local_crate_id)
});
write!(cgu_name, "{}", crate_prefix).unwrap();
for component in components {
write!(cgu_name, "-{}", component).unwrap();
}
if let Some(special_suffix) = special_suffix {
write!(cgu_name, ".{}", special_suffix).unwrap();
}
Symbol::intern(&cgu_name[..])
}
}