1use std::{fmt, iter, mem};
2
3use itertools::Itertools;
4use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
5use rustc_data_structures::thin_vec::ThinVec;
6use rustc_hir::lang_items::LangItem;
7use rustc_hir::{CoroutineDesugaring, CoroutineKind};
8use rustc_index::Idx;
9use rustc_middle::mir::*;
10use rustc_middle::ty::adjustment::PointerCoercion;
11use rustc_middle::ty::util::{Discr, IntTypeExt};
12use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt};
13use rustc_middle::{bug, span_bug};
14use rustc_span::{DUMMY_SP, dummy_spanned};
15use tracing::{debug, instrument};
16
17use crate::coroutine::CTX_ARG;
18use crate::patch::MirPatch;
19
20#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropStyle {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
DropStyle::Dead => "Dead",
DropStyle::Static => "Static",
DropStyle::Conditional => "Conditional",
DropStyle::Open => "Open",
})
}
}Debug)]
22pub(crate) enum DropStyle {
23 Dead,
25
26 Static,
29
30 Conditional,
32
33 Open,
39}
40
41#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropFlagMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
DropFlagMode::Shallow => "Shallow",
DropFlagMode::Deep => "Deep",
})
}
}Debug)]
43pub(crate) enum DropFlagMode {
44 Shallow,
46 Deep,
48}
49
50#[derive(#[automatically_derived]
impl ::core::marker::Copy for Unwind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Unwind {
#[inline]
fn clone(&self) -> Unwind {
let _: ::core::clone::AssertParamIsClone<BasicBlock>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Unwind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Unwind::To(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "To",
&__self_0),
Unwind::InCleanup =>
::core::fmt::Formatter::write_str(f, "InCleanup"),
}
}
}Debug)]
52pub(crate) enum Unwind {
53 To(BasicBlock),
55 InCleanup,
57}
58
59impl Unwind {
60 fn is_cleanup(self) -> bool {
61 match self {
62 Unwind::To(..) => false,
63 Unwind::InCleanup => true,
64 }
65 }
66
67 fn into_action(self) -> UnwindAction {
68 match self {
69 Unwind::To(bb) => UnwindAction::Cleanup(bb),
70 Unwind::InCleanup => UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
71 }
72 }
73
74 fn map<F>(self, f: F) -> Self
75 where
76 F: FnOnce(BasicBlock) -> BasicBlock,
77 {
78 match self {
79 Unwind::To(bb) => Unwind::To(f(bb)),
80 Unwind::InCleanup => Unwind::InCleanup,
81 }
82 }
83}
84
85pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {
86 type Path: Copy + fmt::Debug;
92
93 fn patch_ref(&self) -> &MirPatch<'tcx>;
96 fn patch(&mut self) -> &mut MirPatch<'tcx>;
97 fn body(&self) -> &'a Body<'tcx>;
98 fn tcx(&self) -> TyCtxt<'tcx>;
99 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
100 fn allow_async_drops(&self) -> bool;
101
102 fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
106
107 fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
109
110 fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
115
116 fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path>;
122
123 fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
129
130 fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
134
135 fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path>;
141}
142
143#[derive(#[automatically_derived]
impl<'a, 'b, 'tcx, D: ::core::fmt::Debug> ::core::fmt::Debug for
DropCtxt<'a, 'b, 'tcx, D> where D: DropElaborator<'b, 'tcx>,
D::Path: ::core::fmt::Debug {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["elaborator", "source_info", "place", "path", "succ", "unwind",
"dropline"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.elaborator, &self.source_info, &self.place, &self.path,
&self.succ, &self.unwind, &&self.dropline];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DropCtxt",
names, values)
}
}Debug)]
144struct DropCtxt<'a, 'b, 'tcx, D>
145where
146 D: DropElaborator<'b, 'tcx>,
147{
148 elaborator: &'a mut D,
149
150 source_info: SourceInfo,
151
152 place: Place<'tcx>,
153 path: D::Path,
154 succ: BasicBlock,
155 unwind: Unwind,
156 dropline: Option<BasicBlock>,
157}
158
159pub(crate) fn elaborate_drop<'b, 'tcx, D>(
168 elaborator: &mut D,
169 source_info: SourceInfo,
170 place: Place<'tcx>,
171 path: D::Path,
172 succ: BasicBlock,
173 unwind: Unwind,
174 bb: BasicBlock,
175 dropline: Option<BasicBlock>,
176) where
177 D: DropElaborator<'b, 'tcx>,
178 'tcx: 'b,
179{
180 DropCtxt { elaborator, source_info, place, path, succ, unwind, dropline }.elaborate_drop(bb)
181}
182
183impl<'a, 'b, 'tcx, D> DropCtxt<'a, 'b, 'tcx, D>
184where
185 D: DropElaborator<'b, 'tcx>,
186 'tcx: 'b,
187{
188 x;#[instrument(level = "trace", skip(self), ret)]
189 fn place_ty(&self, place: Place<'tcx>) -> Ty<'tcx> {
190 if place.local < self.elaborator.body().local_decls.next_index() {
191 place.ty(self.elaborator.body(), self.tcx()).ty
192 } else {
193 PlaceTy::from_ty(self.elaborator.patch_ref().local_ty(place.local))
195 .multi_projection_ty(self.elaborator.tcx(), place.projection)
196 .ty
197 }
198 }
199
200 fn tcx(&self) -> TyCtxt<'tcx> {
201 self.elaborator.tcx()
202 }
203
204 x;#[instrument(level = "debug", skip(self), ret)]
229 fn build_async_drop(
230 &mut self,
231 place: Place<'tcx>,
232 drop_ty: Ty<'tcx>,
233 succ: BasicBlock,
234 unwind: Unwind,
235 dropline: Option<BasicBlock>,
236 call_destructor_only: bool,
237 ) -> BasicBlock {
238 let tcx = self.tcx();
239 let span = self.source_info.span;
240 let obj_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, drop_ty);
241
242 let async_drop_fn_def_id = if call_destructor_only {
243 let async_drop_trait = tcx.require_lang_item(LangItem::AsyncDrop, span);
245 tcx.associated_item_def_ids(async_drop_trait)[0]
246 } else {
247 tcx.require_lang_item(LangItem::AsyncDropInPlace, span)
249 };
250
251 let fut_ty = tcx
252 .instantiate_bound_regions_with_erased(
253 Ty::new_fn_def(tcx, async_drop_fn_def_id, ty::Binder::dummy([drop_ty])).fn_sig(tcx),
255 )
256 .output();
257 let fut = self.new_temp(fut_ty);
258
259 let succ_with_dead = self.new_block_with_statements(
263 unwind,
264 vec![self.storage_dead(fut)],
265 TerminatorKind::Goto { target: succ },
266 );
267 let dropline_with_dead = dropline.map(|target| {
268 self.new_block_with_statements(
269 unwind,
270 vec![self.storage_dead(fut)],
271 TerminatorKind::Goto { target },
272 )
273 });
274 let unwind_with_dead = unwind.map(|target| {
275 self.new_block_with_statements(
276 Unwind::InCleanup,
277 vec![self.storage_dead(fut)],
278 TerminatorKind::Goto { target },
279 )
280 });
281
282 let coroutine_kind = self.elaborator.body().coroutine_kind().unwrap();
284 let yield_value = match coroutine_kind {
285 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
287 let full_yield_ty = self.elaborator.body().yield_ty().unwrap();
288 let ty::Adt(_poll_adt, args) = *full_yield_ty.kind() else { bug!() };
289 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
290 let yield_ty = args.type_at(0);
291 Operand::unevaluated_constant(
292 tcx,
293 tcx.require_lang_item(LangItem::AsyncGenPending, span),
294 tcx.mk_args(&[yield_ty.into()]),
295 span,
296 )
297 }
298 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
300 Operand::zero_sized_constant(tcx.types.unit, span)
301 }
302 _ => panic!("unexpected coroutine for async drop {coroutine_kind:?}"),
304 };
305
306 let panic_bb = self.build_resumed_after_drop_abort_block(unwind_with_dead, coroutine_kind);
315 let (drop_pin_bb, drop_resume_bb, drop_drop_bb) = self.build_pin_poll_yield_loop(
316 CTX_ARG.into(),
317 fut.into(),
318 yield_value.clone(),
319 dropline_with_dead.unwrap_or(succ_with_dead),
322 unwind_with_dead,
323 );
324 self.elaborator
325 .patch()
326 .patch_terminator(drop_resume_bb, TerminatorKind::Goto { target: panic_bb });
327 self.elaborator
328 .patch()
329 .patch_terminator(drop_drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
330
331 let succ_yield_loop = if dropline_with_dead.is_some() {
338 let (pin_bb, resume_bb, drop_bb) = self.build_pin_poll_yield_loop(
339 CTX_ARG.into(),
340 fut.into(),
341 yield_value,
342 succ_with_dead,
344 unwind_with_dead,
345 );
346 self.elaborator
347 .patch()
348 .patch_terminator(resume_bb, TerminatorKind::Goto { target: pin_bb });
349 self.elaborator
350 .patch()
351 .patch_terminator(drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
352 pin_bb
353 } else {
354 drop_pin_bb
356 };
357
358 let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
362 let pin_obj_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[obj_ref_ty.into()]));
363 let pin_obj_local = self.new_temp(pin_obj_ty);
365 let drop_arg = if call_destructor_only {
366 Operand::Move(pin_obj_local.into())
368 } else {
369 Operand::Copy(tcx.mk_place_field(pin_obj_local.into(), FieldIdx::ZERO, obj_ref_ty))
371 };
372 let call_drop_bb = self.new_block_with_statements(
373 unwind_with_dead,
374 vec![self.storage_live(fut)],
375 TerminatorKind::Call {
376 func: Operand::function_handle(tcx, async_drop_fn_def_id, &[drop_ty.into()], span),
378 args: [dummy_spanned(drop_arg)].into(),
379 destination: fut.into(),
380 target: Some(succ_yield_loop),
381 unwind: unwind_with_dead.into_action(),
382 call_source: CallSource::Misc,
383 fn_span: self.source_info.span,
384 },
385 );
386
387 let obj_ref_place = Place::from(self.new_temp(obj_ref_ty));
389 let pin_obj_new_unchecked_fn = tcx.require_lang_item(LangItem::PinNewUnchecked, span);
390 let assign_obj_ref_place = self.assign(
391 obj_ref_place,
392 Rvalue::Ref(
393 tcx.lifetimes.re_erased,
394 BorrowKind::Mut { kind: MutBorrowKind::Default },
395 place,
396 ),
397 );
398 self.new_block_with_statements(
399 unwind,
400 vec![assign_obj_ref_place],
401 TerminatorKind::Call {
402 func: Operand::function_handle(
403 tcx,
404 pin_obj_new_unchecked_fn,
405 &[obj_ref_ty.into()],
407 span,
408 ),
409 args: [dummy_spanned(Operand::Move(obj_ref_place))].into(),
410 destination: pin_obj_local.into(),
411 target: Some(call_drop_bb),
412 unwind: unwind.into_action(),
413 call_source: CallSource::Misc,
414 fn_span: span,
415 },
416 )
417 }
418
419 fn build_resumed_after_drop_abort_block(
420 &mut self,
421 unwind: Unwind,
422 coroutine_kind: CoroutineKind,
423 ) -> BasicBlock {
424 let tcx = self.tcx();
425 let panic_bb = self.new_block(unwind, TerminatorKind::Unreachable);
426 let msg = AssertMessage::ResumedAfterDrop(coroutine_kind);
427 let false_op = Operand::Constant(Box::new(ConstOperand {
428 span: self.source_info.span,
429 user_ty: None,
430 const_: Const::from_bool(tcx, false),
431 }));
432 self.elaborator.patch().patch_terminator(
433 panic_bb,
434 TerminatorKind::Assert {
435 cond: false_op,
436 expected: true,
437 msg: Box::new(msg),
438 target: panic_bb,
439 unwind: unwind.into_action(),
440 },
441 );
442 panic_bb
443 }
444
445 x;#[instrument(level = "trace", skip(self), ret)]
461 fn build_pin_poll_yield_loop(
462 &mut self,
463 resume_place: Place<'tcx>,
464 fut_place: Place<'tcx>,
465 yield_value: Operand<'tcx>,
466 succ: BasicBlock,
467 unwind: Unwind,
468 ) -> (BasicBlock, BasicBlock, BasicBlock) {
469 let tcx = self.tcx();
470 let source_info = self.source_info;
471
472 let resume_arg_ty = resume_place.ty(self.elaborator.body(), tcx).ty;
473 let context_ref_ty = Ty::new_task_context(tcx);
474
475 let poll_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Poll, source_info.span));
476 let poll_enum = Ty::new_adt(tcx, poll_adt_def, tcx.mk_args(&[tcx.types.unit.into()]));
477
478 let fut_ty = self.elaborator.patch_ref().local_ty(fut_place.local);
479 let fut_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, fut_ty);
480
481 let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, source_info.span));
482 let fut_pin_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[fut_ref_ty.into()]));
483
484 let yield_resume_local = self.new_temp(resume_arg_ty);
487 let resume_bb = self.new_block_with_statements(
488 unwind,
489 vec![
490 self.assign(
491 resume_place,
492 Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
493 ),
494 self.storage_dead(yield_resume_local),
495 ],
496 TerminatorKind::Unreachable,
498 );
499 let dropline_bb = self.new_block_with_statements(
500 unwind,
501 vec![
502 self.assign(
503 resume_place,
504 Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
505 ),
506 self.storage_dead(yield_resume_local),
507 ],
508 TerminatorKind::Unreachable,
510 );
511 let yield_bb = self.new_block_with_statements(
512 unwind,
513 vec![self.storage_live(yield_resume_local)],
514 TerminatorKind::Yield {
515 value: yield_value,
516 resume: resume_bb,
517 resume_arg: yield_resume_local.into(),
518 drop: Some(dropline_bb),
519 },
520 );
521
522 let poll_unit_local = self.new_temp(poll_enum);
523 let switch_bb = {
524 let poll_ready_variant =
525 tcx.require_lang_item(LangItem::PollReady, self.source_info.span);
526 let poll_ready_variant_idx = poll_adt_def.variant_index_with_id(poll_ready_variant);
527 let poll_pending_variant =
528 tcx.require_lang_item(LangItem::PollPending, self.source_info.span);
529 let poll_pending_variant_idx = poll_adt_def.variant_index_with_id(poll_pending_variant);
530
531 let Discr { val: poll_ready_discr, ty: poll_discr_ty } =
532 poll_enum.discriminant_for_variant(tcx, poll_ready_variant_idx).unwrap();
533 let Discr { val: poll_pending_discr, ty: _ } =
534 poll_enum.discriminant_for_variant(tcx, poll_pending_variant_idx).unwrap();
535
536 let poll_discr_local = self.new_temp(poll_discr_ty);
537 let otherwise_bb = self.elaborator.patch().unreachable_no_cleanup_block();
538 self.new_block_with_statements(
539 unwind,
540 vec![
541 self.assign(
542 poll_discr_local.into(),
543 Rvalue::Discriminant(poll_unit_local.into()),
544 ),
545 ],
546 TerminatorKind::SwitchInt {
547 discr: Operand::Move(poll_discr_local.into()),
548 targets: SwitchTargets::new(
549 [
550 (poll_ready_discr, succ),
552 (poll_pending_discr, yield_bb),
554 ]
555 .into_iter(),
556 otherwise_bb,
558 ),
559 },
560 )
561 };
562
563 let fut_pin_local = self.new_temp(fut_pin_ty);
564 let context_ref_local = self.new_temp(context_ref_ty);
565
566 let poll_fn = tcx.require_lang_item(LangItem::FuturePoll, source_info.span);
567 let poll_bb = self.new_block_with_statements(
568 unwind,
569 Vec::new(),
570 TerminatorKind::Call {
571 func: Operand::function_handle(tcx, poll_fn, &[fut_ty.into()], source_info.span),
573 args: [
574 dummy_spanned(Operand::Move(fut_pin_local.into())),
575 dummy_spanned(Operand::Move(context_ref_local.into())),
576 ]
577 .into(),
578 destination: poll_unit_local.into(),
579 target: Some(switch_bb),
580 unwind: unwind.into_action(),
581 call_source: CallSource::Misc,
582 fn_span: source_info.span,
583 },
584 );
585
586 let get_context_fn = tcx.require_lang_item(LangItem::GetContext, source_info.span);
587 let get_context_bb = {
588 let entry_resume_local = self.new_temp(resume_arg_ty);
591 self.new_block_with_statements(
592 unwind,
593 vec![self.assign(
594 entry_resume_local.into(),
595 Rvalue::Use(Operand::Move(resume_place), WithRetag::Yes),
596 )],
597 TerminatorKind::Call {
598 func: Operand::function_handle(
599 tcx,
600 get_context_fn,
601 &[tcx.lifetimes.re_erased.into(), tcx.lifetimes.re_erased.into()],
603 source_info.span,
604 ),
605 args: [dummy_spanned(Operand::Move(entry_resume_local.into()))].into(),
606 destination: context_ref_local.into(),
607 target: Some(poll_bb),
608 unwind: unwind.into_action(),
609 call_source: CallSource::Misc,
610 fn_span: source_info.span,
611 },
612 )
613 };
614
615 let fut_ref_local = self.new_temp(fut_ref_ty);
616 let fut_pin_new_unchecked_fn =
617 tcx.require_lang_item(LangItem::PinNewUnchecked, source_info.span);
618 let pin_bb = self.new_block_with_statements(
619 unwind,
620 vec![self.assign(
621 fut_ref_local.into(),
622 Rvalue::Ref(
623 tcx.lifetimes.re_erased,
624 BorrowKind::Mut { kind: MutBorrowKind::Default },
625 fut_place,
626 ),
627 )],
628 TerminatorKind::Call {
629 func: Operand::function_handle(
630 tcx,
631 fut_pin_new_unchecked_fn,
632 &[fut_ref_ty.into()],
633 source_info.span,
634 ),
635 args: [dummy_spanned(Operand::Move(fut_ref_local.into()))].into(),
636 destination: fut_pin_local.into(),
637 target: Some(get_context_bb),
638 unwind: unwind.into_action(),
639 call_source: CallSource::Misc,
640 fn_span: source_info.span,
641 },
642 );
643
644 (pin_bb, resume_bb, dropline_bb)
645 }
646
647 fn build_drop(&mut self, bb: BasicBlock) {
648 let drop_ty = self.place_ty(self.place);
649 if !self.elaborator.patch_ref().block(self.elaborator.body(), bb).is_cleanup
650 && self.check_if_can_async_drop(drop_ty, false)
651 {
652 let async_drop_bb = self.build_async_drop(
653 self.place,
654 drop_ty,
655 self.succ,
656 self.unwind,
657 self.dropline,
658 false,
659 );
660 self.elaborator
661 .patch()
662 .patch_terminator(bb, TerminatorKind::Goto { target: async_drop_bb });
663 } else {
664 self.elaborator.patch().patch_terminator(
665 bb,
666 TerminatorKind::Drop {
667 place: self.place,
668 target: self.succ,
669 unwind: self.unwind.into_action(),
670 replace: false,
671 drop: None,
672 },
673 );
674 }
675 }
676
677 fn check_if_can_async_drop(&mut self, drop_ty: Ty<'tcx>, call_destructor_only: bool) -> bool {
679 if !self.elaborator.allow_async_drops()
680 || !self
681 .elaborator
682 .body()
683 .coroutine
684 .as_ref()
685 .is_some_and(|ck| ck.coroutine_kind.is_async_desugaring())
686 {
687 return false;
688 }
689
690 if drop_ty == self.place_ty(Local::arg(0).into()) {
691 return false;
692 }
693
694 let is_async_drop_feature_enabled = if self.tcx().features().async_drop() {
695 true
696 } else {
697 if let ty::Adt(adt_def, _) = drop_ty.kind() {
699 !adt_def.did().is_local() && adt_def.async_destructor(self.tcx()).is_some()
700 } else {
701 false
702 }
703 };
704
705 if !is_async_drop_feature_enabled {
709 return false;
710 }
711
712 let needs_async_drop = if call_destructor_only {
713 drop_ty.is_async_drop(self.tcx(), self.elaborator.typing_env())
714 } else {
715 drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
716 };
717
718 if needs_async_drop && self.tcx().features().staged_api() {
720 ::rustc_middle::util::bug::span_bug_fmt(self.source_info.span,
format_args!("don\'t use async drop in libstd, it becomes insta-stable"));span_bug!(
721 self.source_info.span,
722 "don't use async drop in libstd, it becomes insta-stable"
723 );
724 }
725
726 needs_async_drop
727 }
728
729 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("elaborate_drop",
"rustc_mir_transform::elaborate_drop",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
::tracing_core::__macro_support::Option::Some(747u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("bb")
}> =
::tracing::__macro_support::FieldName::new("bb");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bb)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
DropStyle::Dead => {
self.elaborator.patch().patch_terminator(bb,
TerminatorKind::Goto { target: self.succ });
}
DropStyle::Static => { self.build_drop(bb); }
DropStyle::Conditional => {
let drop_bb = self.complete_drop(self.succ, self.unwind);
self.elaborator.patch().patch_terminator(bb,
TerminatorKind::Goto { target: drop_bb });
}
DropStyle::Open => {
let drop_bb = self.open_drop();
self.elaborator.patch().patch_terminator(bb,
TerminatorKind::Goto { target: drop_bb });
}
}
}
}
}#[instrument(level = "debug")]
748 fn elaborate_drop(&mut self, bb: BasicBlock) {
749 match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
750 DropStyle::Dead => {
751 self.elaborator
752 .patch()
753 .patch_terminator(bb, TerminatorKind::Goto { target: self.succ });
754 }
755 DropStyle::Static => {
756 self.build_drop(bb);
757 }
758 DropStyle::Conditional => {
759 let drop_bb = self.complete_drop(self.succ, self.unwind);
760 self.elaborator
761 .patch()
762 .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
763 }
764 DropStyle::Open => {
765 let drop_bb = self.open_drop();
766 self.elaborator
767 .patch()
768 .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
769 }
770 }
771 }
772
773 fn move_paths_for_fields(
776 &self,
777 base_place: Place<'tcx>,
778 variant_path: D::Path,
779 variant: &'tcx ty::VariantDef,
780 args: GenericArgsRef<'tcx>,
781 ) -> Vec<(Place<'tcx>, Option<D::Path>)> {
782 variant
783 .fields
784 .iter_enumerated()
785 .map(|(field_idx, field)| {
786 let subpath = self.elaborator.field_subpath(variant_path, field_idx);
787 let tcx = self.tcx();
788
789 match self.elaborator.typing_env().typing_mode().assert_not_erased() {
790 ty::TypingMode::PostAnalysis | ty::TypingMode::Codegen => {}
791 ty::TypingMode::Coherence
792 | ty::TypingMode::Reflection
793 | ty::TypingMode::Typeck { .. }
794 | ty::TypingMode::PostTypeckUntilBorrowck { .. }
795 | ty::TypingMode::PostBorrowck { .. } => {
796 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
797 }
798 }
799
800 let field_ty = field.ty(tcx, args);
801 let field_ty = tcx
804 .try_normalize_erasing_regions(self.elaborator.typing_env(), field_ty)
805 .unwrap_or(field_ty.skip_norm_wip());
806
807 (tcx.mk_place_field(base_place, field_idx, field_ty), subpath)
808 })
809 .filter(|path| self.should_retain_for_ladder(path))
810 .collect()
811 }
812
813 x;#[instrument(level = "debug", skip(self), ret)]
814 fn drop_subpath(
815 &mut self,
816 place: Place<'tcx>,
817 path: Option<D::Path>,
818 succ: BasicBlock,
819 unwind: Unwind,
820 dropline: Option<BasicBlock>,
821 ) -> BasicBlock {
822 if let Some(path) = path {
823 DropCtxt {
824 elaborator: self.elaborator,
825 source_info: self.source_info,
826 path,
827 place,
828 succ,
829 unwind,
830 dropline,
831 }
832 .elaborated_drop_block()
833 } else {
834 DropCtxt {
835 elaborator: self.elaborator,
836 source_info: self.source_info,
837 place,
838 succ,
839 unwind,
840 dropline,
841 path: self.path,
843 }
844 .complete_drop(succ, unwind)
845 }
846 }
847
848 x;#[instrument(level = "debug", skip(self), ret)]
859 fn drop_halfladder(
860 &mut self,
861 unwind_ladder: &[Unwind],
862 dropline_ladder: &[Option<BasicBlock>],
863 mut succ: BasicBlock,
864 fields: &[(Place<'tcx>, Option<D::Path>)],
865 ) -> Vec<BasicBlock> {
866 iter::once(succ)
867 .chain(itertools::izip!(fields.iter().rev(), unwind_ladder, dropline_ladder).map(
868 |(&(place, path), &unwind_succ, &dropline_to)| {
869 succ = self.drop_subpath(place, path, succ, unwind_succ, dropline_to);
870 succ
871 },
872 ))
873 .collect()
874 }
875
876 fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind, Option<BasicBlock>) {
877 (
881 self.drop_flag_reset_block(DropFlagMode::Shallow, self.succ, self.unwind),
882 self.unwind,
883 self.dropline,
884 )
885 }
886
887 fn should_retain_for_ladder(&self, (place, subpath): &(Place<'tcx>, Option<D::Path>)) -> bool {
889 if !self.place_ty(*place).needs_drop(self.tcx(), self.elaborator.typing_env()) {
890 return false;
891 }
892 if let Some(subpath) = subpath
893 && let DropStyle::Dead = self.elaborator.drop_style(*subpath, DropFlagMode::Deep)
894 {
895 return false;
896 }
897 true
898 }
899
900 x;#[instrument(level = "debug", skip(self), ret)]
938 fn drop_ladder(
939 &mut self,
940 mut fields: Vec<(Place<'tcx>, Option<D::Path>)>,
941 succ: BasicBlock,
942 unwind: Unwind,
943 dropline: Option<BasicBlock>,
944 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
945 assert!(
946 if unwind.is_cleanup() { dropline.is_none() } else { true },
947 "Dropline is set for cleanup drop ladder"
948 );
949
950 fields.retain(|path| self.should_retain_for_ladder(path));
951
952 debug!("drop_ladder - fields needing drop: {:?}", fields);
953
954 let dropline_ladder: Vec<Option<BasicBlock>> = vec![None; fields.len() + 1];
955 let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
956 let unwind_ladder: Vec<_> = if let Unwind::To(succ) = unwind {
957 let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
958 halfladder.into_iter().map(Unwind::To).collect()
959 } else {
960 unwind_ladder
961 };
962 let dropline_ladder: Vec<_> = if let Some(succ) = dropline {
963 let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
964 halfladder.into_iter().map(Some).collect()
965 } else {
966 dropline_ladder
967 };
968
969 let normal_ladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
970
971 (
972 *normal_ladder.last().unwrap(),
973 *unwind_ladder.last().unwrap(),
974 *dropline_ladder.last().unwrap(),
975 )
976 }
977
978 x;#[instrument(level = "debug", skip(self), ret)]
979 fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
980 let fields = tys
981 .iter()
982 .enumerate()
983 .map(|(i, &ty)| {
984 (
985 self.tcx().mk_place_field(self.place, FieldIdx::new(i), ty),
986 self.elaborator.field_subpath(self.path, FieldIdx::new(i)),
987 )
988 })
989 .collect();
990
991 let (succ, unwind, dropline) = self.drop_ladder_bottom();
992 self.drop_ladder(fields, succ, unwind, dropline).0
993 }
994
995 x;#[instrument(level = "debug", ret)]
997 fn open_drop_for_box_contents(
998 &mut self,
999 adt: ty::AdtDef<'tcx>,
1000 args: GenericArgsRef<'tcx>,
1001 succ: BasicBlock,
1002 unwind: Unwind,
1003 dropline: Option<BasicBlock>,
1004 ) -> BasicBlock {
1005 let unique_ty =
1008 adt.non_enum_variant().fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1009 let unique_variant = unique_ty.ty_adt_def().unwrap().non_enum_variant();
1010 let nonnull_ty = unique_variant.fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1011 let ptr_ty = Ty::new_imm_ptr(self.tcx(), args[0].expect_ty());
1012
1013 let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
1014 let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
1015
1016 let ptr_local = self.new_temp(ptr_ty);
1017
1018 let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
1019 let interior_path = self.elaborator.deref_subpath(self.path);
1020
1021 let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind, dropline);
1022
1023 self.new_block_with_statements(
1024 unwind,
1025 vec![self.assign(
1026 Place::from(ptr_local),
1027 Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
1028 )],
1029 TerminatorKind::Goto { target: do_drop_bb },
1030 )
1031 }
1032
1033 x;#[instrument(level = "debug", ret)]
1034 fn open_drop_for_adt(
1035 &mut self,
1036 adt: ty::AdtDef<'tcx>,
1037 args: GenericArgsRef<'tcx>,
1038 ) -> BasicBlock {
1039 if adt.variants().is_empty() {
1040 return self.new_block(self.unwind, TerminatorKind::Unreachable);
1041 }
1042
1043 let skip_contents = adt.is_union() || adt.is_manually_drop();
1044 let (contents_succ, contents_unwind, contents_dropline) = if skip_contents {
1045 if adt.has_dtor(self.tcx()) && self.elaborator.get_drop_flag(self.path).is_some() {
1046 span_bug!(self.source_info.span, "open dropping partially moved union");
1053 }
1054
1055 (self.succ, self.unwind, self.dropline)
1056 } else {
1057 self.open_drop_for_adt_contents(adt, args)
1058 };
1059
1060 if adt.has_dtor(self.tcx()) {
1061 let destructor_block = if adt.is_box() {
1062 let succ = self.destructor_call_block_sync(contents_succ, contents_unwind);
1064 let unwind = contents_unwind
1065 .map(|unwind| self.destructor_call_block_sync(unwind, Unwind::InCleanup));
1066 let dropline = contents_dropline
1067 .map(|dropline| self.destructor_call_block_sync(dropline, contents_unwind));
1068 self.open_drop_for_box_contents(adt, args, succ, unwind, dropline)
1069 } else {
1070 self.destructor_call_block(contents_succ, contents_unwind, contents_dropline)
1071 };
1072
1073 self.drop_flag_test_block(destructor_block, contents_succ, contents_unwind)
1074 } else {
1075 contents_succ
1076 }
1077 }
1078
1079 fn open_drop_for_adt_contents(
1080 &mut self,
1081 adt: ty::AdtDef<'tcx>,
1082 args: GenericArgsRef<'tcx>,
1083 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1084 let (succ, unwind, dropline) = self.drop_ladder_bottom();
1085 if !adt.is_enum() {
1086 let fields =
1087 self.move_paths_for_fields(self.place, self.path, adt.variant(FIRST_VARIANT), args);
1088 self.drop_ladder(fields, succ, unwind, dropline)
1089 } else {
1090 self.open_drop_for_multivariant(adt, args, succ, unwind, dropline)
1091 }
1092 }
1093
1094 fn open_drop_for_multivariant(
1095 &mut self,
1096 adt: ty::AdtDef<'tcx>,
1097 args: GenericArgsRef<'tcx>,
1098 succ: BasicBlock,
1099 unwind: Unwind,
1100 dropline: Option<BasicBlock>,
1101 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1102 let mut values = Vec::with_capacity(adt.variants().len());
1103 let mut normal_blocks = Vec::with_capacity(adt.variants().len());
1104 let mut unwind_blocks =
1105 Vec::with_capacity(if unwind.is_cleanup() { 0 } else { adt.variants().len() });
1106 let mut dropline_blocks =
1107 Vec::with_capacity(if dropline.is_none() { 0 } else { adt.variants().len() });
1108
1109 let mut have_otherwise_with_drop_glue = false;
1110 let mut have_otherwise = false;
1111 let tcx = self.tcx();
1112
1113 for (variant_index, discr) in adt.discriminants(tcx) {
1114 let variant = &adt.variant(variant_index);
1115 let subpath = self.elaborator.downcast_subpath(self.path, variant_index);
1116
1117 if let Some(variant_path) = subpath {
1118 let base_place = tcx.mk_place_elem(
1119 self.place,
1120 ProjectionElem::Downcast(Some(variant.name), variant_index),
1121 );
1122 let fields = self.move_paths_for_fields(base_place, variant_path, variant, args);
1123 values.push(discr.val);
1124 if let Unwind::To(unwind) = unwind {
1125 let unwind_ladder = ::alloc::vec::from_elem(Unwind::InCleanup, fields.len() + 1)vec![Unwind::InCleanup; fields.len() + 1];
1144 let dropline_ladder: Vec<Option<BasicBlock>> = ::alloc::vec::from_elem(None, fields.len() + 1)vec![None; fields.len() + 1];
1145 let halfladder =
1146 self.drop_halfladder(&unwind_ladder, &dropline_ladder, unwind, &fields);
1147 unwind_blocks.push(halfladder.last().cloned().unwrap());
1148 }
1149 let (normal, _, drop_bb) = self.drop_ladder(fields, succ, unwind, dropline);
1150 normal_blocks.push(normal);
1151 if dropline.is_some() {
1152 dropline_blocks.push(drop_bb.unwrap());
1153 }
1154 } else {
1155 have_otherwise = true;
1156
1157 let typing_env = self.elaborator.typing_env();
1158 let have_field_with_drop_glue = variant
1159 .fields
1160 .iter()
1161 .any(|field| field.ty(tcx, args).skip_norm_wip().needs_drop(tcx, typing_env));
1162 if have_field_with_drop_glue {
1163 have_otherwise_with_drop_glue = true;
1164 }
1165 }
1166 }
1167
1168 if !have_otherwise {
1169 values.pop();
1170 } else if !have_otherwise_with_drop_glue {
1171 normal_blocks.push(succ);
1172 if let Unwind::To(unwind) = unwind {
1173 unwind_blocks.push(unwind);
1174 }
1175 if let Some(dropline) = dropline {
1176 dropline_blocks.push(dropline);
1177 }
1178 } else {
1179 normal_blocks.push(self.drop_block(succ, unwind));
1180 if let Unwind::To(unwind) = unwind {
1181 unwind_blocks.push(self.drop_block(unwind, Unwind::InCleanup));
1182 }
1183 if let Some(dropline) = dropline {
1184 dropline_blocks.push(self.drop_block(dropline, unwind));
1185 }
1186 }
1187
1188 (
1189 self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
1190 unwind.map(|unwind| {
1191 self.adt_switch_block(adt, unwind_blocks, &values, unwind, Unwind::InCleanup)
1192 }),
1193 dropline.map(|dropline| {
1194 self.adt_switch_block(adt, dropline_blocks, &values, dropline, unwind)
1195 }),
1196 )
1197 }
1198
1199 fn adt_switch_block(
1200 &mut self,
1201 adt: ty::AdtDef<'tcx>,
1202 blocks: Vec<BasicBlock>,
1203 values: &[u128],
1204 succ: BasicBlock,
1205 unwind: Unwind,
1206 ) -> BasicBlock {
1207 let switch_block = blocks.iter().copied().all_equal_value().unwrap_or_else(|_| {
1208 let discr_ty = adt.repr().discr_type().to_ty(self.tcx());
1216 let discr = Place::from(self.new_temp(discr_ty));
1217 let discr_rv = Rvalue::Discriminant(self.place);
1218 self.new_block_with_statements(
1219 unwind,
1220 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.assign(discr, discr_rv)]))vec![self.assign(discr, discr_rv)],
1221 TerminatorKind::SwitchInt {
1222 discr: Operand::Move(discr),
1223 targets: SwitchTargets::new(
1224 values.iter().copied().zip(blocks.iter().copied()),
1225 *blocks.last().unwrap(),
1226 ),
1227 },
1228 )
1229 });
1230 self.drop_flag_test_block(switch_block, succ, unwind)
1231 }
1232
1233 x;#[instrument(level = "debug", skip(self), ret)]
1234 fn destructor_call_block_sync(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1235 let tcx = self.tcx();
1236 let drop_trait = tcx.require_lang_item(LangItem::Drop, DUMMY_SP);
1237 let drop_fn = tcx.associated_item_def_ids(drop_trait)[0];
1238 let ty = self.place_ty(self.place);
1239
1240 let ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
1241 let ref_place = self.new_temp(ref_ty);
1242 let unit_temp = Place::from(self.new_temp(tcx.types.unit));
1243
1244 self.new_block_with_statements(
1245 unwind,
1246 vec![self.assign(
1247 Place::from(ref_place),
1248 Rvalue::Ref(
1249 tcx.lifetimes.re_erased,
1250 BorrowKind::Mut { kind: MutBorrowKind::Default },
1251 self.place,
1252 ),
1253 )],
1254 TerminatorKind::Call {
1255 func: Operand::function_handle(tcx, drop_fn, &[ty.into()], self.source_info.span),
1257 args: [dummy_spanned(Operand::Move(Place::from(ref_place)))].into(),
1258 destination: unit_temp,
1259 target: Some(succ),
1260 unwind: unwind.into_action(),
1261 call_source: CallSource::Misc,
1262 fn_span: self.source_info.span,
1263 },
1264 )
1265 }
1266
1267 x;#[instrument(level = "debug", skip(self), ret)]
1268 fn destructor_call_block(
1269 &mut self,
1270 succ: BasicBlock,
1271 unwind: Unwind,
1272 dropline: Option<BasicBlock>,
1273 ) -> BasicBlock {
1274 let ty = self.place_ty(self.place);
1275 if !unwind.is_cleanup() && self.check_if_can_async_drop(ty, true) {
1276 self.build_async_drop(self.place, ty, succ, unwind, dropline, true)
1277 } else {
1278 self.destructor_call_block_sync(succ, unwind)
1279 }
1280 }
1281
1282 fn drop_loop(
1294 &mut self,
1295 succ: BasicBlock,
1296 cur: Local,
1297 len: Local,
1298 ety: Ty<'tcx>,
1299 unwind: Unwind,
1300 dropline: Option<BasicBlock>,
1301 ) -> BasicBlock {
1302 let copy = |place: Place<'tcx>| Operand::Copy(place);
1303 let move_ = |place: Place<'tcx>| Operand::Move(place);
1304 let tcx = self.tcx();
1305
1306 let ptr_ty = Ty::new_mut_ptr(tcx, ety);
1307 let ptr = Place::from(self.new_temp(ptr_ty));
1308 let can_go = Place::from(self.new_temp(tcx.types.bool));
1309 let one = self.constant_usize(1);
1310
1311 let drop_block = self.new_block_with_statements(
1312 unwind,
1313 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.assign(ptr,
Rvalue::RawPtr(RawPtrKind::Mut,
tcx.mk_place_index(self.place, cur))),
self.assign(cur.into(),
Rvalue::BinaryOp(BinOp::Add,
Box::new((move_(cur.into()), one))))]))vec![
1314 self.assign(
1315 ptr,
1316 Rvalue::RawPtr(RawPtrKind::Mut, tcx.mk_place_index(self.place, cur)),
1317 ),
1318 self.assign(
1319 cur.into(),
1320 Rvalue::BinaryOp(BinOp::Add, Box::new((move_(cur.into()), one))),
1321 ),
1322 ],
1323 TerminatorKind::Unreachable,
1325 );
1326
1327 let loop_block = self.new_block_with_statements(
1328 unwind,
1329 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.assign(can_go,
Rvalue::BinaryOp(BinOp::Eq,
Box::new((copy(Place::from(cur)), copy(len.into())))))]))vec![self.assign(
1330 can_go,
1331 Rvalue::BinaryOp(BinOp::Eq, Box::new((copy(Place::from(cur)), copy(len.into())))),
1332 )],
1333 TerminatorKind::if_(move_(can_go), succ, drop_block),
1334 );
1335
1336 let place = tcx.mk_place_deref(ptr);
1337 if !unwind.is_cleanup() && self.check_if_can_async_drop(ety, false) {
1338 let async_drop_bb =
1339 self.build_async_drop(place, ety, loop_block, unwind, dropline, false);
1340 self.elaborator
1341 .patch()
1342 .patch_terminator(drop_block, TerminatorKind::Goto { target: async_drop_bb });
1343 } else {
1344 self.elaborator.patch().patch_terminator(
1345 drop_block,
1346 TerminatorKind::Drop {
1347 place,
1348 target: loop_block,
1349 unwind: unwind.into_action(),
1350 replace: false,
1351 drop: None,
1352 },
1353 );
1354 }
1355 loop_block
1356 }
1357
1358 x;#[instrument(level = "debug", skip(self), ret)]
1359 fn open_drop_for_array(
1360 &mut self,
1361 array_ty: Ty<'tcx>,
1362 ety: Ty<'tcx>,
1363 opt_size: Option<u64>,
1364 ) -> BasicBlock {
1365 let tcx = self.tcx();
1366
1367 if let Some(size) = opt_size {
1368 enum ProjectionKind<Path> {
1369 Drop(std::ops::Range<u64>),
1370 Keep(u64, Path),
1371 }
1372 let mut drop_ranges = vec![];
1377 let mut dropping = true;
1378 let mut start = 0;
1379 for i in 0..size {
1380 let path = self.elaborator.array_subpath(self.path, i, size);
1381 if dropping && path.is_some() {
1382 drop_ranges.push(ProjectionKind::Drop(start..i));
1383 dropping = false;
1384 } else if !dropping && path.is_none() {
1385 dropping = true;
1386 start = i;
1387 }
1388 if let Some(path) = path {
1389 drop_ranges.push(ProjectionKind::Keep(i, path));
1390 }
1391 }
1392 if !drop_ranges.is_empty() {
1393 if dropping {
1394 drop_ranges.push(ProjectionKind::Drop(start..size));
1395 }
1396 let fields = drop_ranges
1397 .iter()
1398 .rev()
1399 .map(|p| {
1400 let (project, path) = match p {
1401 ProjectionKind::Drop(r) => (
1402 ProjectionElem::Subslice {
1403 from: r.start,
1404 to: r.end,
1405 from_end: false,
1406 },
1407 None,
1408 ),
1409 &ProjectionKind::Keep(offset, path) => (
1410 ProjectionElem::ConstantIndex {
1411 offset,
1412 min_length: size,
1413 from_end: false,
1414 },
1415 Some(path),
1416 ),
1417 };
1418 (tcx.mk_place_elem(self.place, project), path)
1419 })
1420 .collect::<Vec<_>>();
1421 let (succ, unwind, dropline) = self.drop_ladder_bottom();
1422 return self.drop_ladder(fields, succ, unwind, dropline).0;
1423 }
1424 }
1425
1426 let array_ptr_ty = Ty::new_mut_ptr(tcx, array_ty);
1427 let array_ptr = self.new_temp(array_ptr_ty);
1428
1429 let slice_ty = Ty::new_slice(tcx, ety);
1430 let slice_ptr_ty = Ty::new_mut_ptr(tcx, slice_ty);
1431 let slice_ptr = self.new_temp(slice_ptr_ty);
1432
1433 let array_place = mem::replace(
1434 &mut self.place,
1435 Place::from(slice_ptr).project_deeper(&[PlaceElem::Deref], tcx),
1436 );
1437 let slice_block = self.drop_loop_trio_for_slice(ety);
1438 self.place = array_place;
1439
1440 self.new_block_with_statements(
1441 self.unwind,
1442 vec![
1443 self.assign(Place::from(array_ptr), Rvalue::RawPtr(RawPtrKind::Mut, self.place)),
1444 self.assign(
1445 Place::from(slice_ptr),
1446 Rvalue::Cast(
1447 CastKind::PointerCoercion(
1448 PointerCoercion::Unsize,
1449 CoercionSource::Implicit,
1450 ),
1451 Operand::Move(Place::from(array_ptr)),
1452 slice_ptr_ty,
1453 ),
1454 ),
1455 ],
1456 TerminatorKind::Goto { target: slice_block },
1457 )
1458 }
1459
1460 x;#[instrument(level = "debug", skip(self), ret)]
1463 fn drop_loop_trio_for_slice(&mut self, ety: Ty<'tcx>) -> BasicBlock {
1464 let tcx = self.tcx();
1465 let len = self.new_temp(tcx.types.usize);
1466 let cur = self.new_temp(tcx.types.usize);
1467
1468 let unwind = self
1469 .unwind
1470 .map(|unwind| self.drop_loop(unwind, cur, len, ety, Unwind::InCleanup, None));
1471
1472 let dropline =
1473 self.dropline.map(|dropline| self.drop_loop(dropline, cur, len, ety, unwind, None));
1474
1475 let loop_block = self.drop_loop(self.succ, cur, len, ety, unwind, dropline);
1476
1477 let [PlaceElem::Deref] = self.place.projection.as_slice() else {
1478 span_bug!(
1479 self.source_info.span,
1480 "Expected place for slice drop shim to be *_n, but it's {:?}",
1481 self.place,
1482 );
1483 };
1484
1485 let zero = self.constant_usize(0);
1486 let drop_block = self.new_block_with_statements(
1487 unwind,
1488 vec![
1489 self.assign(
1490 len.into(),
1491 Rvalue::UnaryOp(
1492 UnOp::PtrMetadata,
1493 Operand::Copy(Place::from(self.place.local)),
1494 ),
1495 ),
1496 self.assign(cur.into(), Rvalue::Use(zero, WithRetag::Yes)),
1497 ],
1498 TerminatorKind::Goto { target: loop_block },
1499 );
1500
1501 let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
1503 self.drop_flag_test_block(reset_block, self.succ, unwind)
1504 }
1505
1506 fn open_drop(&mut self) -> BasicBlock {
1515 let ty = self.place_ty(self.place);
1516 match ty.kind() {
1517 ty::Closure(_, args) => self.open_drop_for_tuple(args.as_closure().upvar_tys()),
1518 ty::CoroutineClosure(_, args) => {
1519 self.open_drop_for_tuple(args.as_coroutine_closure().upvar_tys())
1520 }
1521 ty::Coroutine(_, args) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()),
1528 ty::Tuple(fields) => self.open_drop_for_tuple(fields),
1529 ty::Adt(def, args) => self.open_drop_for_adt(*def, args),
1530 ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind),
1531 ty::Array(ety, size) => {
1532 let size = size.try_to_target_usize(self.tcx());
1533 self.open_drop_for_array(ty, *ety, size)
1534 }
1535 ty::Slice(ety) => self.drop_loop_trio_for_slice(*ety),
1536
1537 ty::UnsafeBinder(_) => {
1538 self.tcx().dcx().span_delayed_bug(
1541 self.source_info.span,
1542 "open drop for unsafe binder shouldn't be encountered",
1543 );
1544 self.new_block(self.unwind, TerminatorKind::Unreachable)
1545 }
1546
1547 _ => ::rustc_middle::util::bug::span_bug_fmt(self.source_info.span,
format_args!("open drop from non-ADT `{0:?}`", ty))span_bug!(self.source_info.span, "open drop from non-ADT `{:?}`", ty),
1548 }
1549 }
1550
1551 x;#[instrument(level = "debug", skip(self), ret)]
1552 fn complete_drop(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1553 let drop_block = self.drop_block(succ, unwind);
1554 self.drop_flag_test_block(drop_block, succ, unwind)
1555 }
1556
1557 x;#[instrument(level = "debug", skip(self), ret)]
1560 fn drop_flag_reset_block(
1561 &mut self,
1562 mode: DropFlagMode,
1563 succ: BasicBlock,
1564 unwind: Unwind,
1565 ) -> BasicBlock {
1566 if unwind.is_cleanup() {
1567 return succ;
1570 }
1571 let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
1572 let block_start = Location { block, statement_index: 0 };
1573 self.elaborator.clear_drop_flag(block_start, self.path, mode);
1574 block
1575 }
1576
1577 x;#[instrument(level = "debug", skip(self), ret)]
1578 fn elaborated_drop_block(&mut self) -> BasicBlock {
1579 let blk = self.new_block(
1580 self.unwind,
1581 TerminatorKind::Drop {
1582 place: self.place,
1583 target: self.succ,
1584 unwind: self.unwind.into_action(),
1585 replace: false,
1586 drop: self.dropline,
1587 },
1588 );
1589 self.elaborate_drop(blk);
1590 blk
1591 }
1592
1593 fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1594 let drop_ty = self.place_ty(self.place);
1595 if !unwind.is_cleanup() && self.check_if_can_async_drop(drop_ty, false) {
1596 self.build_async_drop(self.place, drop_ty, self.succ, unwind, self.dropline, false)
1597 } else {
1598 self.new_block(
1599 unwind,
1600 TerminatorKind::Drop {
1601 place: self.place,
1602 target,
1603 unwind: unwind.into_action(),
1604 replace: false,
1605 drop: None,
1606 },
1607 )
1608 }
1609 }
1610
1611 x;#[instrument(level = "debug", skip(self), ret)]
1617 fn drop_flag_test_block(
1618 &mut self,
1619 on_set: BasicBlock,
1620 on_unset: BasicBlock,
1621 unwind: Unwind,
1622 ) -> BasicBlock {
1623 let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
1624 match style {
1625 DropStyle::Dead => on_unset,
1626 DropStyle::Static => on_set,
1627 DropStyle::Conditional | DropStyle::Open => {
1628 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
1629 let term = TerminatorKind::if_(flag, on_set, on_unset);
1630 self.new_block(unwind, term)
1631 }
1632 }
1633 }
1634
1635 x;#[instrument(level = "trace", skip(self), ret)]
1636 fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
1637 self.elaborator.patch().new_block(BasicBlockData::new(
1638 Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1639 unwind.is_cleanup(),
1640 ))
1641 }
1642
1643 x;#[instrument(level = "trace", skip(self, statements), ret)]
1644 fn new_block_with_statements(
1645 &mut self,
1646 unwind: Unwind,
1647 statements: Vec<Statement<'tcx>>,
1648 k: TerminatorKind<'tcx>,
1649 ) -> BasicBlock {
1650 self.elaborator.patch().new_block(BasicBlockData::new_stmts(
1651 statements,
1652 Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1653 unwind.is_cleanup(),
1654 ))
1655 }
1656
1657 fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
1658 self.elaborator.patch().new_temp(ty, self.source_info.span)
1659 }
1660
1661 fn constant_usize(&self, val: u16) -> Operand<'tcx> {
1662 Operand::Constant(Box::new(ConstOperand {
1663 span: self.source_info.span,
1664 user_ty: None,
1665 const_: Const::from_usize(self.tcx(), val.into()),
1666 }))
1667 }
1668
1669 fn assign(&self, lhs: Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
1670 Statement::new(self.source_info, StatementKind::Assign(Box::new((lhs, rhs))))
1671 }
1672
1673 fn storage_live(&self, local: Local) -> Statement<'tcx> {
1674 Statement::new(self.source_info, StatementKind::StorageLive(local))
1675 }
1676
1677 fn storage_dead(&self, local: Local) -> Statement<'tcx> {
1678 Statement::new(self.source_info, StatementKind::StorageDead(local))
1679 }
1680}