]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_symbol_mangling/src/legacy.rs
Rollup merge of #95376 - WaffleLapkin:drain_keep_rest, r=dtolnay
[rust.git] / compiler / rustc_symbol_mangling / src / legacy.rs
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;
8
9 use tracing::debug;
10
11 use std::fmt::{self, Write};
12 use std::mem::{self, discriminant};
13
14 pub(super) fn mangle<'tcx>(
15     tcx: TyCtxt<'tcx>,
16     instance: Instance<'tcx>,
17     instantiating_crate: Option<CrateNum>,
18 ) -> String {
19     let def_id = instance.def_id();
20
21     // We want to compute the "type" of this item. Unfortunately, some
22     // kinds of items (e.g., closures) don't have an entry in the
23     // item-type array. So walk back up the find the closest parent
24     // that DOES have an entry.
25     let mut ty_def_id = def_id;
26     let instance_ty;
27     loop {
28         let key = tcx.def_key(ty_def_id);
29         match key.disambiguated_data.data {
30             DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
31                 instance_ty = tcx.type_of(ty_def_id);
32                 debug!(?instance_ty);
33                 break;
34             }
35             _ => {
36                 // if we're making a symbol for something, there ought
37                 // to be a value or type-def or something in there
38                 // *somewhere*
39                 ty_def_id.index = key.parent.unwrap_or_else(|| {
40                     bug!(
41                         "finding type for {:?}, encountered def-id {:?} with no \
42                          parent",
43                         def_id,
44                         ty_def_id
45                     );
46                 });
47             }
48         }
49     }
50
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);
54
55     let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
56
57     let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false };
58     printer
59         .print_def_path(
60             def_id,
61             if let ty::InstanceDef::DropGlue(_, _) = instance.def {
62                 // Add the name of the dropped type to the symbol name
63                 &*instance.substs
64             } else {
65                 &[]
66             },
67         )
68         .unwrap();
69
70     if let ty::InstanceDef::VTableShim(..) = instance.def {
71         let _ = printer.write_str("{{vtable-shim}}");
72     }
73
74     if let ty::InstanceDef::ReifyShim(..) = instance.def {
75         let _ = printer.write_str("{{reify-shim}}");
76     }
77
78     printer.path.finish(hash)
79 }
80
81 fn get_symbol_hash<'tcx>(
82     tcx: TyCtxt<'tcx>,
83
84     // instance this name will be for
85     instance: Instance<'tcx>,
86
87     // type of the item, without any generic
88     // parameters substituted; this is
89     // included in the hash as a kind of
90     // safeguard.
91     item_type: Ty<'tcx>,
92
93     instantiating_crate: Option<CrateNum>,
94 ) -> u64 {
95     let def_id = instance.def_id();
96     let substs = instance.substs;
97     debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
98
99     tcx.with_stable_hashing_context(|mut hcx| {
100         let mut hasher = StableHasher::new();
101
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
105             // truly unique path
106             tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
107
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);
114
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);
120                 }
121
122                 // also include any type parameters (for generic items)
123                 substs.hash_stable(hcx, &mut hasher);
124
125                 if let Some(instantiating_crate) = instantiating_crate {
126                     tcx.def_path_hash(instantiating_crate.as_def_id())
127                         .stable_crate_id()
128                         .hash_stable(hcx, &mut hasher);
129                 }
130
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);
135             });
136         });
137
138         // 64 bits should be enough to avoid collisions.
139         hasher.finish::<u64>()
140     })
141 }
142
143 // Follow C++ namespace-mangling style, see
144 // https://en.wikipedia.org/wiki/Name_mangling for more info.
145 //
146 // It turns out that on macOS you can actually have arbitrary symbols in
147 // function names (at least when given to LLVM), but this is not possible
148 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
149 // we won't need to do this name mangling. The problem with name mangling is
150 // that it seriously limits the available characters. For example we can't
151 // have things like &T in symbol names when one would theoretically
152 // want them for things like impls of traits on that type.
153 //
154 // To be able to work on all platforms and get *some* reasonable output, we
155 // use C++ name-mangling.
156 #[derive(Debug)]
157 struct SymbolPath {
158     result: String,
159     temp_buf: String,
160 }
161
162 impl SymbolPath {
163     fn new() -> Self {
164         let mut result =
165             SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
166         result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
167         result
168     }
169
170     fn finalize_pending_component(&mut self) {
171         if !self.temp_buf.is_empty() {
172             let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
173             self.temp_buf.clear();
174         }
175     }
176
177     fn finish(mut self, hash: u64) -> String {
178         self.finalize_pending_component();
179         // E = end name-sequence
180         let _ = write!(self.result, "17h{:016x}E", hash);
181         self.result
182     }
183 }
184
185 struct SymbolPrinter<'tcx> {
186     tcx: TyCtxt<'tcx>,
187     path: SymbolPath,
188
189     // When `true`, `finalize_pending_component` isn't used.
190     // This is needed when recursing into `path_qualified`,
191     // or `path_generic_args`, as any nested paths are
192     // logically within one component.
193     keep_within_component: bool,
194 }
195
196 // HACK(eddyb) this relies on using the `fmt` interface to get
197 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
198 // symbol names should have their own printing machinery.
199
200 impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
201     type Error = fmt::Error;
202
203     type Path = Self;
204     type Region = Self;
205     type Type = Self;
206     type DynExistential = Self;
207     type Const = Self;
208
209     fn tcx(&self) -> TyCtxt<'tcx> {
210         self.tcx
211     }
212
213     fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
214         Ok(self)
215     }
216
217     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
218         match *ty.kind() {
219             // Print all nominal types as paths (unlike `pretty_print_type`).
220             ty::FnDef(def_id, substs)
221             | ty::Opaque(def_id, substs)
222             | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
223             | ty::Closure(def_id, substs)
224             | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
225
226             // The `pretty_print_type` formatting of array size depends on
227             // -Zverbose flag, so we cannot reuse it here.
228             ty::Array(ty, size) => {
229                 self.write_str("[")?;
230                 self = self.print_type(ty)?;
231                 self.write_str("; ")?;
232                 if let Some(size) = size.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
233                     write!(self, "{}", size)?
234                 } else if let ty::ConstKind::Param(param) = size.kind() {
235                     self = param.print(self)?
236                 } else {
237                     self.write_str("_")?
238                 }
239                 self.write_str("]")?;
240                 Ok(self)
241             }
242
243             _ => self.pretty_print_type(ty),
244         }
245     }
246
247     fn print_dyn_existential(
248         mut self,
249         predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
250     ) -> Result<Self::DynExistential, Self::Error> {
251         let mut first = true;
252         for p in predicates {
253             if !first {
254                 write!(self, "+")?;
255             }
256             first = false;
257             self = p.print(self)?;
258         }
259         Ok(self)
260     }
261
262     fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
263         // only print integers
264         match (ct.kind(), ct.ty().kind()) {
265             (ty::ConstKind::Value(ty::ValTree::Leaf(scalar)), ty::Int(_) | ty::Uint(_)) => {
266                 // The `pretty_print_const` formatting depends on -Zverbose
267                 // flag, so we cannot reuse it here.
268                 let signed = matches!(ct.ty().kind(), ty::Int(_));
269                 write!(
270                     self,
271                     "{:#?}",
272                     ty::ConstInt::new(scalar, signed, ct.ty().is_ptr_sized_integral())
273                 )?;
274             }
275             _ => self.write_str("_")?,
276         }
277         Ok(self)
278     }
279
280     fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
281         self.write_str(self.tcx.crate_name(cnum).as_str())?;
282         Ok(self)
283     }
284     fn path_qualified(
285         self,
286         self_ty: Ty<'tcx>,
287         trait_ref: Option<ty::TraitRef<'tcx>>,
288     ) -> Result<Self::Path, Self::Error> {
289         // Similar to `pretty_path_qualified`, but for the other
290         // types that are printed as paths (see `print_type` above).
291         match self_ty.kind() {
292             ty::FnDef(..)
293             | ty::Opaque(..)
294             | ty::Projection(_)
295             | ty::Closure(..)
296             | ty::Generator(..)
297                 if trait_ref.is_none() =>
298             {
299                 self.print_type(self_ty)
300             }
301
302             _ => self.pretty_path_qualified(self_ty, trait_ref),
303         }
304     }
305
306     fn path_append_impl(
307         self,
308         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
309         _disambiguated_data: &DisambiguatedDefPathData,
310         self_ty: Ty<'tcx>,
311         trait_ref: Option<ty::TraitRef<'tcx>>,
312     ) -> Result<Self::Path, Self::Error> {
313         self.pretty_path_append_impl(
314             |mut cx| {
315                 cx = print_prefix(cx)?;
316
317                 if cx.keep_within_component {
318                     // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
319                     cx.write_str("::")?;
320                 } else {
321                     cx.path.finalize_pending_component();
322                 }
323
324                 Ok(cx)
325             },
326             self_ty,
327             trait_ref,
328         )
329     }
330     fn path_append(
331         mut self,
332         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
333         disambiguated_data: &DisambiguatedDefPathData,
334     ) -> Result<Self::Path, Self::Error> {
335         self = print_prefix(self)?;
336
337         // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
338         if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
339             return Ok(self);
340         }
341
342         if self.keep_within_component {
343             // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
344             self.write_str("::")?;
345         } else {
346             self.path.finalize_pending_component();
347         }
348
349         write!(self, "{}", disambiguated_data.data)?;
350
351         Ok(self)
352     }
353     fn path_generic_args(
354         mut self,
355         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
356         args: &[GenericArg<'tcx>],
357     ) -> Result<Self::Path, Self::Error> {
358         self = print_prefix(self)?;
359
360         let args =
361             args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
362
363         if args.clone().next().is_some() {
364             self.generic_delimiters(|cx| cx.comma_sep(args))
365         } else {
366             Ok(self)
367         }
368     }
369 }
370
371 impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
372     fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
373         false
374     }
375     fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
376     where
377         T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
378     {
379         if let Some(first) = elems.next() {
380             self = first.print(self)?;
381             for elem in elems {
382                 self.write_str(",")?;
383                 self = elem.print(self)?;
384             }
385         }
386         Ok(self)
387     }
388
389     fn generic_delimiters(
390         mut self,
391         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
392     ) -> Result<Self, Self::Error> {
393         write!(self, "<")?;
394
395         let kept_within_component = mem::replace(&mut self.keep_within_component, true);
396         self = f(self)?;
397         self.keep_within_component = kept_within_component;
398
399         write!(self, ">")?;
400
401         Ok(self)
402     }
403 }
404
405 impl fmt::Write for SymbolPrinter<'_> {
406     fn write_str(&mut self, s: &str) -> fmt::Result {
407         // Name sanitation. LLVM will happily accept identifiers with weird names, but
408         // gas doesn't!
409         // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
410         // NVPTX assembly has more strict naming rules than gas, so additionally, dots
411         // are replaced with '$' there.
412
413         for c in s.chars() {
414             if self.path.temp_buf.is_empty() {
415                 match c {
416                     'a'..='z' | 'A'..='Z' | '_' => {}
417                     _ => {
418                         // Underscore-qualify anything that didn't start as an ident.
419                         self.path.temp_buf.push('_');
420                     }
421                 }
422             }
423             match c {
424                 // Escape these with $ sequences
425                 '@' => self.path.temp_buf.push_str("$SP$"),
426                 '*' => self.path.temp_buf.push_str("$BP$"),
427                 '&' => self.path.temp_buf.push_str("$RF$"),
428                 '<' => self.path.temp_buf.push_str("$LT$"),
429                 '>' => self.path.temp_buf.push_str("$GT$"),
430                 '(' => self.path.temp_buf.push_str("$LP$"),
431                 ')' => self.path.temp_buf.push_str("$RP$"),
432                 ',' => self.path.temp_buf.push_str("$C$"),
433
434                 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
435                     // NVPTX doesn't support these characters in symbol names.
436                     self.path.temp_buf.push('$')
437                 }
438
439                 // '.' doesn't occur in types and functions, so reuse it
440                 // for ':' and '-'
441                 '-' | ':' => self.path.temp_buf.push('.'),
442
443                 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
444                 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
445
446                 // These are legal symbols
447                 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
448
449                 _ => {
450                     self.path.temp_buf.push('$');
451                     for c in c.escape_unicode().skip(1) {
452                         match c {
453                             '{' => {}
454                             '}' => self.path.temp_buf.push('$'),
455                             c => self.path.temp_buf.push(c),
456                         }
457                     }
458                 }
459             }
460         }
461
462         Ok(())
463     }
464 }