From 12191d8b5ac1b6cea2d8a3619616310a441242cb Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 16 Nov 2026 08:35:09 +1100 Subject: [PATCH 1/5] Remove an unnecessary pattern It's left over from an earlier cleanup. --- .../src/error_reporting/traits/suggestions.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 8751d884725a9..3e7dede0ccc0a 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -5534,9 +5534,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { && tcx.is_fn_trait(trait_ref.def_id) && let [self_ty, found_ty] = trait_ref.args.as_slice() && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn()) - && let fn_sig @ ty::FnSig { - .. - } = fn_ty.fn_sig(tcx).skip_binder() + && let fn_sig = fn_ty.fn_sig(tcx).skip_binder() // FIXME(splat): this might need to change if the Fn* traits start using/supporting splat && fn_sig.is_fn_trait_compatible() From 2a137d3b632dd85045abe4205dbffca74c2e5868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Tue, 10 Nov 2026 19:30:38 +0100 Subject: [PATCH 2/5] better auto traits? --- .../rustc_trait_selection/src/traits/auto_trait.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 7b23b6dd4d1b4..195140367e309 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -346,6 +346,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { param_env.caller_bounds().all_clauses(infcx.tcx).iter().collect::>(); let mut user_computed_clauses: FxIndexSet<_> = user_env.caller_bounds().all_clauses(infcx.tcx).iter().collect(); + let mut prev_user_computed_clauses = None::>; let mut new_env = param_env; let dummy_cause = ObligationCause::dummy(); @@ -418,6 +419,16 @@ impl<'tcx> AutoTraitFinder<'tcx> { _ => panic!("Unexpected error for '{ty:?}': {result:?}"), }; + // `computed_clauses` doesn't change, only `user_computed_clauses` does. + // except not always! If it didn't, we can stop here. + if prev_user_computed_clauses + .as_ref() + .is_some_and(|prev| prev == &user_computed_clauses) + { + continue; + } + prev_user_computed_clauses = Some(user_computed_clauses.clone()); + let normalized_preds = elaborate( tcx, computed_clauses.iter().copied().chain(user_computed_clauses.iter().cloned()), From ce8a6c864846b1c87657138903f3e85547fa1d65 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 17 Nov 2026 11:47:50 +1100 Subject: [PATCH 3/5] Avoid unnecessary LLVM passes when thin LTO buffer is null `LLVMRustOptimize` runs three passes when `NeedThinLTOBufferPasses` is true: `CanonicalizeAliasesPass`, `NameAnonGlobalPass` and `AssignGUIDPass`. These passes are only needed when the module's bitcode or summary will be written. This commit updates how `NeedThinLTOBufferPasses` is initialized in `LLVMRustOptimize`; instead of being initialized as always true, it's now only true if a thin LTO buffer is provided. (Subsequent existing code in the function may change `NeedThinLTOBufferPasses` to false.) Avoiding the unnecessary passes improves compile times a little, e.g. on debug builds (which are `O0` + `PreLinkNoLTO`). That requires a change to the passes added by `LLVMRustModuleSerialize`, because it currently relies on `LLVMRustOptimize` having run `CanonicalizeAliasesPass` and `NameAnonGlobalPass`, and this is no longer true in some cases such as `--emit=llvm-bc`. The passes are idempotent so it doesn't hurt if they are run twice in other cases. Non-LTO `--emit=llvm-ir,asm` output changes in two ways: unnamed globals stay unnamed (or are named `__unnamed` by LLVM) instead of being named `anon` (this requires updating some tests) and `!guid` metadata disappears. --- compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp | 4 +++- tests/assembly-llvm/asm/x86-types.rs | 2 +- tests/assembly-llvm/cstring-merging.rs | 10 +++++----- tests/codegen-llvm/call-tmps-lifetime.rs | 2 +- tests/codegen-llvm/indirect-bycopy-bymove-byval.rs | 6 +++--- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index ea2f0010742d7..bab0e3d1ed044 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -997,7 +997,7 @@ extern "C" LLVMRustResult LLVMRustOptimize( }; ModulePassManager MPM; - bool NeedThinLTOBufferPasses = true; + bool NeedThinLTOBufferPasses = ThinLTOBufferRef != nullptr; auto ThinLTOBuffer = std::make_unique(); auto ThinLTOSummaryBuffer = std::make_unique(); raw_string_ostream ThinLTODataOS(ThinLTOBuffer->data); @@ -1631,6 +1631,8 @@ extern "C" LLVMRustBuffer *LLVMRustModuleSerialize(LLVMModuleRef M, PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); ModulePassManager MPM; + MPM.addPass(CanonicalizeAliasesPass()); + MPM.addPass(NameAnonGlobalPass()); #if LLVM_VERSION_GE(23, 0) MPM.addPass(AssignGUIDPass()); #endif diff --git a/tests/assembly-llvm/asm/x86-types.rs b/tests/assembly-llvm/asm/x86-types.rs index ac778f6320c28..e9511f230d0ea 100644 --- a/tests/assembly-llvm/asm/x86-types.rs +++ b/tests/assembly-llvm/asm/x86-types.rs @@ -45,7 +45,7 @@ pub unsafe fn sym_static() { // CHECK-LABEL: const_ptr: // CHECK: #APP -// CHECK: mov al, byte ptr [{{.*}}anon{{.*}}] +// CHECK: mov al, byte ptr [{{.*}}__unnamed{{.*}}] // CHECK: #NO_APP #[no_mangle] pub unsafe fn const_ptr() { diff --git a/tests/assembly-llvm/cstring-merging.rs b/tests/assembly-llvm/cstring-merging.rs index e198a49c52216..7557a5a27b084 100644 --- a/tests/assembly-llvm/cstring-merging.rs +++ b/tests/assembly-llvm/cstring-merging.rs @@ -1,5 +1,5 @@ -// MIPS assembler uses the label prefix `$anon.` for local anonymous variables -// other architectures (including ARM and x86-64) use the prefix `.Lanon.` +// MIPS assembler uses the label prefix `$`. +// Other architectures (including ARM and x86-64) use the prefix `.L`. // Hexagon uses `.string` instead of `.asciz` for null-terminated strings //@ only-linux //@ assembly-output: emit-asm @@ -9,13 +9,13 @@ use std::ffi::CStr; // CHECK: .section .rodata.str1.{{[12]}},"aMS" -// CHECK: {{(\.L|\$)}}anon.{{.+}}: +// CHECK: {{(\.L|\$)}}__unnamed_{{[0-9]+}}: // CHECK-NEXT: .{{asciz|string}} "foo" #[unsafe(no_mangle)] static CSTR: &[u8; 4] = b"foo\0"; // CHECK: .section .rodata.str1.{{[12]}},"aMS" -// CHECK: {{(\.L|\$)}}anon.{{.+}}: +// CHECK: {{(\.L|\$)}}__unnamed_{{[0-9]+}}: // CHECK-NEXT: .{{asciz|string}} "bar" #[unsafe(no_mangle)] pub fn cstr() -> &'static CStr { @@ -23,7 +23,7 @@ pub fn cstr() -> &'static CStr { } // CHECK-NOT: .section -// CHECK: {{(\.L|\$)}}anon.{{.+}}: +// CHECK: {{(\.L|\$)}}__unnamed_{{[0-9]+}}: // CHECK-NEXT: .{{asciz|string}} "baz" #[unsafe(no_mangle)] pub fn manual_cstr() -> &'static str { diff --git a/tests/codegen-llvm/call-tmps-lifetime.rs b/tests/codegen-llvm/call-tmps-lifetime.rs index 0e62cfc1e604e..bb58649797415 100644 --- a/tests/codegen-llvm/call-tmps-lifetime.rs +++ b/tests/codegen-llvm/call-tmps-lifetime.rs @@ -15,7 +15,7 @@ use minicore::*; // // CHECK-LABEL: define void @const_indirect( // CHECK-NEXT: start: -// CHECK-NEXT: call void %h(ptr {{.*}}byval([4096 x i8]){{.*}} [[C:@anon.*]]) +// CHECK-NEXT: call void %h(ptr {{.*}}byval([4096 x i8]){{.*}} [[C:@[0-9]+]]) // CHECK-NEXT: call void %h(ptr {{.*}}byval([4096 x i8]){{.*}} [[C]]) #[no_mangle] pub fn const_indirect(h: extern "C" fn([u32; 1024])) { diff --git a/tests/codegen-llvm/indirect-bycopy-bymove-byval.rs b/tests/codegen-llvm/indirect-bycopy-bymove-byval.rs index a72aee6f424ba..93778c5f110cc 100644 --- a/tests/codegen-llvm/indirect-bycopy-bymove-byval.rs +++ b/tests/codegen-llvm/indirect-bycopy-bymove-byval.rs @@ -30,7 +30,7 @@ impl Copy for Thing {} // CHECK: call void @llvm.memcpy{{.*}}(ptr{{.*}} [[normal_V1:%.*]], ptr{{.*}} %value, // CHECK: call void @opaque(ptr{{.*}} [[normal_V1]]) // CHECK: call void @opaque(ptr{{.*}} %value) -// CHECK: call void @llvm.memcpy{{.*}}(ptr{{.*}} [[normal_V3:%.*]], ptr{{.*}} @anon{{.*}}, +// CHECK: call void @llvm.memcpy{{.*}}(ptr{{.*}} [[normal_V3:%.*]], ptr{{.*}} @{{[0-9]+}}, // CHECK: call void @opaque(ptr{{.*}} [[normal_V3]]) #[unsafe(no_mangle)] pub fn normal() { @@ -54,7 +54,7 @@ pub fn normal() { // CHECK-NEXT: call void @{{.*}}(ptr {{.*}}, ptr{{.*}} [[untupled_V1]]) // CHECK: call indirect_bycopy_bymove_byval::untupled::{closure#1} // CHECK-NEXT: call void @{{.*}}(ptr {{.*}}, ptr{{.*}} %value) -// CHECK: call void @llvm.memcpy{{.*}}(ptr{{.*}} [[untupled_V3:%.*]], ptr{{.*}} @anon{{.*}} +// CHECK: call void @llvm.memcpy{{.*}}(ptr{{.*}} [[untupled_V3:%.*]], ptr{{.*}} @{{[0-9]+}} // CHECK: call indirect_bycopy_bymove_byval::untupled::{closure#2} // CHECK-NEXT: call void @{{.*}}(ptr {{.*}}, ptr{{.*}} [[untupled_V3]]) #[unsafe(no_mangle)] @@ -83,7 +83,7 @@ pub fn untupled() { // CHECK-LABEL: @byval // CHECK: call void @opaque_byval(ptr{{.*}} byval([24 x i8]){{.*}} %value) // CHECK: call void @opaque_byval(ptr{{.*}} byval([24 x i8]){{.*}} %value) -// CHECK: call void @opaque_byval(ptr{{.*}} byval([24 x i8]){{.*}} @anon{{.*}}) +// CHECK: call void @opaque_byval(ptr{{.*}} byval([24 x i8]){{.*}} @{{[0-9]+}}) #[unsafe(no_mangle)] pub fn byval() { #[repr(C)] From 54658327d3dd32ee9a020eef34b06128a5b82f92 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 12 Nov 2026 22:19:03 +1100 Subject: [PATCH 4/5] Avoid instantiating `FnSig` when not necessary In various places we call `fn_sig`, which is expensive because it instantiates the signature, but then only look at the ABI or the safety, which don't require the instantiation. This commit introduces `fn_sig_abi` and `fn_sig_safety` which are alternatives that skip instantiation. In `check_instance_abi` the commit also changes `instance.ty(...)` to `tcx.type_of(...)` to avoid a second unnecessary instantiation path. --- compiler/rustc_middle/src/ty/sty.rs | 16 +++++++- .../rustc_mir_build/src/check_unsafety.rs | 4 +- .../src/abort_unwinding_calls.rs | 6 +-- .../src/ffi_unwind_calls.rs | 8 ++-- .../rustc_mir_transform/src/instsimplify.rs | 2 +- compiler/rustc_mir_transform/src/validate.rs | 2 +- .../src/mono_checks/abi_check.rs | 6 +-- compiler/rustc_type_ir/src/ty_kind.rs | 40 +++++++++++++++---- 8 files changed, 61 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 05d861d093f85..d3479c6aca440 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -7,7 +7,7 @@ use std::debug_assert_matches; use std::ops::{ControlFlow, Range}; use hir::def::{CtorKind, DefKind}; -use rustc_abi::{FIRST_VARIANT, FieldIdx, NumScalableVectors, ScalableElt, VariantIdx}; +use rustc_abi::{ExternAbi, FIRST_VARIANT, FieldIdx, NumScalableVectors, ScalableElt, VariantIdx}; use rustc_attr_ir::lang_items::LangItem; use rustc_errors::{ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; @@ -1606,6 +1606,20 @@ impl<'tcx> Ty<'tcx> { self.kind().fn_sig(tcx) } + /// `ty.fn_sig_abi(tcx)` is much faster than `ty.fn_sig(tcx).abi()` because the latter requires + /// instantiating the signature. + #[tracing::instrument(level = "trace", skip(tcx))] + pub fn fn_sig_abi(self, tcx: TyCtxt<'tcx>) -> ExternAbi { + self.kind().fn_sig_abi(tcx) + } + + /// `ty.fn_sig_safety(tcx)` is much faster than `ty.fn_sig(tcx).safety()` because the latter + /// requires instantiating the signature. + #[tracing::instrument(level = "trace", skip(tcx))] + pub fn fn_sig_safety(self, tcx: TyCtxt<'tcx>) -> hir::Safety { + self.kind().fn_sig_safety(tcx) + } + #[tracing::instrument(level = "trace", skip(tcx))] pub fn unnormalized_fn_sig(self, tcx: TyCtxt<'tcx>) -> ty::Unnormalized<'tcx, PolyFnSig<'tcx>> { self.kind().unnormalized_fn_sig(tcx) diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index f1423c2c4b152..2456f2bfe60f1 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -411,7 +411,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { } ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => { let fn_ty = self.thir[fun].ty; - let sig = fn_ty.fn_sig(self.tcx); + let safety = fn_ty.fn_sig_safety(self.tcx); let (callee_features, safe_target_features): (&[_], _) = match *fn_ty.kind() { ty::FnDef(func_id, ..) => { let cg_attrs = self.tcx.codegen_fn_attrs(func_id); @@ -419,7 +419,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { } _ => (&[], false), }; - if sig.safety().is_unsafe() && !safe_target_features { + if safety.is_unsafe() && !safe_target_features { let func_id = if let ty::FnDef(func_id, _) = fn_ty.kind() { Some(*func_id) } else { diff --git a/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs index 39bcee22f7bd0..45d006e6f193a 100644 --- a/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs +++ b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs @@ -52,7 +52,7 @@ impl<'tcx> crate::MirPass<'tcx> for AbortUnwindingCalls { // unwinding or not. let body_ty = tcx.type_of(def_id).skip_binder(); let body_abi = match body_ty.kind() { - ty::FnDef(..) => body_ty.fn_sig(tcx).abi(), + ty::FnDef(..) => body_ty.fn_sig_abi(tcx), ty::Closure(..) => ExternAbi::RustCall, ty::CoroutineClosure(..) => ExternAbi::RustCall, ty::Coroutine(..) => ExternAbi::Rust, @@ -90,13 +90,13 @@ impl<'tcx> crate::MirPass<'tcx> for AbortUnwindingCalls { let call_can_unwind = match &terminator.kind { TerminatorKind::Call { func, .. } => { let ty = func.ty(&body.local_decls, tcx); - let sig = ty.fn_sig(tcx); + let abi = ty.fn_sig_abi(tcx); let fn_def_id = match ty.kind() { ty::FnPtr(..) => None, &ty::FnDef(def_id, _) => Some(def_id), _ => span_bug!(span, "invalid callee of type {:?}", ty), }; - layout::fn_can_unwind(tcx, fn_def_id, sig.abi()) + layout::fn_can_unwind(tcx, fn_def_id, abi) } TerminatorKind::Drop { .. } => { tcx.sess.opts.unstable_opts.panic_in_drop == PanicStrategy::Unwind diff --git a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs index c6530ec375f9b..dacfa5d8a48e9 100644 --- a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs +++ b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs @@ -26,7 +26,7 @@ fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool { let body_ty = tcx.type_of(def_id).skip_binder(); let body_abi = match body_ty.kind() { - ty::FnDef(..) => body_ty.fn_sig(tcx).abi(), + ty::FnDef(..) => body_ty.fn_sig_abi(tcx), ty::Closure(..) => ExternAbi::RustCall, ty::CoroutineClosure(..) => ExternAbi::RustCall, ty::Coroutine(..) => ExternAbi::Rust, @@ -78,11 +78,11 @@ fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool { let TerminatorKind::Call { func, .. } = &terminator.kind else { continue }; let ty = func.ty(body, tcx); - let sig = ty.fn_sig(tcx); + let abi = ty.fn_sig_abi(tcx); // Rust calls cannot themselves create foreign unwinds. // We assume this is true for intrinsics as well. - if sig.abi().is_rustic_abi() { + if abi.is_rustic_abi() { continue; }; @@ -100,7 +100,7 @@ fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool { _ => bug!("invalid callee of type {:?}", ty), }; - if layout::fn_can_unwind(tcx, fn_def_id, sig.abi()) { + if layout::fn_can_unwind(tcx, fn_def_id, abi) { // We have detected a call that can possibly leak foreign unwind. // // Because the function body itself can unwind, we are not aborting this function call diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index 11ce25f2f5d7d..25d7239b3f2dc 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -385,7 +385,7 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { let body_ty = self.tcx.type_of(def_id).skip_binder(); let body_abi = match body_ty.kind() { - ty::FnDef(..) => body_ty.fn_sig(self.tcx).abi(), + ty::FnDef(..) => body_ty.fn_sig_abi(self.tcx), ty::Closure(..) => ExternAbi::RustCall, ty::Coroutine(..) => ExternAbi::Rust, _ => bug!("unexpected body ty: {body_ty:?}"), diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index 7238dbfbb4da1..65e396e0de2b0 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -52,7 +52,7 @@ impl<'tcx> crate::MirPass<'tcx> for Validator { } else { let body_ty = tcx.type_of(def_id).skip_binder(); let body_abi = match body_ty.kind() { - ty::FnDef(..) => body_ty.fn_sig(tcx).abi(), + ty::FnDef(..) => body_ty.fn_sig_abi(tcx), ty::Closure(..) => ExternAbi::RustCall, ty::CoroutineClosure(..) => ExternAbi::RustCall, ty::Coroutine(..) => ExternAbi::Rust, diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs index cff206540bede..9ac225b4fb3c5 100644 --- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs +++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs @@ -170,8 +170,8 @@ fn do_check_unsized_params<'tcx>( /// - the signature requires target features that are not enabled fn check_instance_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) { let typing_env = ty::TypingEnv::fully_monomorphized(); - let ty = instance.ty(tcx, typing_env); - if ty.is_fn() && ty.fn_sig(tcx).abi() == ExternAbi::LlvmIntrinsic { + let ty_no_binder = tcx.type_of(instance.def.def_id()).skip_binder(); + if ty_no_binder.is_fn() && ty_no_binder.fn_sig_abi(tcx) == ExternAbi::LlvmIntrinsic { // We disable all checks for the llvm-intrinsic ABI to allow linking to arbitrary // LLVM intrinsics return; @@ -213,7 +213,7 @@ fn check_call_site_abi<'tcx>( caller: Instance<'tcx>, loc: impl Fn() -> (Span, HirId) + Copy, ) { - let extern_abi = callee.fn_sig(tcx).abi(); + let extern_abi = callee.fn_sig_abi(tcx); if extern_abi.is_rustic_abi() { // We directly handle the soundness of Rust ABIs -- so let's skip the majority of // call sites to avoid a perf regression. diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 16143c3d10e06..68db32e2876d0 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -368,20 +368,14 @@ pub enum TyKind { impl Eq for TyKind {} impl TyKind { - pub fn fn_sig(self, interner: I) -> ty::Binder> { - self.unnormalized_fn_sig(interner).skip_normalization() - } - pub fn unnormalized_fn_sig(self, interner: I) -> Unnormalized>> { match self { ty::FnPtr(sig_tys, hdr) => Unnormalized::new_wip(sig_tys.with(hdr)), ty::FnDef(def_id, args) => { interner.fn_sig(def_id).instantiate(interner, args.no_bound_vars().unwrap()) } - ty::Error(_) => { - // ignore errors (#54954) - Unnormalized::dummy(ty::Binder::dummy(ty::FnSig::dummy())) - } + // ignore errors (#54954) + ty::Error(_) => Unnormalized::dummy(ty::Binder::dummy(ty::FnSig::dummy())), ty::Closure(..) => panic!( "to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`", ), @@ -389,6 +383,36 @@ impl TyKind { } } + pub fn fn_sig(self, interner: I) -> ty::Binder> { + self.unnormalized_fn_sig(interner).skip_normalization() + } + + pub fn fn_sig_abi(self, interner: I) -> ExternAbi { + match self { + ty::FnPtr(_, hdr) => hdr.abi(), + ty::FnDef(def_id, _) => interner.fn_sig(def_id).skip_binder().abi(), + // ignore errors (#54954) + ty::Error(_) => FnSig::::dummy().abi(), + ty::Closure(..) => panic!( + "to get the ABI of a closure, use `args.as_closure().sig().abi()` not `fn_sig_abi()`", + ), + _ => panic!("`fn_sig_abi` called on non-fn type: {:?}", self), + } + } + + pub fn fn_sig_safety(self, interner: I) -> I::Safety { + match self { + ty::FnPtr(_, hdr) => hdr.safety(), + ty::FnDef(def_id, _) => interner.fn_sig(def_id).skip_binder().safety(), + // ignore errors (#54954) + ty::Error(_) => FnSig::::dummy().safety(), + ty::Closure(..) => panic!( + "to get the safety of a closure, use `args.as_closure().sig().safety()` not `fn_sig_safety()`", + ), + _ => panic!("`fn_sig_safety` called on non-fn type: {:?}", self), + } + } + /// Returns `true` when the outermost type cannot be further normalized, /// resolved, or instantiated. /// From e2cd888cb606cfbeae442222c4479a6d48d17356 Mon Sep 17 00:00:00 2001 From: James Barford-Evans Date: Mon, 16 Nov 2026 09:22:12 +0000 Subject: [PATCH 5/5] Have separate `intern_*` and `FlagComputation` methods per `TyKind` --- compiler/rustc_middle/src/ty/context.rs | 296 ++++++++++++++++++++---- compiler/rustc_middle/src/ty/sty.rs | 72 +++--- compiler/rustc_type_ir/src/flags.rs | 246 +++++++++++--------- 3 files changed, 421 insertions(+), 193 deletions(-) diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 30a77f2587026..738599b3ef5d4 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -48,8 +48,8 @@ use rustc_structures::{CrateType, Limit}; use rustc_type_ir::TyKind::*; pub use rustc_type_ir::lift::Lift; use rustc_type_ir::{ - CollectAndApply, IncludeSizedImplicitBounds, PlaceholderType, WithCachedTypeInfo, elaborate, - search_graph, + CollectAndApply, IncludeSizedImplicitBounds, PlaceholderType, TypeFlags, WithCachedTypeInfo, + elaborate, search_graph, }; use tracing::{debug, instrument}; @@ -75,10 +75,10 @@ use crate::traits::solve::{ use crate::ty::predicate::ExistentialPredicateStableCmpExt as _; use crate::ty::{ self, AdtDef, AdtDefData, AdtKind, Binder, CanonicalizerState, Clause, ClausePolarity, Clauses, - Const, ConstKind, FnSigKind, GenericArg, GenericArgsUnsized, GenericParamDefKind, List, - ListWithCachedTypeInfo, ParamConst, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, - Predicate, PredicateKind, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, - TyVid, ValTree, ValTreeKind, Visibility, + Const, ConstKind, FlagComputation, FnSigKind, GenericArg, GenericArgsUnsized, + GenericParamDefKind, List, ListWithCachedTypeInfo, ParamConst, Pattern, PatternKind, + PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, Region, RegionKind, ReprOptions, + TraitObjectVisitor, Ty, TyKind, TyVid, ValTree, ValTreeKind, Visibility, }; impl<'tcx> rustc_type_ir::inherent::DefId> for DefId { @@ -216,24 +216,6 @@ impl<'tcx> CtxtInterners<'tcx> { } } - /// Interns a type. (Use `mk_*` functions instead, where possible.) - #[allow(rustc::usage_of_ty_tykind)] - #[inline(never)] - fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { - Ty(Interned::new_unchecked( - self.type_ - .intern(kind, |kind| { - let flags = ty::FlagComputation::>::for_kind(&kind); - InternedInSet(self.arena.alloc(WithCachedTypeInfo { - internee: kind, - flags: flags.flags, - outer_exclusive_binder: flags.outer_exclusive_binder, - })) - }) - .0, - )) - } - /// Interns a const. (Use `mk_*` functions instead, where possible.) #[allow(rustc::usage_of_ty_tykind)] #[inline(never)] @@ -286,6 +268,196 @@ impl<'tcx> CtxtInterners<'tcx> { .0 } } + + #[allow(rustc::usage_of_ty_tykind)] + #[inline(always)] + fn intern_ty( + &self, + kind: ty::TyKind<'tcx>, + create_flags: impl FnOnce() -> FlagComputation>, + ) -> Ty<'tcx> { + Ty(Interned::new_unchecked( + self.type_ + .intern(kind, |_| { + let flags = create_flags(); + InternedInSet(self.arena.alloc(WithCachedTypeInfo { + internee: kind, + flags: flags.flags, + outer_exclusive_binder: flags.outer_exclusive_binder, + })) + }) + .0, + )) + } + + #[inline(never)] + fn intern_with_empty_flags(&self, kind: ty::TyKind<'tcx>) -> Ty<'tcx> { + self.intern_ty(kind, || FlagComputation::for_flags(TypeFlags::empty())) + } + + #[inline(never)] + pub(super) fn intern_pat(&self, base: Ty<'tcx>, pat: Pattern<'tcx>) -> Ty<'tcx> { + self.intern_ty(Pat(base, pat), || FlagComputation::for_pat(base, pat)) + } + + #[inline(never)] + pub(super) fn intern_coroutine_witness( + &self, + def_id: DefId, + args: ty::GenericArgs<'tcx>, + ) -> Ty<'tcx> { + self.intern_ty(ty::CoroutineWitness(def_id, args), || FlagComputation::for_args(args)) + } + + #[inline(never)] + pub(super) fn intern_infer(&self, infer: ty::InferTy) -> Ty<'tcx> { + self.intern_ty(Infer(infer), || FlagComputation::for_infer(infer)) + } + + #[inline(never)] + pub(super) fn intern_error(&self, error: rustc_errors::ErrorGuaranteed) -> Ty<'tcx> { + self.intern_ty(Error(error), || { + FlagComputation::for_flags(ty::TypeFlags::HAS_NON_REGION_ERROR) + }) + } + + #[inline(never)] + pub(super) fn intern_adt(&self, def: AdtDef<'tcx>, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> { + self.intern_ty(Adt(def, args), || FlagComputation::for_args(args)) + } + + #[inline(never)] + pub(super) fn intern_foreign(&self, def_id: DefId) -> Ty<'tcx> { + self.intern_ty(Foreign(def_id), || FlagComputation::for_flags(TypeFlags::empty())) + } + + #[inline(never)] + pub(super) fn intern_array(&self, element: Ty<'tcx>, len: Const<'tcx>) -> Ty<'tcx> { + self.intern_ty(Array(element, len), || FlagComputation::for_array(element, len)) + } + + #[inline(never)] + pub(super) fn intern_slice(&self, element: Ty<'tcx>) -> Ty<'tcx> { + self.intern_ty(Slice(element), || FlagComputation::for_ty(element)) + } + + #[inline(never)] + pub(super) fn intern_raw_ptr( + &self, + pointee: Ty<'tcx>, + mutability: hir::Mutability, + ) -> Ty<'tcx> { + self.intern_ty(RawPtr(pointee, mutability), || FlagComputation::for_ty(pointee)) + } + + #[inline(never)] + pub(super) fn intern_ref( + &self, + region: Region<'tcx>, + pointee: Ty<'tcx>, + mutability: hir::Mutability, + ) -> Ty<'tcx> { + self.intern_ty(Ref(region, pointee, mutability), || { + FlagComputation::for_ref(region, pointee) + }) + } + + #[inline(never)] + pub(super) fn intern_fn_def( + &self, + def_id: DefId, + args: Binder<'tcx, ty::GenericArgs<'tcx>>, + ) -> Ty<'tcx> { + self.intern_ty(FnDef(def_id, args), || FlagComputation::for_fn_def(args)) + } + + #[inline(never)] + pub(super) fn intern_fn_ptr( + &self, + sig_tys: Binder<'tcx, ty::FnSigTys>>, + header: ty::FnHeader>, + ) -> Ty<'tcx> { + self.intern_ty(FnPtr(sig_tys, header), || FlagComputation::for_fn_ptr(sig_tys)) + } + + #[inline(never)] + pub(super) fn intern_unsafe_binder( + &self, + bound_ty: ty::UnsafeBinderInner>, + ) -> Ty<'tcx> { + self.intern_ty(UnsafeBinder(bound_ty), || FlagComputation::for_unsafe_binder(bound_ty)) + } + + #[inline(never)] + pub(super) fn intern_dynamic( + &self, + predicates: &'tcx List>, + region: Region<'tcx>, + ) -> Ty<'tcx> { + self.intern_ty(Dynamic(predicates, region), || { + FlagComputation::for_dynamic(predicates, region) + }) + } + + #[inline(never)] + pub(super) fn intern_closure(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> { + self.intern_ty(Closure(def_id, args), || FlagComputation::for_args(args)) + } + + #[inline(never)] + pub(super) fn intern_coroutine_closure( + &self, + def_id: DefId, + args: ty::GenericArgs<'tcx>, + ) -> Ty<'tcx> { + self.intern_ty(CoroutineClosure(def_id, args), || FlagComputation::for_args(args)) + } + + #[inline(never)] + pub(super) fn intern_coroutine(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> { + self.intern_ty(Coroutine(def_id, args), || FlagComputation::for_coroutine(args)) + } + + #[inline(never)] + pub(super) fn intern_tuple(&self, types: &'tcx List>) -> Ty<'tcx> { + self.intern_ty(Tuple(types), || FlagComputation::for_tys(types)) + } + + #[inline(never)] + pub(super) fn intern_alias(&self, is_rigid: ty::IsRigid, alias: ty::AliasTy<'tcx>) -> Ty<'tcx> { + self.intern_ty(Alias(is_rigid, alias), || FlagComputation::for_alias(is_rigid, alias)) + } + + #[inline(never)] + pub(super) fn intern_param(&self, param: ty::ParamTy) -> Ty<'tcx> { + self.intern_ty(Param(param), || FlagComputation::for_flags(ty::TypeFlags::HAS_TY_PARAM)) + } + + #[inline(never)] + pub(super) fn intern_bound( + &self, + index: ty::BoundVarIndexKind, + bound_ty: ty::BoundTy<'tcx>, + ) -> Ty<'tcx> { + self.intern_ty(Bound(index, bound_ty), || FlagComputation::for_bound(index)) + } + + #[inline(never)] + pub(super) fn intern_placeholder(&self, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> { + self.intern_ty(Placeholder(placeholder), || { + FlagComputation::for_flags(ty::TypeFlags::HAS_TY_PLACEHOLDER) + }) + } + + #[inline(never)] + pub(super) fn intern_view( + &self, + def: ty::AdtDef<'tcx>, + args: ty::GenericArgs<'tcx>, + fields: Ty<'tcx>, + ) -> Ty<'tcx> { + self.intern_ty(View(def, args, fields), || FlagComputation::for_view(args, fields)) + } } // For these preinterned values, an alternative would be to have @@ -425,28 +597,30 @@ pub struct CommonConsts<'tcx> { impl<'tcx> CommonTypes<'tcx> { fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { - let mk = |ty| interners.intern_ty(ty); + let mk = |ty| interners.intern_with_empty_flags(ty); let infer_ty_vars = (0..NUM_PREINTERNED_INFER_TY_VARS) - .map(|n| mk(Infer(ty::TyVar(TyVid::from(n))))) + .map(|n| interners.intern_infer(ty::TyVar(TyVid::from(n)))) .collect(); - let infer_fresh_tys: Vec<_> = - (0..NUM_PREINTERNED_INFER_FRESH_TYS).map(|n| mk(Infer(ty::FreshTy(n)))).collect(); + let infer_fresh_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_TYS) + .map(|n| interners.intern_infer(ty::FreshTy(n))) + .collect(); + let infer_fresh_int_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_INT_TYS) - .map(|n| mk(Infer(ty::FreshIntTy(n)))) + .map(|n| interners.intern_infer(ty::FreshIntTy(n))) .collect(); let infer_fresh_float_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_FLOAT_TYS) - .map(|n| mk(Infer(ty::FreshFloatTy(n)))) + .map(|n| interners.intern_infer(ty::FreshFloatTy(n))) .collect(); let bound_bound_anons = (0..NUM_PREINTERNED_BOUND_BOUND_ANONS_I) .map(|i| { (0..NUM_PREINTERNED_BOUND_BOUND_ANONS_V) .map(|v| { - mk(ty::Bound( + interners.intern_bound( ty::BoundVarIndexKind::Bound(ty::DebruijnIndex::from(i)), ty::BoundTy { var: ty::BoundVar::from(v), kind: ty::BoundTyKind::Anon }, - )) + ) }) .collect() }) @@ -454,24 +628,24 @@ impl<'tcx> CommonTypes<'tcx> { let bound_canonical_anons = (0..NUM_PREINTERNED_BOUND_CANONICAL_ANONS) .map(|v| { - mk(ty::Bound( + interners.intern_bound( ty::BoundVarIndexKind::Canonical, ty::BoundTy { var: ty::BoundVar::from(v), kind: ty::BoundTyKind::Anon }, - )) + ) }) .collect(); let placeholder_root_anons = (0..NUM_PREINTERNED_PLACEHOLDER_ROOT_ANONS) .map(|v| { - mk(ty::Placeholder(PlaceholderType::new_anon( + interners.intern_placeholder(PlaceholderType::new_anon( ty::UniverseIndex::ROOT, ty::BoundVar::from(v), - ))) + )) }) .collect(); CommonTypes { - unit: mk(Tuple(List::empty())), + unit: interners.intern_tuple(List::empty()), bool: mk(Bool), char: mk(Char), never: mk(Never), @@ -492,7 +666,8 @@ impl<'tcx> CommonTypes<'tcx> { f64: mk(Float(ty::FloatTy::F64)), f128: mk(Float(ty::FloatTy::F128)), str_: mk(Str), - self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })), + + self_param: interners.intern_param(ty::ParamTy { index: 0, name: kw::SelfUpper }), trait_object_dummy_self: infer_fresh_tys[0], @@ -772,7 +947,7 @@ pub struct GlobalCtxt<'tcx> { pub arena: &'tcx WorkerLocal>, pub hir_arena: &'tcx WorkerLocal>, - interners: CtxtInterners<'tcx>, + pub(super) interners: CtxtInterners<'tcx>, pub sess: &'tcx Session, crate_types: Vec, @@ -2470,11 +2645,50 @@ impl<'tcx> TyCtxt<'tcx> { self.interners.intern_const(kind) } - // Avoid this in favour of more specific `Ty::new_*` methods, where possible. + // Avoid this in favour of more specific `Ty::new_*` methods where possible. + // They will be faster because they avoid this match statement. + // FIXME(Jamesbarford): Minimise usage. #[allow(rustc::usage_of_ty_tykind)] #[inline] pub fn mk_ty_from_kind(self, st: TyKind<'tcx>) -> Ty<'tcx> { - self.interners.intern_ty(st) + match st { + ty::Bool => self.interners.intern_with_empty_flags(ty::Bool), + ty::Char => self.interners.intern_with_empty_flags(ty::Char), + ty::Int(int) => self.interners.intern_with_empty_flags(ty::Int(int)), + ty::Uint(uint) => self.interners.intern_with_empty_flags(ty::Uint(uint)), + ty::Float(float) => self.interners.intern_with_empty_flags(ty::Float(float)), + ty::Adt(def, args) => self.interners.intern_adt(def, args), + ty::Foreign(def_id) => self.interners.intern_foreign(def_id), + ty::Str => self.interners.intern_with_empty_flags(ty::Str), + ty::Array(element, len) => self.interners.intern_array(element, len), + ty::Pat(base, pat) => self.interners.intern_pat(base, pat), + ty::Slice(element) => self.interners.intern_slice(element), + ty::RawPtr(pointee, mutability) => self.interners.intern_raw_ptr(pointee, mutability), + ty::Ref(region, pointee, mutability) => { + self.interners.intern_ref(region, pointee, mutability) + } + ty::FnDef(def_id, args) => self.interners.intern_fn_def(def_id, args), + ty::FnPtr(sig_tys, header) => self.interners.intern_fn_ptr(sig_tys, header), + ty::UnsafeBinder(bound_ty) => self.interners.intern_unsafe_binder(bound_ty), + ty::Dynamic(predicates, region) => self.interners.intern_dynamic(predicates, region), + ty::Closure(def_id, args) => self.interners.intern_closure(def_id, args), + ty::CoroutineClosure(def_id, args) => { + self.interners.intern_coroutine_closure(def_id, args) + } + ty::Coroutine(def_id, args) => self.interners.intern_coroutine(def_id, args), + ty::CoroutineWitness(def_id, args) => { + self.interners.intern_coroutine_witness(def_id, args) + } + ty::Never => self.interners.intern_with_empty_flags(ty::Never), + ty::Tuple(types) => self.interners.intern_tuple(types), + ty::Alias(is_rigid, alias) => self.interners.intern_alias(is_rigid, alias), + ty::Param(param) => self.interners.intern_param(param), + ty::Bound(index, bound_ty) => self.interners.intern_bound(index, bound_ty), + ty::Placeholder(placeholder) => self.interners.intern_placeholder(placeholder), + ty::Infer(infer) => self.interners.intern_infer(infer), + ty::Error(error) => self.interners.intern_error(error), + ty::View(def, args, fields) => self.interners.intern_view(def, args, fields), + } } pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 05d861d093f85..5b44f876ac16b 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -362,16 +362,9 @@ impl ParamConst { /// Constructors for `Ty` impl<'tcx> Ty<'tcx> { - /// Avoid using this in favour of more specific `new_*` methods, where possible. - /// The more specific methods will often optimize their creation. - #[inline] - fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> { - tcx.mk_ty_from_kind(st) - } - #[inline] pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> { - Ty::new(tcx, TyKind::Infer(infer)) + tcx.interners.intern_infer(infer) } #[inline] @@ -381,7 +374,7 @@ impl<'tcx> Ty<'tcx> { .infer_ty_vars .get(v.as_usize()) .copied() - .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v)))) + .unwrap_or_else(|| tcx.interners.intern_infer(TyVar(v))) } #[inline] @@ -426,7 +419,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> { - Ty::new(tcx, Param(ParamTy { index, name })) + tcx.interners.intern_param(ParamTy { index, name }) } #[inline] @@ -442,7 +435,7 @@ impl<'tcx> Ty<'tcx> { { ty } else { - Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty)) + tcx.interners.intern_bound(ty::BoundVarIndexKind::Bound(index), bound_ty) } } @@ -452,12 +445,9 @@ impl<'tcx> Ty<'tcx> { if let Some(ty) = tcx.types.bound_canonical_anons.get(var.as_usize()).copied() { ty } else { - Ty::new( - tcx, - Bound( - ty::BoundVarIndexKind::Canonical, - ty::BoundTy { var, kind: ty::BoundTyKind::Anon }, - ), + tcx.interners.intern_bound( + ty::BoundVarIndexKind::Canonical, + ty::BoundTy { var, kind: ty::BoundTyKind::Anon }, ) } } @@ -471,7 +461,7 @@ impl<'tcx> Ty<'tcx> { { ty } else { - Ty::new(tcx, Placeholder(placeholder)) + tcx.interners.intern_placeholder(placeholder) } } @@ -481,12 +471,12 @@ impl<'tcx> Ty<'tcx> { is_rigid: ty::IsRigid, alias_ty: ty::AliasTy<'tcx>, ) -> Ty<'tcx> { - Ty::new(tcx, Alias(is_rigid, alias_ty)) + tcx.interners.intern_alias(is_rigid, alias_ty) } #[inline] pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> { - Ty::new(tcx, Pat(base, pat)) + tcx.interners.intern_pat(base, pat) } #[inline] @@ -531,7 +521,7 @@ impl<'tcx> Ty<'tcx> { /// Constructs a `TyKind::Error` type with current `ErrorGuaranteed` pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> { - Ty::new(tcx, Error(guar)) + tcx.interners.intern_error(guar) } /// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` to ensure it gets used. @@ -549,7 +539,7 @@ impl<'tcx> Ty<'tcx> { msg: impl Into>, ) -> Ty<'tcx> { let reported = tcx.dcx().span_delayed_bug(span, msg); - Ty::new(tcx, Error(reported)) + tcx.interners.intern_error(reported) } #[inline] @@ -596,7 +586,7 @@ impl<'tcx> Ty<'tcx> { ty: Ty<'tcx>, mutbl: ty::Mutability, ) -> Ty<'tcx> { - Ty::new(tcx, Ref(r, ty, mutbl)) + tcx.interners.intern_ref(r, ty, mutbl) } #[inline] @@ -621,7 +611,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> { - Ty::new(tcx, ty::RawPtr(ty, mutbl)) + tcx.interners.intern_raw_ptr(ty, mutbl) } #[inline] @@ -638,17 +628,17 @@ impl<'tcx> Ty<'tcx> { pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgs<'tcx>) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def.did(), args); tcx.debug_assert_adt_def_kind_compatible(def); - Ty::new(tcx, Adt(def, args)) + tcx.interners.intern_adt(def, args) } #[inline] pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> { - Ty::new(tcx, Foreign(def_id)) + tcx.interners.intern_foreign(def_id) } #[inline] pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { - Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n))) + tcx.interners.intern_array(ty, ty::Const::from_target_usize(tcx, n)) } #[inline] @@ -657,17 +647,21 @@ impl<'tcx> Ty<'tcx> { ty: Ty<'tcx>, ct: ty::Const<'tcx>, ) -> Ty<'tcx> { - Ty::new(tcx, Array(ty, ct)) + tcx.interners.intern_array(ty, ct) } #[inline] pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - Ty::new(tcx, Slice(ty)) + tcx.interners.intern_slice(ty) } #[inline] pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> { - if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) } + if ts.is_empty() { + tcx.types.unit + } else { + tcx.interners.intern_tuple(tcx.mk_type_list(ts)) + } } pub fn new_tup_from_iter(tcx: TyCtxt<'tcx>, iter: I) -> T::Output @@ -690,18 +684,18 @@ impl<'tcx> Ty<'tcx> { DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) ); let args = args.map_bound(|args| tcx.check_and_mk_args(def_id, args)); - Ty::new(tcx, FnDef(def_id, args)) + tcx.interners.intern_fn_def(def_id, args) } #[inline] pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { let (sig_tys, hdr) = fty.split(); - Ty::new(tcx, FnPtr(sig_tys, hdr)) + tcx.interners.intern_fn_ptr(sig_tys, hdr) } #[inline] pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> { - Ty::new(tcx, UnsafeBinder(b.into())) + tcx.interners.intern_unsafe_binder(b.into()) } #[inline] @@ -737,7 +731,7 @@ impl<'tcx> Ty<'tcx> { but it has {projection_count}" ); } - Ty::new(tcx, Dynamic(obj, reg)) + tcx.interners.intern_dynamic(obj, reg) } #[inline] @@ -775,7 +769,7 @@ impl<'tcx> Ty<'tcx> { closure_args: GenericArgs<'tcx>, ) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def_id, closure_args); - Ty::new(tcx, Closure(def_id, closure_args)) + tcx.interners.intern_closure(def_id, closure_args) } #[inline] @@ -785,7 +779,7 @@ impl<'tcx> Ty<'tcx> { closure_args: GenericArgs<'tcx>, ) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def_id, closure_args); - Ty::new(tcx, CoroutineClosure(def_id, closure_args)) + tcx.interners.intern_coroutine_closure(def_id, closure_args) } #[inline] @@ -795,7 +789,7 @@ impl<'tcx> Ty<'tcx> { coroutine_args: GenericArgs<'tcx>, ) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def_id, coroutine_args); - Ty::new(tcx, Coroutine(def_id, coroutine_args)) + tcx.interners.intern_coroutine(def_id, coroutine_args) } #[inline] @@ -807,7 +801,7 @@ impl<'tcx> Ty<'tcx> { if cfg!(debug_assertions) { tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args); } - Ty::new(tcx, CoroutineWitness(def_id, args)) + tcx.interners.intern_coroutine_witness(def_id, args) } pub fn new_coroutine_witness_for_coroutine( @@ -851,7 +845,7 @@ impl<'tcx> Ty<'tcx> { .map(|field| Ty::new_field_representing_type(tcx, base, FIRST_VARIANT, *field)); let fields = Ty::new_tup_from_iter(tcx, fields); - Ty::new(tcx, TyKind::View(def, args, fields)) + tcx.interners.intern_view(def, args, fields) } // misc diff --git a/compiler/rustc_type_ir/src/flags.rs b/compiler/rustc_type_ir/src/flags.rs index 26476826b1d19..ee70c79619af1 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -182,8 +182,43 @@ impl FlagComputation { #[allow(rustc::usage_of_ty_tykind)] pub fn for_kind(kind: &ty::TyKind) -> FlagComputation { + match *kind { + ty::Bool + | ty::Char + | ty::Int(_) + | ty::Float(_) + | ty::Uint(_) + | ty::Never + | ty::Str + | ty::Foreign(..) => Self::new(), + ty::Error(_) => Self::for_flags(TypeFlags::HAS_NON_REGION_ERROR), + ty::Param(_) => Self::for_flags(TypeFlags::HAS_TY_PARAM), + ty::Placeholder(..) => Self::for_flags(TypeFlags::HAS_TY_PLACEHOLDER), + ty::Closure(_, args) + | ty::CoroutineClosure(_, args) + | ty::CoroutineWitness(_, args) + | ty::Adt(_, args) => Self::for_args(args), + ty::Coroutine(_, args) => Self::for_coroutine(args), + ty::Bound(index, _) => Self::for_bound(index), + ty::Infer(infer) => Self::for_infer(infer), + ty::Alias(is_rigid, alias) => Self::for_alias(is_rigid, alias), + ty::Dynamic(obj, region) => Self::for_dynamic(obj, region), + ty::Array(ty, len) => Self::for_array(ty, len), + ty::Pat(ty, pat) => Self::for_pat(ty, pat), + ty::Slice(ty) | ty::RawPtr(ty, _) => Self::for_ty(ty), + ty::Ref(region, ty, _) => Self::for_ref(region, ty), + ty::Tuple(types) => Self::for_tys(types), + ty::FnDef(_, args) => Self::for_fn_def(args), + ty::FnPtr(sig_tys, _) => Self::for_fn_ptr(sig_tys), + ty::UnsafeBinder(bound_ty) => Self::for_unsafe_binder(bound_ty), + ty::View(_, args, fields) => Self::for_view(args, fields), + } + } + + pub fn for_view(args: I::GenericArgs, fields: I::Ty) -> FlagComputation { let mut result = FlagComputation::new(); - result.add_kind(kind); + result.add_args(args.as_slice()); + result.add_ty(fields); result } @@ -250,134 +285,119 @@ impl FlagComputation { } // otherwise, this binder captures nothing } - #[allow(rustc::usage_of_ty_tykind)] - fn add_kind(&mut self, kind: &ty::TyKind) { - match *kind { - ty::Bool - | ty::Char - | ty::Int(_) - | ty::Float(_) - | ty::Uint(_) - | ty::Never - | ty::Str - | ty::Foreign(..) => {} - - ty::Error(_) => self.add_flags(TypeFlags::HAS_NON_REGION_ERROR), - - ty::Param(_) => { - self.add_flags(TypeFlags::HAS_TY_PARAM); - } - - ty::Closure(_, args) - | ty::CoroutineClosure(_, args) - | ty::CoroutineWitness(_, args) => { - self.add_args(args.as_slice()); - } - - ty::Coroutine(_, args) => { - self.add_flags(TypeFlags::HAS_TY_CORO); - self.add_args(args.as_slice()); - } - - ty::Bound(ty::BoundVarIndexKind::Canonical, _) => { - self.add_flags(TypeFlags::HAS_TY_BOUND); - self.add_flags(TypeFlags::HAS_CANONICAL_BOUND); - } + /// Flags for a type with no nested types, constants, regions, or binders. + pub fn for_flags(flags: TypeFlags) -> Self { + Self { flags, ..Self::new() } + } - ty::Bound(ty::BoundVarIndexKind::Bound(debruijn), _) => { - self.add_bound_var(debruijn); - self.add_flags(TypeFlags::HAS_TY_BOUND); - } + pub fn for_args(args: I::GenericArgs) -> Self { + let mut result = Self::new(); + result.add_args(args.as_slice()); + result + } - ty::Placeholder(..) => { - self.add_flags(TypeFlags::HAS_TY_PLACEHOLDER); - } + pub fn for_coroutine(args: I::GenericArgs) -> Self { + let mut result = Self::for_args(args); + result.add_flags(TypeFlags::HAS_TY_CORO); + result + } - ty::Infer(infer) => match infer { - ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => { - self.add_flags(TypeFlags::HAS_TY_FRESH) - } + pub fn for_bound(index: ty::BoundVarIndexKind) -> Self { + let mut result = Self::for_flags(TypeFlags::HAS_TY_BOUND); + match index { + ty::BoundVarIndexKind::Canonical => result.add_flags(TypeFlags::HAS_CANONICAL_BOUND), + ty::BoundVarIndexKind::Bound(debruijn) => result.add_bound_var(debruijn), + } - ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => { - self.add_flags(TypeFlags::HAS_TY_INFER) - } - }, + result + } - ty::Adt(_, args) => { - self.add_args(args.as_slice()); - } + pub fn for_infer(infer: ty::InferTy) -> Self { + Self::for_flags(match infer { + ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => TypeFlags::HAS_TY_FRESH, + ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => TypeFlags::HAS_TY_INFER, + }) + } - ty::Alias(is_rigid, alias) => { - self.add_is_rigid(is_rigid); - self.add_flags(match alias.kind { - ty::Projection { .. } => TypeFlags::HAS_TY_PROJECTION, - ty::Free { .. } => TypeFlags::HAS_TY_FREE_ALIAS, - ty::Opaque { .. } => TypeFlags::HAS_TY_OPAQUE, - ty::Inherent { .. } => TypeFlags::HAS_TY_INHERENT, - }); - self.add_alias_ty(alias); - } + pub fn for_alias(is_rigid: ty::IsRigid, alias: ty::AliasTy) -> Self { + let mut result = Self::new(); + result.add_is_rigid(is_rigid); + result.add_flags(match alias.kind { + ty::Projection { .. } => TypeFlags::HAS_TY_PROJECTION, + ty::Free { .. } => TypeFlags::HAS_TY_FREE_ALIAS, + ty::Opaque { .. } => TypeFlags::HAS_TY_OPAQUE, + ty::Inherent { .. } => TypeFlags::HAS_TY_INHERENT, + }); + result.add_alias_ty(alias); + result + } - ty::Dynamic(obj, r) => { - for predicate in obj.iter() { - self.bound_computation(predicate, |computation, predicate| match predicate { - ty::ExistentialPredicate::Trait(tr) => { - computation.add_args(tr.args.as_slice()) - } - ty::ExistentialPredicate::Projection(p) => { - computation.add_existential_projection(&p); - } - ty::ExistentialPredicate::AutoTrait(_) => {} - }); + pub fn for_dynamic(obj: I::BoundExistentialPredicates, region: Region) -> Self { + let mut result = Self::new(); + for predicate in obj.iter() { + result.bound_computation(predicate, |computation, predicate| match predicate { + ty::ExistentialPredicate::Trait(tr) => computation.add_args(tr.args.as_slice()), + ty::ExistentialPredicate::Projection(p) => { + computation.add_existential_projection(&p) } + ty::ExistentialPredicate::AutoTrait(_) => {} + }); + } + result.add_region(region); + result + } - self.add_region(r); - } - - ty::Array(tt, len) => { - self.add_ty(tt); - self.add_const(len); - } - - ty::Pat(ty, pat) => { - self.add_ty(ty); - self.add_ty_pat(pat); - } - - ty::Slice(tt) => self.add_ty(tt), + pub fn for_array(ty: I::Ty, len: Const) -> Self { + let mut result = Self::for_ty(ty); + result.add_const(len); + result + } - ty::RawPtr(ty, _) => { - self.add_ty(ty); - } + pub fn for_pat(ty: I::Ty, pat: I::Pat) -> Self { + let mut result = Self::for_ty(ty); + result.add_ty_pat(pat); + result + } - ty::Ref(r, ty, _) => { - self.add_region(r); - self.add_ty(ty); - } + pub fn for_ty(ty: I::Ty) -> Self { + let mut result = Self::new(); + result.add_ty(ty); + result + } - ty::Tuple(types) => { - self.add_tys(types); - } + pub fn for_ref(region: Region, ty: I::Ty) -> Self { + let mut result = Self::new(); + result.add_region(region); + result.add_ty(ty); + result + } - ty::FnDef(_, args) => { - self.add_binder_args(args); - } + pub fn for_tys(types: I::Tys) -> Self { + let mut result = Self::new(); + result.add_tys(types); + result + } - ty::FnPtr(sig_tys, _) => self.bound_computation(sig_tys, |computation, sig_tys| { - computation.add_tys(sig_tys.inputs_and_output); - }), + pub fn for_fn_def(args: ty::Binder) -> Self { + let mut result = Self::new(); + result.add_binder_args(args); + result + } - ty::UnsafeBinder(bound_ty) => { - self.bound_computation(bound_ty.into(), |computation, ty| { - computation.add_ty(ty); - }) - } + pub fn for_fn_ptr(sig_tys: ty::Binder>) -> Self { + let mut result = Self::new(); + result.bound_computation(sig_tys, |computation, sig_tys| { + computation.add_tys(sig_tys.inputs_and_output); + }); + result + } - ty::View(_, args, fields) => { - self.add_args(args.as_slice()); - self.add_ty(fields); - } - } + pub fn for_unsafe_binder(bound_ty: ty::UnsafeBinderInner) -> Self { + let mut result = Self::new(); + result.bound_computation(bound_ty.into(), |computation, ty| { + computation.add_ty(ty); + }); + result } fn add_ty_pat(&mut self, pat: ::Pat) {