Skip to content

Commit 31d35eb

Browse files
committed
Auto merge of rust-lang#140518 - compiler-errors:less-instance-new-raw, r=<try>
Less `Instance::new_raw` For perf. Based on rust-lang#140374. r? `@ghost`
2 parents d2eadb7 + 1c55d70 commit 31d35eb

File tree

22 files changed

+148
-38
lines changed

22 files changed

+148
-38
lines changed

compiler/rustc_codegen_cranelift/src/global_asm.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,13 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String,
6565

6666
let ty = tcx.typeck(item_id.owner_id).expr_ty(expr);
6767
let instance = match ty.kind() {
68-
&ty::FnDef(def_id, args) => Instance::new(def_id, args),
68+
&ty::FnDef(def_id, args) => Instance::expect_resolve(
69+
tcx,
70+
ty::TypingEnv::fully_monomorphized(),
71+
def_id,
72+
args,
73+
expr.span,
74+
),
6975
_ => span_bug!(op_sp, "asm sym is not a function"),
7076
};
7177
let symbol = tcx.symbol_name(instance);

compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1282,7 +1282,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
12821282
intrinsic.name,
12831283
);
12841284
}
1285-
return Err(Instance::new(instance.def_id(), instance.args));
1285+
return Err(Instance::new_raw(instance.def_id(), instance.args));
12861286
}
12871287
}
12881288

compiler/rustc_codegen_gcc/src/intrinsic/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc
399399
}
400400

401401
// Fall back to default body
402-
_ => return Err(Instance::new(instance.def_id(), instance.args)),
402+
_ => return Err(Instance::new_raw(instance.def_id(), instance.args)),
403403
};
404404

405405
if !fn_abi.ret.is_ignore() {

compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/unused.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ fn make_dummy_instance<'tcx>(tcx: TyCtxt<'tcx>, local_def_id: LocalDefId) -> ty:
157157
let def_id = local_def_id.to_def_id();
158158

159159
// Make a dummy instance that fills in all generics with placeholders.
160-
ty::Instance::new(
160+
ty::Instance::new_raw(
161161
def_id,
162162
ty::GenericArgs::for_item(tcx, def_id, |param, _| {
163163
if let ty::GenericParamDefKind::Lifetime = param.kind {

compiler/rustc_codegen_llvm/src/intrinsic.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
613613
_ => {
614614
debug!("unknown intrinsic '{}' -- falling back to default body", name);
615615
// Call the fallback body instead of generating the intrinsic code
616-
return Err(ty::Instance::new(instance.def_id(), instance.args));
616+
return Err(ty::Instance::new_raw(instance.def_id(), instance.args));
617617
}
618618
};
619619

compiler/rustc_codegen_ssa/src/back/symbol_export.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -565,7 +565,7 @@ pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
565565
ExportedSymbol::Generic(def_id, args) => {
566566
rustc_symbol_mangling::symbol_name_for_instance_in_crate(
567567
tcx,
568-
Instance::new(def_id, args),
568+
Instance::new_raw(def_id, args),
569569
instantiating_crate,
570570
)
571571
}
@@ -613,7 +613,7 @@ fn calling_convention_for_symbol<'tcx>(
613613
None
614614
}
615615
ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
616-
ExportedSymbol::Generic(def_id, args) => Some(Instance::new(def_id, args)),
616+
ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
617617
// DropGlue always use the Rust calling convention and thus follow the target's default
618618
// symbol decoration scheme.
619619
ExportedSymbol::DropGlue(..) => None,

compiler/rustc_codegen_ssa/src/mir/naked_asm.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ fn inline_to_global_operand<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
8686
);
8787

8888
let instance = match mono_type.kind() {
89-
&ty::FnDef(def_id, args) => Instance::new(def_id, args),
89+
&ty::FnDef(def_id, args) => {
90+
Instance::expect_resolve(cx.tcx(), cx.typing_env(), def_id, args, value.span)
91+
}
9092
_ => bug!("asm sym is not a function"),
9193
};
9294

compiler/rustc_codegen_ssa/src/mono_item.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,13 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
7474
hir::InlineAsmOperand::SymFn { expr } => {
7575
let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
7676
let instance = match ty.kind() {
77-
&ty::FnDef(def_id, args) => Instance::new(def_id, args),
77+
&ty::FnDef(def_id, args) => Instance::expect_resolve(
78+
cx.tcx(),
79+
ty::TypingEnv::fully_monomorphized(),
80+
def_id,
81+
args,
82+
expr.span,
83+
),
7884
_ => span_bug!(*op_sp, "asm sym is not a function"),
7985
};
8086

compiler/rustc_hir_analysis/src/lib.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ use rustc_middle::query::Providers;
101101
use rustc_middle::ty::{self, Const, Ty, TyCtxt};
102102
use rustc_session::parse::feature_err;
103103
use rustc_span::symbol::sym;
104-
use rustc_span::{ErrorGuaranteed, Span};
104+
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
105105
use rustc_trait_selection::traits;
106106

107107
pub use crate::collect::suggest_impl_trait;
@@ -216,9 +216,15 @@ pub fn check_crate(tcx: TyCtxt<'_>) {
216216
check::maybe_check_static_with_link_section(tcx, item_def_id);
217217
}
218218
DefKind::Const if tcx.generics_of(item_def_id).is_empty() => {
219-
let instance = ty::Instance::new(item_def_id.into(), ty::GenericArgs::empty());
220-
let cid = GlobalId { instance, promoted: None };
221219
let typing_env = ty::TypingEnv::fully_monomorphized();
220+
let instance = ty::Instance::expect_resolve(
221+
tcx,
222+
typing_env,
223+
item_def_id.into(),
224+
ty::GenericArgs::empty(),
225+
DUMMY_SP,
226+
);
227+
let cid = GlobalId { instance, promoted: None };
222228
tcx.ensure_ok().eval_to_const_value_raw(typing_env.as_query_input(cid));
223229
}
224230
_ => (),

compiler/rustc_lint/src/foreign_modules.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ impl ClashingExternDeclarations {
104104
/// for the item, return its HirId without updating the set.
105105
fn insert(&mut self, tcx: TyCtxt<'_>, fi: hir::ForeignItemId) -> Option<hir::OwnerId> {
106106
let did = fi.owner_id.to_def_id();
107-
let instance = Instance::new(did, ty::List::identity_for_item(tcx, did));
107+
let instance = Instance::new_raw(did, ty::List::identity_for_item(tcx, did));
108108
let name = Symbol::intern(tcx.symbol_name(instance).name);
109109
if let Some(&existing_id) = self.seen_decls.get(&name) {
110110
// Avoid updating the map with the new entry when we do find a collision. We want to

compiler/rustc_middle/src/middle/exported_symbols.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl<'tcx> ExportedSymbol<'tcx> {
5656
match *self {
5757
ExportedSymbol::NonGeneric(def_id) => tcx.symbol_name(ty::Instance::mono(tcx, def_id)),
5858
ExportedSymbol::Generic(def_id, args) => {
59-
tcx.symbol_name(ty::Instance::new(def_id, args))
59+
tcx.symbol_name(ty::Instance::new_raw(def_id, args))
6060
}
6161
ExportedSymbol::DropGlue(ty) => {
6262
tcx.symbol_name(ty::Instance::resolve_drop_in_place(tcx, ty))

compiler/rustc_middle/src/mir/interpret/queries.rs

+26-6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::assert_matches::debug_assert_matches;
2+
13
use rustc_hir::def::DefKind;
24
use rustc_hir::def_id::DefId;
35
use rustc_session::lint;
@@ -18,14 +20,18 @@ impl<'tcx> TyCtxt<'tcx> {
1820
/// generic parameter is used within the constant `ErrorHandled::TooGeneric` will be returned.
1921
#[instrument(skip(self), level = "debug")]
2022
pub fn const_eval_poly(self, def_id: DefId) -> EvalToConstValueResult<'tcx> {
23+
debug_assert_matches!(
24+
self.def_kind(def_id),
25+
DefKind::Const | DefKind::AnonConst | DefKind::InlineConst
26+
);
2127
// In some situations def_id will have generic parameters within scope, but they aren't allowed
2228
// to be used. So we can't use `Instance::mono`, instead we feed unresolved generic parameters
2329
// into `const_eval` which will return `ErrorHandled::TooGeneric` if any of them are
2430
// encountered.
2531
let args = GenericArgs::identity_for_item(self, def_id);
26-
let instance = ty::Instance::new(def_id, args);
27-
let cid = GlobalId { instance, promoted: None };
2832
let typing_env = ty::TypingEnv::post_analysis(self, def_id);
33+
let instance = ty::Instance::expect_resolve(self, typing_env, def_id, args, DUMMY_SP);
34+
let cid = GlobalId { instance, promoted: None };
2935
self.const_eval_global_id(typing_env, cid, DUMMY_SP)
3036
}
3137

@@ -34,14 +40,18 @@ impl<'tcx> TyCtxt<'tcx> {
3440
/// generic parameter is used within the constant `ErrorHandled::TooGeneric` will be returned.
3541
#[instrument(skip(self), level = "debug")]
3642
pub fn const_eval_poly_to_alloc(self, def_id: DefId) -> EvalToAllocationRawResult<'tcx> {
43+
debug_assert_matches!(
44+
self.def_kind(def_id),
45+
DefKind::Const | DefKind::AnonConst | DefKind::InlineConst
46+
);
3747
// In some situations def_id will have generic parameters within scope, but they aren't allowed
3848
// to be used. So we can't use `Instance::mono`, instead we feed unresolved generic parameters
3949
// into `const_eval` which will return `ErrorHandled::TooGeneric` if any of them are
4050
// encountered.
4151
let args = GenericArgs::identity_for_item(self, def_id);
42-
let instance = ty::Instance::new(def_id, args);
43-
let cid = GlobalId { instance, promoted: None };
4452
let typing_env = ty::TypingEnv::post_analysis(self, def_id);
53+
let instance = ty::Instance::expect_resolve(self, typing_env, def_id, args, DUMMY_SP);
54+
let cid = GlobalId { instance, promoted: None };
4555
let inputs = self.erase_regions(typing_env.as_query_input(cid));
4656
self.eval_to_allocation_raw(inputs)
4757
}
@@ -203,14 +213,24 @@ impl<'tcx> TyCtxtEnsureOk<'tcx> {
203213
/// generic parameter is used within the constant `ErrorHandled::TooGeneric` will be returned.
204214
#[instrument(skip(self), level = "debug")]
205215
pub fn const_eval_poly(self, def_id: DefId) {
216+
debug_assert_matches!(
217+
self.tcx.def_kind(def_id),
218+
DefKind::Const | DefKind::AnonConst | DefKind::InlineConst
219+
);
206220
// In some situations def_id will have generic parameters within scope, but they aren't allowed
207221
// to be used. So we can't use `Instance::mono`, instead we feed unresolved generic parameters
208222
// into `const_eval` which will return `ErrorHandled::TooGeneric` if any of them are
209223
// encountered.
210224
let args = GenericArgs::identity_for_item(self.tcx, def_id);
211-
let instance = ty::Instance::new(def_id, self.tcx.erase_regions(args));
212-
let cid = GlobalId { instance, promoted: None };
213225
let typing_env = ty::TypingEnv::post_analysis(self.tcx, def_id);
226+
let instance = ty::Instance::expect_resolve(
227+
self.tcx,
228+
typing_env,
229+
def_id,
230+
self.tcx.erase_regions(args),
231+
DUMMY_SP,
232+
);
233+
let cid = GlobalId { instance, promoted: None };
214234
// Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should
215235
// improve caching of queries.
216236
let inputs = self.tcx.erase_regions(typing_env.as_query_input(cid));

compiler/rustc_middle/src/mir/mono.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ impl<'tcx> fmt::Display for MonoItem<'tcx> {
318318
match *self {
319319
MonoItem::Fn(instance) => write!(f, "fn {instance}"),
320320
MonoItem::Static(def_id) => {
321-
write!(f, "static {}", Instance::new(def_id, GenericArgs::empty()))
321+
write!(f, "static {}", Instance::new_raw(def_id, GenericArgs::empty()))
322322
}
323323
MonoItem::GlobalAsm(..) => write!(f, "global_asm"),
324324
}

compiler/rustc_middle/src/query/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2471,7 +2471,7 @@ rustc_queries! {
24712471
query resolve_instance_raw(
24722472
key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgsRef<'tcx>)>
24732473
) -> Result<Option<ty::Instance<'tcx>>, ErrorGuaranteed> {
2474-
desc { "resolving instance `{}`", ty::Instance::new(key.value.0, key.value.1) }
2474+
desc { |tcx| "resolving instance `{}`", tcx.def_path_str_with_args(key.value.0, key.value.1) }
24752475
}
24762476

24772477
query reveal_opaque_types_in_bounds(key: ty::Clauses<'tcx>) -> ty::Clauses<'tcx> {

compiler/rustc_middle/src/ty/instance.rs

+13-5
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,15 @@ fn resolve_async_drop_poll<'tcx>(mut cor_ty: Ty<'tcx>) -> Instance<'tcx> {
491491
}
492492

493493
impl<'tcx> Instance<'tcx> {
494-
pub fn new(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> {
494+
/// Creates a new [`InstanceKind::Item`] from the `def_id` and `args`.
495+
///
496+
/// Note that this item corresponds to the body of `def_id` directly, which
497+
/// likely does not make sense for trait items which need to be resolved to an
498+
/// implementation, and which may not even have a body themselves. Usages of
499+
/// this function should probably use [`Instance::expect_resolve`], or if run
500+
/// in a polymorphic environment or within a lint (that may encounter ambiguity)
501+
/// [`Instance::try_resolve`] instead.
502+
pub fn new_raw(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> {
495503
assert!(
496504
!args.has_escaping_bound_vars(),
497505
"args of instance {def_id:?} has escaping bound vars: {args:?}"
@@ -510,7 +518,7 @@ impl<'tcx> Instance<'tcx> {
510518
}
511519
});
512520

513-
Instance::new(def_id, args)
521+
Instance::new_raw(def_id, args)
514522
}
515523

516524
#[inline]
@@ -603,7 +611,7 @@ impl<'tcx> Instance<'tcx> {
603611
let type_length = type_length(args);
604612
if !tcx.type_length_limit().value_within_limit(type_length) {
605613
let (shrunk, written_to_path) =
606-
shrunk_instance_name(tcx, Instance::new(def_id, args));
614+
shrunk_instance_name(tcx, Instance::new_raw(def_id, args));
607615
let mut path = PathBuf::new();
608616
let was_written = if let Some(path2) = written_to_path {
609617
path = path2;
@@ -773,7 +781,7 @@ impl<'tcx> Instance<'tcx> {
773781

774782
match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
775783
Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, args),
776-
_ => Instance::new(def_id, args),
784+
_ => Instance::new_raw(def_id, args),
777785
}
778786
}
779787

@@ -899,7 +907,7 @@ impl<'tcx> Instance<'tcx> {
899907
// This is important for `Iterator`'s combinators, but also useful for
900908
// adding future default methods to `Future`, for instance.
901909
debug_assert!(tcx.defaultness(trait_item_id).has_value());
902-
Some(Instance::new(trait_item_id, rcvr_args))
910+
Some(Instance::new_raw(trait_item_id, rcvr_args))
903911
}
904912
}
905913

compiler/rustc_monomorphize/src/collector.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -913,7 +913,7 @@ fn visit_instance_use<'tcx>(
913913
// We explicitly skip this otherwise to ensure we get a linker error
914914
// if anyone tries to call this intrinsic and the codegen backend did not
915915
// override the implementation.
916-
let instance = ty::Instance::new(instance.def_id(), instance.args);
916+
let instance = ty::Instance::new_raw(instance.def_id(), instance.args);
917917
if tcx.should_codegen_locally(instance) {
918918
output.push(create_fn_mono_item(tcx, instance, source));
919919
}
@@ -1502,7 +1502,7 @@ impl<'v> RootCollector<'_, 'v> {
15021502
ty::Closure(def_id, args)
15031503
| ty::Coroutine(def_id, args)
15041504
| ty::CoroutineClosure(def_id, args) => {
1505-
Instance::new(def_id, self.tcx.erase_regions(args))
1505+
Instance::new_raw(def_id, self.tcx.erase_regions(args))
15061506
}
15071507
_ => unreachable!(),
15081508
};

compiler/rustc_smir/src/rustc_smir/builder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ impl<'tcx> BodyBuilder<'tcx> {
2222
pub(crate) fn new(tcx: TyCtxt<'tcx>, instance: ty::Instance<'tcx>) -> Self {
2323
let instance = match instance.def {
2424
// To get the fallback body of an intrinsic, we need to convert it to an item.
25-
ty::InstanceKind::Intrinsic(def_id) => ty::Instance::new(def_id, instance.args),
25+
ty::InstanceKind::Intrinsic(def_id) => ty::Instance::new_raw(def_id, instance.args),
2626
_ => instance,
2727
};
2828
BodyBuilder { tcx, instance }

compiler/rustc_symbol_mangling/src/test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl SymbolNamesTest<'_> {
5656
// some subset.
5757
for attr in tcx.get_attrs(def_id, SYMBOL_NAME) {
5858
let def_id = def_id.to_def_id();
59-
let instance = Instance::new(
59+
let instance = Instance::new_raw(
6060
def_id,
6161
tcx.erase_regions(GenericArgs::identity_for_item(tcx, def_id)),
6262
);

compiler/rustc_ty_utils/src/instance.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ fn resolve_associated_item<'tcx>(
235235
tcx.ensure_ok().compare_impl_item(leaf_def_item)?;
236236
}
237237

238-
Some(ty::Instance::new(leaf_def.item.def_id, args))
238+
Some(ty::Instance::new_raw(leaf_def.item.def_id, args))
239239
}
240240
traits::ImplSource::Builtin(BuiltinImplSource::Object(_), _) => {
241241
let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_args);
@@ -280,7 +280,7 @@ fn resolve_associated_item<'tcx>(
280280

281281
// Use the default `fn clone_from` from `trait Clone`.
282282
let args = tcx.erase_regions(rcvr_args);
283-
Some(ty::Instance::new(trait_item_id, args))
283+
Some(ty::Instance::new_raw(trait_item_id, args))
284284
}
285285
} else if tcx.is_lang_item(trait_ref.def_id, LangItem::FnPtrTrait) {
286286
if tcx.is_lang_item(trait_item_id, LangItem::FnPtrAddr) {
@@ -329,7 +329,7 @@ fn resolve_associated_item<'tcx>(
329329
// sync with the built-in trait implementations (since all of the
330330
// implementations return `FnOnce::Output`).
331331
if ty::ClosureKind::FnOnce == args.as_coroutine_closure().kind() {
332-
Some(Instance::new(coroutine_closure_def_id, args))
332+
Some(Instance::new_raw(coroutine_closure_def_id, args))
333333
} else {
334334
Some(Instance {
335335
def: ty::InstanceKind::ConstructCoroutineInClosureShim {
@@ -362,7 +362,7 @@ fn resolve_associated_item<'tcx>(
362362
args,
363363
})
364364
} else {
365-
Some(Instance::new(coroutine_closure_def_id, args))
365+
Some(Instance::new_raw(coroutine_closure_def_id, args))
366366
}
367367
}
368368
ty::Closure(closure_def_id, args) => {
@@ -381,7 +381,7 @@ fn resolve_associated_item<'tcx>(
381381
let name = tcx.item_name(trait_item_id);
382382
assert_eq!(name, sym::transmute);
383383
let args = tcx.erase_regions(rcvr_args);
384-
Some(ty::Instance::new(trait_item_id, args))
384+
Some(ty::Instance::new_raw(trait_item_id, args))
385385
} else {
386386
Instance::try_resolve_item_for_coroutine(tcx, trait_item_id, trait_id, rcvr_args)
387387
}

src/tools/clippy/clippy_lints/src/non_copy_const.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -263,12 +263,12 @@ impl<'tcx> NonCopyConst<'tcx> {
263263
fn is_value_unfrozen_poly(cx: &LateContext<'tcx>, body_id: BodyId, ty: Ty<'tcx>) -> bool {
264264
let def_id = body_id.hir_id.owner.to_def_id();
265265
let args = ty::GenericArgs::identity_for_item(cx.tcx, def_id);
266-
let instance = ty::Instance::new(def_id, args);
266+
let typing_env = ty::TypingEnv::post_analysis(cx.tcx, def_id);
267+
let instance = ty::Instance::expect_resolve(self.tcx,typing_env,def_id, args, DUMMY_SP);
267268
let cid = GlobalId {
268269
instance,
269270
promoted: None,
270271
};
271-
let typing_env = ty::TypingEnv::post_analysis(cx.tcx, def_id);
272272
let result = cx.tcx.const_eval_global_id_for_typeck(typing_env, cid, DUMMY_SP);
273273
Self::is_value_unfrozen_raw(cx, result, ty)
274274
}

0 commit comments

Comments
 (0)