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::mir::interpret::{ConstValue, Scalar};
5 use rustc_middle::ty::print::{PrettyPrinter, Print, Printer};
6 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
7 use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable};
8 use rustc_middle::util::common::record_time;
12 use std::fmt::{self, Write};
13 use std::mem::{self, discriminant};
15 pub(super) fn mangle<'tcx>(
17 instance: Instance<'tcx>,
18 instantiating_crate: Option<CrateNum>,
20 let def_id = instance.def_id();
22 // We want to compute the "type" of this item. Unfortunately, some
23 // kinds of items (e.g., closures) don't have an entry in the
24 // item-type array. So walk back up the find the closest parent
25 // that DOES have an entry.
26 let mut ty_def_id = def_id;
29 let key = tcx.def_key(ty_def_id);
30 match key.disambiguated_data.data {
31 DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
32 instance_ty = tcx.type_of(ty_def_id);
36 // if we're making a symbol for something, there ought
37 // to be a value or type-def or something in there
39 ty_def_id.index = key.parent.unwrap_or_else(|| {
41 "finding type for {:?}, encountered def-id {:?} with no \
51 // Erase regions because they may not be deterministic when hashed
52 // and should not matter anyhow.
53 let instance_ty = tcx.erase_regions(instance_ty);
55 let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
57 let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false };
61 if let ty::InstanceDef::DropGlue(_, _) = instance.def {
62 // Add the name of the dropped type to the symbol name
70 if let ty::InstanceDef::VtableShim(..) = instance.def {
71 let _ = printer.write_str("{{vtable-shim}}");
74 if let ty::InstanceDef::ReifyShim(..) = instance.def {
75 let _ = printer.write_str("{{reify-shim}}");
78 printer.path.finish(hash)
81 fn get_symbol_hash<'tcx>(
84 // instance this name will be for
85 instance: Instance<'tcx>,
87 // type of the item, without any generic
88 // parameters substituted; this is
89 // included in the hash as a kind of
93 instantiating_crate: Option<CrateNum>,
95 let def_id = instance.def_id();
96 let substs = instance.substs;
97 debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
99 let mut hasher = StableHasher::new();
100 let mut hcx = tcx.create_stable_hashing_context();
102 record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
103 // the main symbol name is not necessarily unique; hash in the
104 // compiler's internal def-path, guaranteeing each symbol has a
106 tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
108 // Include the main item-type. Note that, in this case, the
109 // assertions about `needs_subst` may not hold, but this item-type
110 // ought to be the same for every reference anyway.
111 assert!(!item_type.has_erasable_regions());
112 hcx.while_hashing_spans(false, |hcx| {
113 item_type.hash_stable(hcx, &mut hasher);
115 // If this is a function, we hash the signature as well.
116 // This is not *strictly* needed, but it may help in some
117 // situations, see the `run-make/a-b-a-linker-guard` test.
118 if let ty::FnDef(..) = item_type.kind() {
119 item_type.fn_sig(tcx).hash_stable(hcx, &mut hasher);
122 // also include any type parameters (for generic items)
123 substs.hash_stable(hcx, &mut hasher);
125 if let Some(instantiating_crate) = instantiating_crate {
126 tcx.def_path_hash(instantiating_crate.as_def_id())
128 .hash_stable(hcx, &mut hasher);
131 // We want to avoid accidental collision between different types of instances.
132 // Especially, `VtableShim`s and `ReifyShim`s may overlap with their original
133 // instances without this.
134 discriminant(&instance.def).hash_stable(hcx, &mut hasher);
138 // 64 bits should be enough to avoid collisions.
139 hasher.finish::<u64>()
142 // Follow C++ namespace-mangling style, see
143 // https://en.wikipedia.org/wiki/Name_mangling for more info.
145 // It turns out that on macOS you can actually have arbitrary symbols in
146 // function names (at least when given to LLVM), but this is not possible
147 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
148 // we won't need to do this name mangling. The problem with name mangling is
149 // that it seriously limits the available characters. For example we can't
150 // have things like &T in symbol names when one would theoretically
151 // want them for things like impls of traits on that type.
153 // To be able to work on all platforms and get *some* reasonable output, we
154 // use C++ name-mangling.
164 SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
165 result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
169 fn finalize_pending_component(&mut self) {
170 if !self.temp_buf.is_empty() {
171 let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
172 self.temp_buf.clear();
176 fn finish(mut self, hash: u64) -> String {
177 self.finalize_pending_component();
178 // E = end name-sequence
179 let _ = write!(self.result, "17h{:016x}E", hash);
184 struct SymbolPrinter<'tcx> {
188 // When `true`, `finalize_pending_component` isn't used.
189 // This is needed when recursing into `path_qualified`,
190 // or `path_generic_args`, as any nested paths are
191 // logically within one component.
192 keep_within_component: bool,
195 // HACK(eddyb) this relies on using the `fmt` interface to get
196 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
197 // symbol names should have their own printing machinery.
199 impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
200 type Error = fmt::Error;
205 type DynExistential = Self;
208 fn tcx(&self) -> TyCtxt<'tcx> {
212 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
216 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
218 // Print all nominal types as paths (unlike `pretty_print_type`).
219 ty::FnDef(def_id, substs)
220 | ty::Opaque(def_id, substs)
221 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
222 | ty::Closure(def_id, substs)
223 | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
225 // The `pretty_print_type` formatting of array size depends on
226 // -Zverbose flag, so we cannot reuse it here.
227 ty::Array(ty, size) => {
228 self.write_str("[")?;
229 self = self.print_type(ty)?;
230 self.write_str("; ")?;
231 if let Some(size) = size.val().try_to_bits(self.tcx().data_layout.pointer_size) {
232 write!(self, "{}", size)?
233 } else if let ty::ConstKind::Param(param) = size.val() {
234 self = param.print(self)?
238 self.write_str("]")?;
242 _ => self.pretty_print_type(ty),
246 fn print_dyn_existential(
248 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
249 ) -> Result<Self::DynExistential, Self::Error> {
250 let mut first = true;
251 for p in predicates {
256 self = p.print(self)?;
261 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
262 // only print integers
263 match (ct.val(), ct.ty().kind()) {
265 ty::ConstKind::Value(ConstValue::Scalar(Scalar::Int(scalar))),
266 ty::Int(_) | ty::Uint(_),
268 // The `pretty_print_const` formatting depends on -Zverbose
269 // flag, so we cannot reuse it here.
270 let signed = matches!(ct.ty().kind(), ty::Int(_));
274 ty::ConstInt::new(scalar, signed, ct.ty().is_ptr_sized_integral())
277 _ => self.write_str("_")?,
282 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
283 self.write_str(self.tcx.crate_name(cnum).as_str())?;
289 trait_ref: Option<ty::TraitRef<'tcx>>,
290 ) -> Result<Self::Path, Self::Error> {
291 // Similar to `pretty_path_qualified`, but for the other
292 // types that are printed as paths (see `print_type` above).
293 match self_ty.kind() {
299 if trait_ref.is_none() =>
301 self.print_type(self_ty)
304 _ => self.pretty_path_qualified(self_ty, trait_ref),
310 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
311 _disambiguated_data: &DisambiguatedDefPathData,
313 trait_ref: Option<ty::TraitRef<'tcx>>,
314 ) -> Result<Self::Path, Self::Error> {
315 self.pretty_path_append_impl(
317 cx = print_prefix(cx)?;
319 if cx.keep_within_component {
320 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
323 cx.path.finalize_pending_component();
334 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
335 disambiguated_data: &DisambiguatedDefPathData,
336 ) -> Result<Self::Path, Self::Error> {
337 self = print_prefix(self)?;
339 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
340 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
344 if self.keep_within_component {
345 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
346 self.write_str("::")?;
348 self.path.finalize_pending_component();
351 write!(self, "{}", disambiguated_data.data)?;
355 fn path_generic_args(
357 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
358 args: &[GenericArg<'tcx>],
359 ) -> Result<Self::Path, Self::Error> {
360 self = print_prefix(self)?;
363 args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
365 if args.clone().next().is_some() {
366 self.generic_delimiters(|cx| cx.comma_sep(args))
373 impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
374 fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
377 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
379 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
381 if let Some(first) = elems.next() {
382 self = first.print(self)?;
384 self.write_str(",")?;
385 self = elem.print(self)?;
391 fn generic_delimiters(
393 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
394 ) -> Result<Self, Self::Error> {
397 let kept_within_component = mem::replace(&mut self.keep_within_component, true);
399 self.keep_within_component = kept_within_component;
407 impl fmt::Write for SymbolPrinter<'_> {
408 fn write_str(&mut self, s: &str) -> fmt::Result {
409 // Name sanitation. LLVM will happily accept identifiers with weird names, but
411 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
412 // NVPTX assembly has more strict naming rules than gas, so additionally, dots
413 // are replaced with '$' there.
416 if self.path.temp_buf.is_empty() {
418 'a'..='z' | 'A'..='Z' | '_' => {}
420 // Underscore-qualify anything that didn't start as an ident.
421 self.path.temp_buf.push('_');
426 // Escape these with $ sequences
427 '@' => self.path.temp_buf.push_str("$SP$"),
428 '*' => self.path.temp_buf.push_str("$BP$"),
429 '&' => self.path.temp_buf.push_str("$RF$"),
430 '<' => self.path.temp_buf.push_str("$LT$"),
431 '>' => self.path.temp_buf.push_str("$GT$"),
432 '(' => self.path.temp_buf.push_str("$LP$"),
433 ')' => self.path.temp_buf.push_str("$RP$"),
434 ',' => self.path.temp_buf.push_str("$C$"),
436 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
437 // NVPTX doesn't support these characters in symbol names.
438 self.path.temp_buf.push('$')
441 // '.' doesn't occur in types and functions, so reuse it
443 '-' | ':' => self.path.temp_buf.push('.'),
445 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
446 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
448 // These are legal symbols
449 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
452 self.path.temp_buf.push('$');
453 for c in c.escape_unicode().skip(1) {
456 '}' => self.path.temp_buf.push('$'),
457 c => self.path.temp_buf.push(c),