1 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
2 use rustc_hir::def_id::CrateNum;
3 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
4 use rustc_middle::ty::print::{PrettyPrinter, Print, Printer};
5 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
6 use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeVisitable};
7 use rustc_middle::util::common::record_time;
9 use std::fmt::{self, Write};
10 use std::mem::{self, discriminant};
12 pub(super) fn mangle<'tcx>(
14 instance: Instance<'tcx>,
15 instantiating_crate: Option<CrateNum>,
17 let def_id = instance.def_id();
19 // We want to compute the "type" of this item. Unfortunately, some
20 // kinds of items (e.g., closures) don't have an entry in the
21 // item-type array. So walk back up the find the closest parent
22 // that DOES have an entry.
23 let mut ty_def_id = def_id;
26 let key = tcx.def_key(ty_def_id);
27 match key.disambiguated_data.data {
28 DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
29 instance_ty = tcx.type_of(ty_def_id);
34 // if we're making a symbol for something, there ought
35 // to be a value or type-def or something in there
37 ty_def_id.index = key.parent.unwrap_or_else(|| {
39 "finding type for {:?}, encountered def-id {:?} with no \
49 // Erase regions because they may not be deterministic when hashed
50 // and should not matter anyhow.
51 let instance_ty = tcx.erase_regions(instance_ty);
53 let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
55 let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false };
59 if let ty::InstanceDef::DropGlue(_, _) = instance.def {
60 // Add the name of the dropped type to the symbol name
68 if let ty::InstanceDef::VTableShim(..) = instance.def {
69 let _ = printer.write_str("{{vtable-shim}}");
72 if let ty::InstanceDef::ReifyShim(..) = instance.def {
73 let _ = printer.write_str("{{reify-shim}}");
76 printer.path.finish(hash)
79 fn get_symbol_hash<'tcx>(
82 // instance this name will be for
83 instance: Instance<'tcx>,
85 // type of the item, without any generic
86 // parameters substituted; this is
87 // included in the hash as a kind of
91 instantiating_crate: Option<CrateNum>,
93 let def_id = instance.def_id();
94 let substs = instance.substs;
95 debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
97 tcx.with_stable_hashing_context(|mut hcx| {
98 let mut hasher = StableHasher::new();
100 record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
101 // the main symbol name is not necessarily unique; hash in the
102 // compiler's internal def-path, guaranteeing each symbol has a
104 tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
106 // Include the main item-type. Note that, in this case, the
107 // assertions about `needs_subst` may not hold, but this item-type
108 // ought to be the same for every reference anyway.
109 assert!(!item_type.has_erasable_regions());
110 hcx.while_hashing_spans(false, |hcx| {
111 item_type.hash_stable(hcx, &mut hasher);
113 // If this is a function, we hash the signature as well.
114 // This is not *strictly* needed, but it may help in some
115 // situations, see the `run-make/a-b-a-linker-guard` test.
116 if let ty::FnDef(..) = item_type.kind() {
117 item_type.fn_sig(tcx).hash_stable(hcx, &mut hasher);
120 // also include any type parameters (for generic items)
121 substs.hash_stable(hcx, &mut hasher);
123 if let Some(instantiating_crate) = instantiating_crate {
124 tcx.def_path_hash(instantiating_crate.as_def_id())
126 .hash_stable(hcx, &mut hasher);
129 // We want to avoid accidental collision between different types of instances.
130 // Especially, `VTableShim`s and `ReifyShim`s may overlap with their original
131 // instances without this.
132 discriminant(&instance.def).hash_stable(hcx, &mut hasher);
136 // 64 bits should be enough to avoid collisions.
137 hasher.finish::<u64>()
141 // Follow C++ namespace-mangling style, see
142 // https://en.wikipedia.org/wiki/Name_mangling for more info.
144 // It turns out that on macOS you can actually have arbitrary symbols in
145 // function names (at least when given to LLVM), but this is not possible
146 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
147 // we won't need to do this name mangling. The problem with name mangling is
148 // that it seriously limits the available characters. For example we can't
149 // have things like &T in symbol names when one would theoretically
150 // want them for things like impls of traits on that type.
152 // To be able to work on all platforms and get *some* reasonable output, we
153 // use C++ name-mangling.
163 SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
164 result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
168 fn finalize_pending_component(&mut self) {
169 if !self.temp_buf.is_empty() {
170 let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
171 self.temp_buf.clear();
175 fn finish(mut self, hash: u64) -> String {
176 self.finalize_pending_component();
177 // E = end name-sequence
178 let _ = write!(self.result, "17h{:016x}E", hash);
183 struct SymbolPrinter<'tcx> {
187 // When `true`, `finalize_pending_component` isn't used.
188 // This is needed when recursing into `path_qualified`,
189 // or `path_generic_args`, as any nested paths are
190 // logically within one component.
191 keep_within_component: bool,
194 // HACK(eddyb) this relies on using the `fmt` interface to get
195 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
196 // symbol names should have their own printing machinery.
198 impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
199 type Error = fmt::Error;
204 type DynExistential = Self;
207 fn tcx(&self) -> TyCtxt<'tcx> {
211 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
215 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
217 // Print all nominal types as paths (unlike `pretty_print_type`).
218 ty::FnDef(def_id, substs)
219 | ty::Alias(_, ty::AliasTy { def_id, substs, .. })
220 | ty::Closure(def_id, substs)
221 | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
223 // The `pretty_print_type` formatting of array size depends on
224 // -Zverbose flag, so we cannot reuse it here.
225 ty::Array(ty, size) => {
226 self.write_str("[")?;
227 self = self.print_type(ty)?;
228 self.write_str("; ")?;
229 if let Some(size) = size.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
230 write!(self, "{}", size)?
231 } else if let ty::ConstKind::Param(param) = size.kind() {
232 self = param.print(self)?
236 self.write_str("]")?;
240 _ => self.pretty_print_type(ty),
244 fn print_dyn_existential(
246 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
247 ) -> Result<Self::DynExistential, Self::Error> {
248 let mut first = true;
249 for p in predicates {
254 self = p.print(self)?;
259 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
260 // only print integers
261 match (ct.kind(), ct.ty().kind()) {
262 (ty::ConstKind::Value(ty::ValTree::Leaf(scalar)), ty::Int(_) | ty::Uint(_)) => {
263 // The `pretty_print_const` formatting depends on -Zverbose
264 // flag, so we cannot reuse it here.
265 let signed = matches!(ct.ty().kind(), ty::Int(_));
269 ty::ConstInt::new(scalar, signed, ct.ty().is_ptr_sized_integral())
272 _ => self.write_str("_")?,
277 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
278 self.write_str(self.tcx.crate_name(cnum).as_str())?;
284 trait_ref: Option<ty::TraitRef<'tcx>>,
285 ) -> Result<Self::Path, Self::Error> {
286 // Similar to `pretty_path_qualified`, but for the other
287 // types that are printed as paths (see `print_type` above).
288 match self_ty.kind() {
289 ty::FnDef(..) | ty::Alias(..) | ty::Closure(..) | ty::Generator(..)
290 if trait_ref.is_none() =>
292 self.print_type(self_ty)
295 _ => self.pretty_path_qualified(self_ty, trait_ref),
301 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
302 _disambiguated_data: &DisambiguatedDefPathData,
304 trait_ref: Option<ty::TraitRef<'tcx>>,
305 ) -> Result<Self::Path, Self::Error> {
306 self.pretty_path_append_impl(
308 cx = print_prefix(cx)?;
310 if cx.keep_within_component {
311 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
314 cx.path.finalize_pending_component();
325 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
326 disambiguated_data: &DisambiguatedDefPathData,
327 ) -> Result<Self::Path, Self::Error> {
328 self = print_prefix(self)?;
330 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
331 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
335 if self.keep_within_component {
336 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
337 self.write_str("::")?;
339 self.path.finalize_pending_component();
342 write!(self, "{}", disambiguated_data.data)?;
346 fn path_generic_args(
348 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
349 args: &[GenericArg<'tcx>],
350 ) -> Result<Self::Path, Self::Error> {
351 self = print_prefix(self)?;
354 args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
356 if args.clone().next().is_some() {
357 self.generic_delimiters(|cx| cx.comma_sep(args))
364 impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
365 fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
368 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
370 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
372 if let Some(first) = elems.next() {
373 self = first.print(self)?;
375 self.write_str(",")?;
376 self = elem.print(self)?;
382 fn generic_delimiters(
384 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
385 ) -> Result<Self, Self::Error> {
388 let kept_within_component = mem::replace(&mut self.keep_within_component, true);
390 self.keep_within_component = kept_within_component;
398 impl fmt::Write for SymbolPrinter<'_> {
399 fn write_str(&mut self, s: &str) -> fmt::Result {
400 // Name sanitation. LLVM will happily accept identifiers with weird names, but
402 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
403 // NVPTX assembly has more strict naming rules than gas, so additionally, dots
404 // are replaced with '$' there.
407 if self.path.temp_buf.is_empty() {
409 'a'..='z' | 'A'..='Z' | '_' => {}
411 // Underscore-qualify anything that didn't start as an ident.
412 self.path.temp_buf.push('_');
417 // Escape these with $ sequences
418 '@' => self.path.temp_buf.push_str("$SP$"),
419 '*' => self.path.temp_buf.push_str("$BP$"),
420 '&' => self.path.temp_buf.push_str("$RF$"),
421 '<' => self.path.temp_buf.push_str("$LT$"),
422 '>' => self.path.temp_buf.push_str("$GT$"),
423 '(' => self.path.temp_buf.push_str("$LP$"),
424 ')' => self.path.temp_buf.push_str("$RP$"),
425 ',' => self.path.temp_buf.push_str("$C$"),
427 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
428 // NVPTX doesn't support these characters in symbol names.
429 self.path.temp_buf.push('$')
432 // '.' doesn't occur in types and functions, so reuse it
434 '-' | ':' => self.path.temp_buf.push('.'),
436 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
437 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
439 // These are legal symbols
440 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
443 self.path.temp_buf.push('$');
444 for c in c.escape_unicode().skip(1) {
447 '}' => self.path.temp_buf.push('$'),
448 c => self.path.temp_buf.push(c),