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