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