Skip to main content

rustc_symbol_mangling/
legacy.rs

1use std::fmt::{self, Write};
2use std::mem::{self, discriminant};
3
4use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
5use rustc_hashes::Hash64;
6use rustc_hir::def_id::{CrateNum, DefId};
7use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
8use rustc_middle::bug;
9use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer};
10use rustc_middle::ty::{
11    self, GenericArg, GenericArgKind, Instance, ReifyReason, Ty, TyCtxt, TypeVisitableExt,
12};
13use tracing::debug;
14
15pub(super) fn mangle<'tcx>(
16    tcx: TyCtxt<'tcx>,
17    instance: Instance<'tcx>,
18    instantiating_crate: Option<CrateNum>,
19) -> String {
20    let def_id = instance.def_id();
21
22    // We want to compute the "type" of this item. Unfortunately, some
23    // kinds of items (e.g., synthetic static allocations from const eval)
24    // don't have a proper implementation for the `type_of` query. So walk
25    // back up the find the closest parent that DOES have a type.
26    let mut ty_def_id = def_id;
27    let instance_ty;
28    loop {
29        let key = tcx.def_key(ty_def_id);
30        match key.disambiguated_data.data {
31            DefPathData::TypeNs(_)
32            | DefPathData::ValueNs(_)
33            | DefPathData::Closure
34            | DefPathData::SyntheticCoroutineBody => {
35                instance_ty = tcx.type_of(ty_def_id).instantiate_identity();
36                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_symbol_mangling/src/legacy.rs:36",
                        "rustc_symbol_mangling::legacy", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_symbol_mangling/src/legacy.rs"),
                        ::tracing_core::__macro_support::Option::Some(36u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_symbol_mangling::legacy"),
                        ::tracing_core::field::FieldSet::new(&["instance_ty"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&instance_ty)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?instance_ty);
37                break;
38            }
39            _ => {
40                // if we're making a symbol for something, there ought
41                // to be a value or type-def or something in there
42                // *somewhere*
43                ty_def_id.index = key.parent.unwrap_or_else(|| {
44                    ::rustc_middle::util::bug::bug_fmt(format_args!("finding type for {0:?}, encountered def-id {1:?} with no parent",
        def_id, ty_def_id));bug!(
45                        "finding type for {:?}, encountered def-id {:?} with no \
46                         parent",
47                        def_id,
48                        ty_def_id
49                    );
50                });
51            }
52        }
53    }
54
55    // Erase regions because they may not be deterministic when hashed
56    // and should not matter anyhow.
57    let instance_ty = tcx.erase_and_anonymize_regions(instance_ty);
58
59    let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
60
61    let mut p = LegacySymbolMangler { tcx, path: SymbolPath::new(), keep_within_component: false };
62    p.print_def_path(
63        def_id,
64        if let ty::InstanceKind::DropGlue(_, _)
65        | ty::InstanceKind::AsyncDropGlueCtorShim(_, _)
66        | ty::InstanceKind::FutureDropPollShim(_, _, _) = instance.def
67        {
68            // Add the name of the dropped type to the symbol name
69            &*instance.args
70        } else if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def {
71            let ty::Coroutine(_, cor_args) = ty.kind() else {
72                ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
73            };
74            let drop_ty = cor_args.first().unwrap().expect_ty();
75            tcx.mk_args(&[GenericArg::from(drop_ty)])
76        } else {
77            &[]
78        },
79    )
80    .unwrap();
81
82    match instance.def {
83        ty::InstanceKind::ThreadLocalShim(..) => {
84            p.write_str("{{tls-shim}}").unwrap();
85        }
86        ty::InstanceKind::VTableShim(..) => {
87            p.write_str("{{vtable-shim}}").unwrap();
88        }
89        ty::InstanceKind::ReifyShim(_, reason) => {
90            p.write_str("{{reify-shim").unwrap();
91            match reason {
92                Some(ReifyReason::FnPtr) => p.write_str("-fnptr").unwrap(),
93                Some(ReifyReason::Vtable) => p.write_str("-vtable").unwrap(),
94                None => (),
95            }
96            p.write_str("}}").unwrap();
97        }
98        // FIXME(async_closures): This shouldn't be needed when we fix
99        // `Instance::ty`/`Instance::def_id`.
100        ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref, .. } => {
101            p.write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" })
102                .unwrap();
103        }
104        _ => {}
105    }
106
107    if let ty::InstanceKind::FutureDropPollShim(..) = instance.def {
108        let _ = p.write_str("{{drop-shim}}");
109    }
110
111    p.path.finish(hash)
112}
113
114fn get_symbol_hash<'tcx>(
115    tcx: TyCtxt<'tcx>,
116
117    // instance this name will be for
118    instance: Instance<'tcx>,
119
120    // type of the item, without any generic
121    // parameters instantiated; this is
122    // included in the hash as a kind of
123    // safeguard.
124    item_type: Ty<'tcx>,
125
126    instantiating_crate: Option<CrateNum>,
127) -> Hash64 {
128    let def_id = instance.def_id();
129    let args = instance.args;
130    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_symbol_mangling/src/legacy.rs:130",
                        "rustc_symbol_mangling::legacy", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_symbol_mangling/src/legacy.rs"),
                        ::tracing_core::__macro_support::Option::Some(130u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_symbol_mangling::legacy"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("get_symbol_hash(def_id={0:?}, parameters={1:?})",
                                                    def_id, args) as &dyn Value))])
            });
    } else { ; }
};debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, args);
131
132    tcx.with_stable_hashing_context(|mut hcx| {
133        let mut hasher = StableHasher::new();
134
135        // the main symbol name is not necessarily unique; hash in the
136        // compiler's internal def-path, guaranteeing each symbol has a
137        // truly unique path
138        tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
139
140        // Include the main item-type. Note that, in this case, the
141        // assertions about `has_param` may not hold, but this item-type
142        // ought to be the same for every reference anyway.
143        if !!item_type.has_erasable_regions() {
    ::core::panicking::panic("assertion failed: !item_type.has_erasable_regions()")
};assert!(!item_type.has_erasable_regions());
144        hcx.while_hashing_spans(false, |hcx| {
145            item_type.hash_stable(hcx, &mut hasher);
146
147            // If this is a function, we hash the signature as well.
148            // This is not *strictly* needed, but it may help in some
149            // situations, see the `run-make/a-b-a-linker-guard` test.
150            if let ty::FnDef(..) = item_type.kind() {
151                item_type.fn_sig(tcx).hash_stable(hcx, &mut hasher);
152            }
153
154            // also include any type parameters (for generic items)
155            args.hash_stable(hcx, &mut hasher);
156
157            if let Some(instantiating_crate) = instantiating_crate {
158                tcx.stable_crate_id(instantiating_crate).hash_stable(hcx, &mut hasher);
159            }
160
161            // We want to avoid accidental collision between different types of instances.
162            // Especially, `VTableShim`s and `ReifyShim`s may overlap with their original
163            // instances without this.
164            discriminant(&instance.def).hash_stable(hcx, &mut hasher);
165        });
166
167        // 64 bits should be enough to avoid collisions.
168        hasher.finish::<Hash64>()
169    })
170}
171
172// Follow C++ namespace-mangling style, see
173// https://en.wikipedia.org/wiki/Name_mangling for more info.
174//
175// It turns out that on macOS you can actually have arbitrary symbols in
176// function names (at least when given to LLVM), but this is not possible
177// when using unix's linker. Perhaps one day when we just use a linker from LLVM
178// we won't need to do this name mangling. The problem with name mangling is
179// that it seriously limits the available characters. For example we can't
180// have things like &T in symbol names when one would theoretically
181// want them for things like impls of traits on that type.
182//
183// To be able to work on all platforms and get *some* reasonable output, we
184// use C++ name-mangling.
185#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SymbolPath {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "SymbolPath",
            "result", &self.result, "temp_buf", &&self.temp_buf)
    }
}Debug)]
186struct SymbolPath {
187    result: String,
188    temp_buf: String,
189}
190
191impl SymbolPath {
192    fn new() -> Self {
193        let mut result =
194            SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
195        result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
196        result
197    }
198
199    fn finalize_pending_component(&mut self) {
200        if !self.temp_buf.is_empty() {
201            let _ = self.result.write_fmt(format_args!("{0}{1}", self.temp_buf.len(),
        self.temp_buf))write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
202            self.temp_buf.clear();
203        }
204    }
205
206    fn finish(mut self, hash: Hash64) -> String {
207        self.finalize_pending_component();
208        // E = end name-sequence
209        let _ = self.result.write_fmt(format_args!("17h{0:016x}E", hash))write!(self.result, "17h{hash:016x}E");
210        self.result
211    }
212}
213
214struct LegacySymbolMangler<'tcx> {
215    tcx: TyCtxt<'tcx>,
216    path: SymbolPath,
217
218    // When `true`, `finalize_pending_component` isn't used.
219    // This is needed when recursing into `print_path_with_qualified`,
220    // or `print_path_with_generic_args`, as any nested paths are
221    // logically within one component.
222    keep_within_component: bool,
223}
224
225// HACK(eddyb) this relies on using the `fmt` interface to get
226// `PrettyPrinter` aka pretty printing of e.g. types in paths,
227// symbol names should have their own printing machinery.
228
229impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> {
230    fn tcx(&self) -> TyCtxt<'tcx> {
231        self.tcx
232    }
233
234    fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
235        // This might be reachable (via `pretty_print_dyn_existential`) even though
236        // `<Self As PrettyPrinter>::should_print_optional_region` returns false and
237        // `print_path_with_generic_args` filters out lifetimes. See #144994.
238        Ok(())
239    }
240
241    fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
242        match *ty.kind() {
243            // Print all nominal types as paths (unlike `pretty_print_type`).
244            ty::FnDef(def_id, args)
245            | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. })
246            | ty::Closure(def_id, args)
247            | ty::CoroutineClosure(def_id, args)
248            | ty::Coroutine(def_id, args) => self.print_def_path(def_id, args),
249
250            // The `pretty_print_type` formatting of array size depends on
251            // -Zverbose-internals flag, so we cannot reuse it here.
252            ty::Array(ty, size) => {
253                self.write_str("[")?;
254                self.print_type(ty)?;
255                self.write_str("; ")?;
256                if let Some(size) = size.try_to_target_usize(self.tcx()) {
257                    self.write_fmt(format_args!("{0}", size))write!(self, "{size}")?
258                } else if let ty::ConstKind::Param(param) = size.kind() {
259                    param.print(self)?
260                } else {
261                    self.write_str("_")?
262                }
263                self.write_str("]")?;
264                Ok(())
265            }
266
267            ty::Alias(ty::Inherent, _) => {
    ::core::panicking::panic_fmt(format_args!("unexpected inherent projection"));
}panic!("unexpected inherent projection"),
268
269            _ => self.pretty_print_type(ty),
270        }
271    }
272
273    fn print_dyn_existential(
274        &mut self,
275        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
276    ) -> Result<(), PrintError> {
277        let mut first = true;
278        for p in predicates {
279            if !first {
280                self.write_fmt(format_args!("+"))write!(self, "+")?;
281            }
282            first = false;
283            p.print(self)?;
284        }
285        Ok(())
286    }
287
288    fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
289        // only print integers
290        match ct.kind() {
291            ty::ConstKind::Value(cv) if cv.ty.is_integral() => {
292                // The `pretty_print_const` formatting depends on -Zverbose-internals
293                // flag, so we cannot reuse it here.
294                let scalar = cv.to_leaf();
295                let signed = #[allow(non_exhaustive_omitted_patterns)] match cv.ty.kind() {
    ty::Int(_) => true,
    _ => false,
}matches!(cv.ty.kind(), ty::Int(_));
296                self.write_fmt(format_args!("{0:#?}",
        ty::ConstInt::new(scalar, signed, cv.ty.is_ptr_sized_integral())))write!(
297                    self,
298                    "{:#?}",
299                    ty::ConstInt::new(scalar, signed, cv.ty.is_ptr_sized_integral())
300                )?;
301            }
302            _ => self.write_str("_")?,
303        }
304        Ok(())
305    }
306
307    fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
308        self.write_str(self.tcx.crate_name(cnum).as_str())?;
309        Ok(())
310    }
311
312    fn print_path_with_qualified(
313        &mut self,
314        self_ty: Ty<'tcx>,
315        trait_ref: Option<ty::TraitRef<'tcx>>,
316    ) -> Result<(), PrintError> {
317        // Similar to `pretty_print_path_with_qualified`, but for the other
318        // types that are printed as paths (see `print_type` above).
319        match self_ty.kind() {
320            ty::FnDef(..)
321            | ty::Alias(..)
322            | ty::Closure(..)
323            | ty::CoroutineClosure(..)
324            | ty::Coroutine(..)
325                if trait_ref.is_none() =>
326            {
327                self.print_type(self_ty)
328            }
329
330            _ => self.pretty_print_path_with_qualified(self_ty, trait_ref),
331        }
332    }
333
334    fn print_path_with_impl(
335        &mut self,
336        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
337        self_ty: Ty<'tcx>,
338        trait_ref: Option<ty::TraitRef<'tcx>>,
339    ) -> Result<(), PrintError> {
340        self.pretty_print_path_with_impl(
341            |cx| {
342                print_prefix(cx)?;
343
344                if cx.keep_within_component {
345                    // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
346                    cx.write_str("::")?;
347                } else {
348                    cx.path.finalize_pending_component();
349                }
350
351                Ok(())
352            },
353            self_ty,
354            trait_ref,
355        )
356    }
357
358    fn print_path_with_simple(
359        &mut self,
360        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
361        disambiguated_data: &DisambiguatedDefPathData,
362    ) -> Result<(), PrintError> {
363        print_prefix(self)?;
364
365        // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
366        if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
367            return Ok(());
368        }
369
370        if self.keep_within_component {
371            // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
372            self.write_str("::")?;
373        } else {
374            self.path.finalize_pending_component();
375        }
376
377        self.write_fmt(format_args!("{0}", disambiguated_data.data))write!(self, "{}", disambiguated_data.data)?;
378
379        Ok(())
380    }
381
382    fn print_path_with_generic_args(
383        &mut self,
384        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
385        args: &[GenericArg<'tcx>],
386    ) -> Result<(), PrintError> {
387        print_prefix(self)?;
388
389        let args =
390            args.iter().cloned().filter(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg.kind() {
    GenericArgKind::Lifetime(_) => true,
    _ => false,
}matches!(arg.kind(), GenericArgKind::Lifetime(_)));
391        if args.clone().next().is_some() {
392            self.generic_delimiters(|cx| cx.comma_sep(args))
393        } else {
394            Ok(())
395        }
396    }
397
398    fn print_impl_path(
399        &mut self,
400        impl_def_id: DefId,
401        args: &'tcx [GenericArg<'tcx>],
402    ) -> Result<(), PrintError> {
403        let self_ty = self.tcx.type_of(impl_def_id);
404        let impl_trait_ref = self.tcx.impl_opt_trait_ref(impl_def_id);
405        let generics = self.tcx.generics_of(impl_def_id);
406        // We have two cases to worry about here:
407        // 1. We're printing a nested item inside of an impl item, like an inner
408        // function inside of a method. Due to the way that def path printing works,
409        // we'll render this something like `<Ty as Trait>::method::inner_fn`
410        // but we have no substs for this impl since it's not really inheriting
411        // generics from the outer item. We need to use the identity substs, and
412        // to normalize we need to use the correct param-env too.
413        // 2. We're mangling an item with identity substs. This seems to only happen
414        // when generating coverage, since we try to generate coverage for unused
415        // items too, and if something isn't monomorphized then we necessarily don't
416        // have anything to substitute the instance with.
417        // NOTE: We don't support mangling partially substituted but still polymorphic
418        // instances, like `impl<A> Tr<A> for ()` where `A` is substituted w/ `(T,)`.
419        let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
420            || &args[..generics.count()]
421                == self
422                    .tcx
423                    .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item(
424                        self.tcx,
425                        impl_def_id,
426                    ))
427                    .as_slice()
428        {
429            (
430                ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
431                self_ty.instantiate_identity(),
432                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate_identity()),
433            )
434        } else {
435            if !!args.has_non_region_param() {
    {
        ::core::panicking::panic_fmt(format_args!("should not be mangling partially substituted polymorphic instance: {0:?} {1:?}",
                impl_def_id, args));
    }
};assert!(
436                !args.has_non_region_param(),
437                "should not be mangling partially substituted \
438                polymorphic instance: {impl_def_id:?} {args:?}"
439            );
440            (
441                ty::TypingEnv::fully_monomorphized(),
442                self_ty.instantiate(self.tcx, args),
443                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate(self.tcx, args)),
444            )
445        };
446
447        match &mut impl_trait_ref {
448            Some(impl_trait_ref) => {
449                match (&impl_trait_ref.self_ty(), &self_ty) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(impl_trait_ref.self_ty(), self_ty);
450                *impl_trait_ref = self.tcx.normalize_erasing_regions(typing_env, *impl_trait_ref);
451                self_ty = impl_trait_ref.self_ty();
452            }
453            None => {
454                self_ty = self.tcx.normalize_erasing_regions(typing_env, self_ty);
455            }
456        }
457
458        self.default_print_impl_path(impl_def_id, self_ty, impl_trait_ref)
459    }
460}
461
462impl<'tcx> PrettyPrinter<'tcx> for LegacySymbolMangler<'tcx> {
463    fn should_print_optional_region(&self, _region: ty::Region<'_>) -> bool {
464        false
465    }
466
467    // Identical to `PrettyPrinter::comma_sep` except there is no space after each comma.
468    fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>
469    where
470        T: Print<'tcx, Self>,
471    {
472        if let Some(first) = elems.next() {
473            first.print(self)?;
474            for elem in elems {
475                self.write_str(",")?;
476                elem.print(self)?;
477            }
478        }
479        Ok(())
480    }
481
482    fn generic_delimiters(
483        &mut self,
484        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
485    ) -> Result<(), PrintError> {
486        self.write_fmt(format_args!("<"))write!(self, "<")?;
487
488        let kept_within_component = mem::replace(&mut self.keep_within_component, true);
489        f(self)?;
490        self.keep_within_component = kept_within_component;
491
492        self.write_fmt(format_args!(">"))write!(self, ">")?;
493
494        Ok(())
495    }
496}
497
498impl fmt::Write for LegacySymbolMangler<'_> {
499    fn write_str(&mut self, s: &str) -> fmt::Result {
500        // Name sanitation. LLVM will happily accept identifiers with weird names, but
501        // gas doesn't!
502        // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
503        // NVPTX assembly has more strict naming rules than gas, so additionally, dots
504        // are replaced with '$' there.
505
506        for c in s.chars() {
507            if self.path.temp_buf.is_empty() {
508                match c {
509                    'a'..='z' | 'A'..='Z' | '_' => {}
510                    _ => {
511                        // Underscore-qualify anything that didn't start as an ident.
512                        self.path.temp_buf.push('_');
513                    }
514                }
515            }
516            match c {
517                // Escape these with $ sequences
518                '@' => self.path.temp_buf.push_str("$SP$"),
519                '*' => self.path.temp_buf.push_str("$BP$"),
520                '&' => self.path.temp_buf.push_str("$RF$"),
521                '<' => self.path.temp_buf.push_str("$LT$"),
522                '>' => self.path.temp_buf.push_str("$GT$"),
523                '(' => self.path.temp_buf.push_str("$LP$"),
524                ')' => self.path.temp_buf.push_str("$RP$"),
525                ',' => self.path.temp_buf.push_str("$C$"),
526
527                '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
528                    // NVPTX doesn't support these characters in symbol names.
529                    self.path.temp_buf.push('$')
530                }
531
532                // '.' doesn't occur in types and functions, so reuse it
533                // for ':' and '-'
534                '-' | ':' => self.path.temp_buf.push('.'),
535
536                // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
537                'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
538
539                // These are legal symbols
540                'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
541
542                _ => {
543                    self.path.temp_buf.push('$');
544                    for c in c.escape_unicode().skip(1) {
545                        match c {
546                            '{' => {}
547                            '}' => self.path.temp_buf.push('$'),
548                            c => self.path.temp_buf.push(c),
549                        }
550                    }
551                }
552            }
553        }
554
555        Ok(())
556    }
557}