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