]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_symbol_mangling/src/legacy.rs
Rollup merge of #96412 - ChrisDenton:remove-dir-all, r=thomcc
[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, TypeFoldable};
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     let mut hasher = StableHasher::new();
100     let mut hcx = tcx.create_stable_hashing_context();
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 // Follow C++ namespace-mangling style, see
143 // https://en.wikipedia.org/wiki/Name_mangling for more info.
144 //
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.
152 //
153 // To be able to work on all platforms and get *some* reasonable output, we
154 // use C++ name-mangling.
155 #[derive(Debug)]
156 struct SymbolPath {
157     result: String,
158     temp_buf: String,
159 }
160
161 impl SymbolPath {
162     fn new() -> Self {
163         let mut result =
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
166         result
167     }
168
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();
173         }
174     }
175
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);
180         self.result
181     }
182 }
183
184 struct SymbolPrinter<'tcx> {
185     tcx: TyCtxt<'tcx>,
186     path: SymbolPath,
187
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,
193 }
194
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.
198
199 impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
200     type Error = fmt::Error;
201
202     type Path = Self;
203     type Region = Self;
204     type Type = Self;
205     type DynExistential = Self;
206     type Const = Self;
207
208     fn tcx(&self) -> TyCtxt<'tcx> {
209         self.tcx
210     }
211
212     fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
213         Ok(self)
214     }
215
216     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
217         match *ty.kind() {
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),
224
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.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
232                     write!(self, "{}", size)?
233                 } else if let ty::ConstKind::Param(param) = size.kind() {
234                     self = param.print(self)?
235                 } else {
236                     self.write_str("_")?
237                 }
238                 self.write_str("]")?;
239                 Ok(self)
240             }
241
242             _ => self.pretty_print_type(ty),
243         }
244     }
245
246     fn print_dyn_existential(
247         mut self,
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 {
252             if !first {
253                 write!(self, "+")?;
254             }
255             first = false;
256             self = p.print(self)?;
257         }
258         Ok(self)
259     }
260
261     fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
262         // only print integers
263         match (ct.kind(), ct.ty().kind()) {
264             (ty::ConstKind::Value(ty::ValTree::Leaf(scalar)), ty::Int(_) | ty::Uint(_)) => {
265                 // The `pretty_print_const` formatting depends on -Zverbose
266                 // flag, so we cannot reuse it here.
267                 let signed = matches!(ct.ty().kind(), ty::Int(_));
268                 write!(
269                     self,
270                     "{:#?}",
271                     ty::ConstInt::new(scalar, signed, ct.ty().is_ptr_sized_integral())
272                 )?;
273             }
274             _ => self.write_str("_")?,
275         }
276         Ok(self)
277     }
278
279     fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
280         self.write_str(self.tcx.crate_name(cnum).as_str())?;
281         Ok(self)
282     }
283     fn path_qualified(
284         self,
285         self_ty: Ty<'tcx>,
286         trait_ref: Option<ty::TraitRef<'tcx>>,
287     ) -> Result<Self::Path, Self::Error> {
288         // Similar to `pretty_path_qualified`, but for the other
289         // types that are printed as paths (see `print_type` above).
290         match self_ty.kind() {
291             ty::FnDef(..)
292             | ty::Opaque(..)
293             | ty::Projection(_)
294             | ty::Closure(..)
295             | ty::Generator(..)
296                 if trait_ref.is_none() =>
297             {
298                 self.print_type(self_ty)
299             }
300
301             _ => self.pretty_path_qualified(self_ty, trait_ref),
302         }
303     }
304
305     fn path_append_impl(
306         self,
307         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
308         _disambiguated_data: &DisambiguatedDefPathData,
309         self_ty: Ty<'tcx>,
310         trait_ref: Option<ty::TraitRef<'tcx>>,
311     ) -> Result<Self::Path, Self::Error> {
312         self.pretty_path_append_impl(
313             |mut cx| {
314                 cx = print_prefix(cx)?;
315
316                 if cx.keep_within_component {
317                     // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
318                     cx.write_str("::")?;
319                 } else {
320                     cx.path.finalize_pending_component();
321                 }
322
323                 Ok(cx)
324             },
325             self_ty,
326             trait_ref,
327         )
328     }
329     fn path_append(
330         mut self,
331         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
332         disambiguated_data: &DisambiguatedDefPathData,
333     ) -> Result<Self::Path, Self::Error> {
334         self = print_prefix(self)?;
335
336         // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
337         if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
338             return Ok(self);
339         }
340
341         if self.keep_within_component {
342             // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
343             self.write_str("::")?;
344         } else {
345             self.path.finalize_pending_component();
346         }
347
348         write!(self, "{}", disambiguated_data.data)?;
349
350         Ok(self)
351     }
352     fn path_generic_args(
353         mut self,
354         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
355         args: &[GenericArg<'tcx>],
356     ) -> Result<Self::Path, Self::Error> {
357         self = print_prefix(self)?;
358
359         let args =
360             args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
361
362         if args.clone().next().is_some() {
363             self.generic_delimiters(|cx| cx.comma_sep(args))
364         } else {
365             Ok(self)
366         }
367     }
368 }
369
370 impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
371     fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
372         false
373     }
374     fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
375     where
376         T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
377     {
378         if let Some(first) = elems.next() {
379             self = first.print(self)?;
380             for elem in elems {
381                 self.write_str(",")?;
382                 self = elem.print(self)?;
383             }
384         }
385         Ok(self)
386     }
387
388     fn generic_delimiters(
389         mut self,
390         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
391     ) -> Result<Self, Self::Error> {
392         write!(self, "<")?;
393
394         let kept_within_component = mem::replace(&mut self.keep_within_component, true);
395         self = f(self)?;
396         self.keep_within_component = kept_within_component;
397
398         write!(self, ">")?;
399
400         Ok(self)
401     }
402 }
403
404 impl fmt::Write for SymbolPrinter<'_> {
405     fn write_str(&mut self, s: &str) -> fmt::Result {
406         // Name sanitation. LLVM will happily accept identifiers with weird names, but
407         // gas doesn't!
408         // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
409         // NVPTX assembly has more strict naming rules than gas, so additionally, dots
410         // are replaced with '$' there.
411
412         for c in s.chars() {
413             if self.path.temp_buf.is_empty() {
414                 match c {
415                     'a'..='z' | 'A'..='Z' | '_' => {}
416                     _ => {
417                         // Underscore-qualify anything that didn't start as an ident.
418                         self.path.temp_buf.push('_');
419                     }
420                 }
421             }
422             match c {
423                 // Escape these with $ sequences
424                 '@' => self.path.temp_buf.push_str("$SP$"),
425                 '*' => self.path.temp_buf.push_str("$BP$"),
426                 '&' => self.path.temp_buf.push_str("$RF$"),
427                 '<' => self.path.temp_buf.push_str("$LT$"),
428                 '>' => self.path.temp_buf.push_str("$GT$"),
429                 '(' => self.path.temp_buf.push_str("$LP$"),
430                 ')' => self.path.temp_buf.push_str("$RP$"),
431                 ',' => self.path.temp_buf.push_str("$C$"),
432
433                 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
434                     // NVPTX doesn't support these characters in symbol names.
435                     self.path.temp_buf.push('$')
436                 }
437
438                 // '.' doesn't occur in types and functions, so reuse it
439                 // for ':' and '-'
440                 '-' | ':' => self.path.temp_buf.push('.'),
441
442                 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
443                 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
444
445                 // These are legal symbols
446                 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
447
448                 _ => {
449                     self.path.temp_buf.push('$');
450                     for c in c.escape_unicode().skip(1) {
451                         match c {
452                             '{' => {}
453                             '}' => self.path.temp_buf.push('$'),
454                             c => self.path.temp_buf.push(c),
455                         }
456                     }
457                 }
458             }
459         }
460
461         Ok(())
462     }
463 }