4 use rustc::middle::lang_items;
5 use rustc::traits::Reveal;
6 use rustc::ty::{self, Ty, TyCtxt};
7 use rustc::ty::layout::VariantIdx;
8 use rustc::ty::subst::SubstsRef;
9 use rustc::ty::util::IntTypeExt;
10 use rustc_data_structures::indexed_vec::Idx;
11 use crate::util::patch::MirPatch;
13 use std::convert::TryInto;
15 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
16 pub enum DropFlagState {
17 Present, // i.e., initialized
18 Absent, // i.e., deinitialized or "moved"
22 pub fn value(self) -> bool {
24 DropFlagState::Present => true,
25 DropFlagState::Absent => false
39 pub enum DropFlagMode {
44 #[derive(Copy, Clone, Debug)]
51 fn is_cleanup(self) -> bool {
53 Unwind::To(..) => false,
54 Unwind::InCleanup => true
58 fn into_option(self) -> Option<BasicBlock> {
60 Unwind::To(bb) => Some(bb),
61 Unwind::InCleanup => None,
65 fn map<F>(self, f: F) -> Self where F: FnOnce(BasicBlock) -> BasicBlock {
67 Unwind::To(bb) => Unwind::To(f(bb)),
68 Unwind::InCleanup => Unwind::InCleanup
73 pub trait DropElaborator<'a, 'tcx>: fmt::Debug {
74 type Path : Copy + fmt::Debug;
76 fn patch(&mut self) -> &mut MirPatch<'tcx>;
77 fn body(&self) -> &'a Body<'tcx>;
78 fn tcx(&self) -> TyCtxt<'tcx>;
79 fn param_env(&self) -> ty::ParamEnv<'tcx>;
81 fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
82 fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
83 fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
86 fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path>;
87 fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
88 fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
89 fn array_subpath(&self, path: Self::Path, index: u32, size: u32) -> Option<Self::Path>;
93 struct DropCtxt<'l, 'b, 'tcx, D>
94 where D : DropElaborator<'b, 'tcx> + 'l
96 elaborator: &'l mut D,
98 source_info: SourceInfo,
100 place: &'l Place<'tcx>,
106 pub fn elaborate_drop<'b, 'tcx, D>(
108 source_info: SourceInfo,
114 where D: DropElaborator<'b, 'tcx>,
118 elaborator, source_info, place, path, succ, unwind
122 impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D>
124 D: DropElaborator<'b, 'tcx>,
127 fn place_ty(&self, place: &Place<'tcx>) -> Ty<'tcx> {
128 place.ty(self.elaborator.body(), self.tcx()).ty
131 fn tcx(&self) -> TyCtxt<'tcx> {
132 self.elaborator.tcx()
135 /// This elaborates a single drop instruction, located at `bb`, and
138 /// The elaborated drop checks the drop flags to only drop what
141 /// In addition, the relevant drop flags also need to be cleared
142 /// to avoid double-drops. However, in the middle of a complex
143 /// drop, one must avoid clearing some of the flags before they
144 /// are read, as that would cause a memory leak.
146 /// In particular, when dropping an ADT, multiple fields may be
147 /// joined together under the `rest` subpath. They are all controlled
148 /// by the primary drop flag, but only the last rest-field dropped
149 /// should clear it (and it must also not clear anything else).
151 // FIXME: I think we should just control the flags externally,
152 // and then we do not need this machinery.
153 pub fn elaborate_drop(&mut self, bb: BasicBlock) {
154 debug!("elaborate_drop({:?})", self);
155 let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
156 debug!("elaborate_drop({:?}): live - {:?}", self, style);
159 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
163 DropStyle::Static => {
164 let loc = self.terminator_loc(bb);
165 self.elaborator.clear_drop_flag(loc, self.path, DropFlagMode::Deep);
166 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop {
167 location: self.place.clone(),
169 unwind: self.unwind.into_option(),
172 DropStyle::Conditional => {
173 let unwind = self.unwind; // FIXME(#43234)
174 let succ = self.succ;
175 let drop_bb = self.complete_drop(Some(DropFlagMode::Deep), succ, unwind);
176 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
181 let drop_bb = self.open_drop();
182 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
189 /// Returns the place and move path for each field of `variant`,
190 /// (the move path is `None` if the field is a rest field).
191 fn move_paths_for_fields(&self,
192 base_place: &Place<'tcx>,
193 variant_path: D::Path,
194 variant: &'tcx ty::VariantDef,
195 substs: SubstsRef<'tcx>)
196 -> Vec<(Place<'tcx>, Option<D::Path>)>
198 variant.fields.iter().enumerate().map(|(i, f)| {
199 let field = Field::new(i);
200 let subpath = self.elaborator.field_subpath(variant_path, field);
202 assert_eq!(self.elaborator.param_env().reveal, Reveal::All);
203 let field_ty = self.tcx().normalize_erasing_regions(
204 self.elaborator.param_env(),
205 f.ty(self.tcx(), substs),
207 (base_place.clone().field(field, field_ty), subpath)
211 fn drop_subpath(&mut self,
213 path: Option<D::Path>,
218 if let Some(path) = path {
219 debug!("drop_subpath: for std field {:?}", place);
222 elaborator: self.elaborator,
223 source_info: self.source_info,
224 path, place, succ, unwind,
225 }.elaborated_drop_block()
227 debug!("drop_subpath: for rest field {:?}", place);
230 elaborator: self.elaborator,
231 source_info: self.source_info,
233 // Using `self.path` here to condition the drop on
234 // our own drop flag.
236 }.complete_drop(None, succ, unwind)
240 /// Creates one-half of the drop ladder for a list of fields, and return
241 /// the list of steps in it in reverse order, with the first step
242 /// dropping 0 fields and so on.
244 /// `unwind_ladder` is such a list of steps in reverse order,
245 /// which is called if the matching step of the drop glue panics.
246 fn drop_halfladder(&mut self,
247 unwind_ladder: &[Unwind],
248 mut succ: BasicBlock,
249 fields: &[(Place<'tcx>, Option<D::Path>)])
252 Some(succ).into_iter().chain(
253 fields.iter().rev().zip(unwind_ladder)
254 .map(|(&(ref place, path), &unwind_succ)| {
255 succ = self.drop_subpath(place, path, succ, unwind_succ);
261 fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind) {
262 // Clear the "master" drop flag at the end. This is needed
263 // because the "master" drop protects the ADT's discriminant,
264 // which is invalidated after the ADT is dropped.
265 let (succ, unwind) = (self.succ, self.unwind); // FIXME(#43234)
267 self.drop_flag_reset_block(DropFlagMode::Shallow, succ, unwind),
268 unwind.map(|unwind| {
269 self.drop_flag_reset_block(DropFlagMode::Shallow, unwind, Unwind::InCleanup)
274 /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
276 /// For example, with 3 fields, the drop ladder is
279 /// ELAB(drop location.0 [target=.d1, unwind=.c1])
281 /// ELAB(drop location.1 [target=.d2, unwind=.c2])
283 /// ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
285 /// ELAB(drop location.1 [target=.c2])
287 /// ELAB(drop location.2 [target=`self.unwind`])
289 /// NOTE: this does not clear the master drop flag, so you need
290 /// to point succ/unwind on a `drop_ladder_bottom`.
293 fields: Vec<(Place<'tcx>, Option<D::Path>)>,
296 ) -> (BasicBlock, Unwind) {
297 debug!("drop_ladder({:?}, {:?})", self, fields);
299 let mut fields = fields;
300 fields.retain(|&(ref place, _)| {
301 self.place_ty(place).needs_drop(self.tcx(), self.elaborator.param_env())
304 debug!("drop_ladder - fields needing drop: {:?}", fields);
306 let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
307 let unwind_ladder: Vec<_> = if let Unwind::To(target) = unwind {
308 let halfladder = self.drop_halfladder(&unwind_ladder, target, &fields);
309 halfladder.into_iter().map(Unwind::To).collect()
315 self.drop_halfladder(&unwind_ladder, succ, &fields);
317 (*normal_ladder.last().unwrap(), *unwind_ladder.last().unwrap())
320 fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
321 debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
323 let fields = tys.iter().enumerate().map(|(i, &ty)| {
324 (self.place.clone().field(Field::new(i), ty),
325 self.elaborator.field_subpath(self.path, Field::new(i)))
328 let (succ, unwind) = self.drop_ladder_bottom();
329 self.drop_ladder(fields, succ, unwind).0
332 fn open_drop_for_box(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
333 debug!("open_drop_for_box({:?}, {:?}, {:?})", self, adt, substs);
335 let interior = self.place.clone().deref();
336 let interior_path = self.elaborator.deref_subpath(self.path);
338 let succ = self.succ; // FIXME(#43234)
339 let unwind = self.unwind;
340 let succ = self.box_free_block(adt, substs, succ, unwind);
341 let unwind_succ = self.unwind.map(|unwind| {
342 self.box_free_block(adt, substs, unwind, Unwind::InCleanup)
345 self.drop_subpath(&interior, interior_path, succ, unwind_succ)
348 fn open_drop_for_adt(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
349 debug!("open_drop_for_adt({:?}, {:?}, {:?})", self, adt, substs);
350 if adt.variants.len() == 0 {
351 return self.elaborator.patch().new_block(BasicBlockData {
353 terminator: Some(Terminator {
354 source_info: self.source_info,
355 kind: TerminatorKind::Unreachable
357 is_cleanup: self.unwind.is_cleanup()
362 adt.is_union() || Some(adt.did) == self.tcx().lang_items().manually_drop();
363 let contents_drop = if skip_contents {
364 (self.succ, self.unwind)
366 self.open_drop_for_adt_contents(adt, substs)
369 if adt.has_dtor(self.tcx()) {
370 self.destructor_call_block(contents_drop)
376 fn open_drop_for_adt_contents(&mut self, adt: &'tcx ty::AdtDef,
377 substs: SubstsRef<'tcx>)
378 -> (BasicBlock, Unwind) {
379 let (succ, unwind) = self.drop_ladder_bottom();
381 let fields = self.move_paths_for_fields(
384 &adt.variants[VariantIdx::new(0)],
387 self.drop_ladder(fields, succ, unwind)
389 self.open_drop_for_multivariant(adt, substs, succ, unwind)
393 fn open_drop_for_multivariant(&mut self, adt: &'tcx ty::AdtDef,
394 substs: SubstsRef<'tcx>,
397 -> (BasicBlock, Unwind) {
398 let mut values = Vec::with_capacity(adt.variants.len());
399 let mut normal_blocks = Vec::with_capacity(adt.variants.len());
400 let mut unwind_blocks = if unwind.is_cleanup() {
403 Some(Vec::with_capacity(adt.variants.len()))
406 let mut have_otherwise = false;
408 for (variant_index, discr) in adt.discriminants(self.tcx()) {
409 let subpath = self.elaborator.downcast_subpath(
410 self.path, variant_index);
411 if let Some(variant_path) = subpath {
412 let base_place = self.place.clone().elem(
413 ProjectionElem::Downcast(Some(adt.variants[variant_index].ident.name),
415 let fields = self.move_paths_for_fields(
418 &adt.variants[variant_index],
420 values.push(discr.val);
421 if let Unwind::To(unwind) = unwind {
422 // We can't use the half-ladder from the original
423 // drop ladder, because this breaks the
424 // "funclet can't have 2 successor funclets"
425 // requirement from MSVC:
427 // switch unwind-switch
429 // v1.0 v2.0 v2.0-unwind v1.0-unwind
431 // v1.1-unwind v2.1-unwind |
433 // \-------------------------------/
435 // Create a duplicate half-ladder to avoid that. We
436 // could technically only do this on MSVC, but I
437 // I want to minimize the divergence between MSVC
440 let unwind_blocks = unwind_blocks.as_mut().unwrap();
441 let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
443 self.drop_halfladder(&unwind_ladder, unwind, &fields);
444 unwind_blocks.push(halfladder.last().cloned().unwrap());
446 let (normal, _) = self.drop_ladder(fields, succ, unwind);
447 normal_blocks.push(normal);
449 have_otherwise = true;
454 normal_blocks.push(self.drop_block(succ, unwind));
455 if let Unwind::To(unwind) = unwind {
456 unwind_blocks.as_mut().unwrap().push(
457 self.drop_block(unwind, Unwind::InCleanup)
464 (self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
465 unwind.map(|unwind| {
466 self.adt_switch_block(
467 adt, unwind_blocks.unwrap(), &values, unwind, Unwind::InCleanup
472 fn adt_switch_block(&mut self,
473 adt: &'tcx ty::AdtDef,
474 blocks: Vec<BasicBlock>,
479 // If there are multiple variants, then if something
480 // is present within the enum the discriminant, tracked
481 // by the rest path, must be initialized.
483 // Additionally, we do not want to switch on the
484 // discriminant after it is free-ed, because that
485 // way lies only trouble.
486 let discr_ty = adt.repr.discr_type().to_ty(self.tcx());
487 let discr = Place::Base(PlaceBase::Local(self.new_temp(discr_ty)));
488 let discr_rv = Rvalue::Discriminant(self.place.clone());
489 let switch_block = BasicBlockData {
490 statements: vec![self.assign(&discr, discr_rv)],
491 terminator: Some(Terminator {
492 source_info: self.source_info,
493 kind: TerminatorKind::SwitchInt {
494 discr: Operand::Move(discr),
496 values: From::from(values.to_owned()),
500 is_cleanup: unwind.is_cleanup(),
502 let switch_block = self.elaborator.patch().new_block(switch_block);
503 self.drop_flag_test_block(switch_block, succ, unwind)
506 fn destructor_call_block(&mut self, (succ, unwind): (BasicBlock, Unwind)) -> BasicBlock {
507 debug!("destructor_call_block({:?}, {:?})", self, succ);
508 let tcx = self.tcx();
509 let drop_trait = tcx.lang_items().drop_trait().unwrap();
510 let drop_fn = tcx.associated_items(drop_trait).next().unwrap();
511 let ty = self.place_ty(self.place);
512 let substs = tcx.mk_substs_trait(ty, &[]);
514 let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
516 mutbl: hir::Mutability::MutMutable
518 let ref_place = self.new_temp(ref_ty);
519 let unit_temp = Place::Base(PlaceBase::Local(self.new_temp(tcx.mk_unit())));
521 let result = BasicBlockData {
522 statements: vec![self.assign(
523 &Place::Base(PlaceBase::Local(ref_place)),
524 Rvalue::Ref(tcx.lifetimes.re_erased,
525 BorrowKind::Mut { allow_two_phase_borrow: false },
528 terminator: Some(Terminator {
529 kind: TerminatorKind::Call {
530 func: Operand::function_handle(tcx, drop_fn.def_id, substs,
531 self.source_info.span),
532 args: vec![Operand::Move(Place::Base(PlaceBase::Local(ref_place)))],
533 destination: Some((unit_temp, succ)),
534 cleanup: unwind.into_option(),
537 source_info: self.source_info,
539 is_cleanup: unwind.is_cleanup(),
541 self.elaborator.patch().new_block(result)
544 /// Create a loop that drops an array:
548 /// can_go = cur == length_or_end
549 /// if can_go then succ else drop-block
553 /// cur = cur.offset(1)
555 /// ptr = &mut P[cur]
564 length_or_end: &Place<'tcx>,
569 let copy = |place: &Place<'tcx>| Operand::Copy(place.clone());
570 let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
571 let tcx = self.tcx();
573 let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
575 mutbl: hir::Mutability::MutMutable
577 let ptr = &Place::Base(PlaceBase::Local(self.new_temp(ref_ty)));
578 let can_go = &Place::Base(PlaceBase::Local(self.new_temp(tcx.types.bool)));
580 let one = self.constant_usize(1);
581 let (ptr_next, cur_next) = if ptr_based {
583 tcx.lifetimes.re_erased,
584 BorrowKind::Mut { allow_two_phase_borrow: false },
585 Place::Projection(Box::new(Projection {
586 base: Place::Base(PlaceBase::Local(cur)),
587 elem: ProjectionElem::Deref,
590 Rvalue::BinaryOp(BinOp::Offset, move_(&Place::Base(PlaceBase::Local(cur))), one))
593 tcx.lifetimes.re_erased,
594 BorrowKind::Mut { allow_two_phase_borrow: false },
595 self.place.clone().index(cur)),
596 Rvalue::BinaryOp(BinOp::Add, move_(&Place::Base(PlaceBase::Local(cur))), one))
599 let drop_block = BasicBlockData {
601 self.assign(ptr, ptr_next),
602 self.assign(&Place::Base(PlaceBase::Local(cur)), cur_next)
604 is_cleanup: unwind.is_cleanup(),
605 terminator: Some(Terminator {
606 source_info: self.source_info,
607 // this gets overwritten by drop elaboration.
608 kind: TerminatorKind::Unreachable,
611 let drop_block = self.elaborator.patch().new_block(drop_block);
613 let loop_block = BasicBlockData {
615 self.assign(can_go, Rvalue::BinaryOp(BinOp::Eq,
616 copy(&Place::Base(PlaceBase::Local(cur))),
617 copy(length_or_end)))
619 is_cleanup: unwind.is_cleanup(),
620 terminator: Some(Terminator {
621 source_info: self.source_info,
622 kind: TerminatorKind::if_(tcx, move_(can_go), succ, drop_block)
625 let loop_block = self.elaborator.patch().new_block(loop_block);
627 self.elaborator.patch().patch_terminator(drop_block, TerminatorKind::Drop {
628 location: ptr.clone().deref(),
630 unwind: unwind.into_option()
636 fn open_drop_for_array(&mut self, ety: Ty<'tcx>, opt_size: Option<u64>) -> BasicBlock {
637 debug!("open_drop_for_array({:?}, {:?})", ety, opt_size);
639 // if size_of::<ety>() == 0 {
645 if let Some(size) = opt_size {
646 let size: u32 = size.try_into().unwrap_or_else(|_| {
647 bug!("move out check isn't implemented for array sizes bigger than u32::MAX");
649 let fields: Vec<(Place<'tcx>, Option<D::Path>)> = (0..size).map(|i| {
650 (self.place.clone().elem(ProjectionElem::ConstantIndex{
655 self.elaborator.array_subpath(self.path, i, size))
658 if fields.iter().any(|(_,path)| path.is_some()) {
659 let (succ, unwind) = self.drop_ladder_bottom();
660 return self.drop_ladder(fields, succ, unwind).0
664 let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
665 let tcx = self.tcx();
666 let elem_size = &Place::Base(PlaceBase::Local(self.new_temp(tcx.types.usize)));
667 let len = &Place::Base(PlaceBase::Local(self.new_temp(tcx.types.usize)));
669 static USIZE_SWITCH_ZERO: &[u128] = &[0];
671 let base_block = BasicBlockData {
673 self.assign(elem_size, Rvalue::NullaryOp(NullOp::SizeOf, ety)),
674 self.assign(len, Rvalue::Len(self.place.clone())),
676 is_cleanup: self.unwind.is_cleanup(),
677 terminator: Some(Terminator {
678 source_info: self.source_info,
679 kind: TerminatorKind::SwitchInt {
680 discr: move_(elem_size),
681 switch_ty: tcx.types.usize,
682 values: From::from(USIZE_SWITCH_ZERO),
684 self.drop_loop_pair(ety, false, len.clone()),
685 self.drop_loop_pair(ety, true, len.clone()),
690 self.elaborator.patch().new_block(base_block)
693 /// Ceates a pair of drop-loops of `place`, which drops its contents, even
694 /// in the case of 1 panic. If `ptr_based`, creates a pointer loop,
695 /// otherwise create an index loop.
702 debug!("drop_loop_pair({:?}, {:?})", ety, ptr_based);
703 let tcx = self.tcx();
704 let iter_ty = if ptr_based {
710 let cur = self.new_temp(iter_ty);
711 let length_or_end = if ptr_based {
712 // FIXME check if we want to make it return a `Place` directly
713 // if all use sites want a `Place::Base` anyway.
714 let temp = self.new_temp(iter_ty);
715 Place::Base(PlaceBase::Local(temp))
720 let unwind = self.unwind.map(|unwind| {
721 self.drop_loop(unwind,
729 let loop_block = self.drop_loop(
737 let cur = Place::Base(PlaceBase::Local(cur));
738 let drop_block_stmts = if ptr_based {
739 let tmp_ty = tcx.mk_mut_ptr(self.place_ty(self.place));
740 let tmp = Place::Base(PlaceBase::Local(self.new_temp(tmp_ty)));
742 // cur = tmp as *mut T;
743 // end = Offset(cur, len);
745 self.assign(&tmp, Rvalue::Ref(
746 tcx.lifetimes.re_erased,
747 BorrowKind::Mut { allow_two_phase_borrow: false },
752 Rvalue::Cast(CastKind::Misc, Operand::Move(tmp), iter_ty),
756 Rvalue::BinaryOp(BinOp::Offset, Operand::Copy(cur), Operand::Move(length)
760 // cur = 0 (length already pushed)
761 let zero = self.constant_usize(0);
762 vec![self.assign(&cur, Rvalue::Use(zero))]
764 let drop_block = self.elaborator.patch().new_block(BasicBlockData {
765 statements: drop_block_stmts,
766 is_cleanup: unwind.is_cleanup(),
767 terminator: Some(Terminator {
768 source_info: self.source_info,
769 kind: TerminatorKind::Goto { target: loop_block }
773 // FIXME(#34708): handle partially-dropped array/slice elements.
774 let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
775 self.drop_flag_test_block(reset_block, self.succ, unwind)
778 /// The slow-path - create an "open", elaborated drop for a type
779 /// which is moved-out-of only partially, and patch `bb` to a jump
780 /// to it. This must not be called on ADTs with a destructor,
781 /// as these can't be moved-out-of, except for `Box<T>`, which is
784 /// This creates a "drop ladder" that drops the needed fields of the
785 /// ADT, both in the success case or if one of the destructors fail.
786 fn open_drop(&mut self) -> BasicBlock {
787 let ty = self.place_ty(self.place);
789 ty::Closure(def_id, substs) => {
790 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
791 self.open_drop_for_tuple(&tys)
793 // Note that `elaborate_drops` only drops the upvars of a generator,
794 // and this is ok because `open_drop` here can only be reached
795 // within that own generator's resume function.
796 // This should only happen for the self argument on the resume function.
797 // It effetively only contains upvars until the generator transformation runs.
798 // See librustc_body/transform/generator.rs for more details.
799 ty::Generator(def_id, substs, _) => {
800 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
801 self.open_drop_for_tuple(&tys)
804 let tys: Vec<_> = tys.iter().map(|k| k.expect_ty()).collect();
805 self.open_drop_for_tuple(&tys)
807 ty::Adt(def, substs) => {
809 self.open_drop_for_box(def, substs)
811 self.open_drop_for_adt(def, substs)
815 let unwind = self.unwind; // FIXME(#43234)
816 let succ = self.succ;
817 self.complete_drop(Some(DropFlagMode::Deep), succ, unwind)
819 ty::Array(ety, size) => {
820 let size = size.assert_usize(self.tcx());
821 self.open_drop_for_array(ety, size)
823 ty::Slice(ety) => self.open_drop_for_array(ety, None),
825 _ => bug!("open drop from non-ADT `{:?}`", ty)
829 /// Returns a basic block that drop a place using the context
830 /// and path in `c`. If `mode` is something, also clear `c`
833 /// if FLAG(self.path)
834 /// if let Some(mode) = mode: FLAG(self.path)[mode] = false
838 drop_mode: Option<DropFlagMode>,
842 debug!("complete_drop({:?},{:?})", self, drop_mode);
844 let drop_block = self.drop_block(succ, unwind);
845 let drop_block = if let Some(mode) = drop_mode {
846 self.drop_flag_reset_block(mode, drop_block, unwind)
851 self.drop_flag_test_block(drop_block, succ, unwind)
854 fn drop_flag_reset_block(&mut self,
857 unwind: Unwind) -> BasicBlock
859 debug!("drop_flag_reset_block({:?},{:?})", self, mode);
861 let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
862 let block_start = Location { block: block, statement_index: 0 };
863 self.elaborator.clear_drop_flag(block_start, self.path, mode);
867 fn elaborated_drop_block(&mut self) -> BasicBlock {
868 debug!("elaborated_drop_block({:?})", self);
869 let unwind = self.unwind; // FIXME(#43234)
870 let succ = self.succ;
871 let blk = self.drop_block(succ, unwind);
872 self.elaborate_drop(blk);
878 adt: &'tcx ty::AdtDef,
879 substs: SubstsRef<'tcx>,
883 let block = self.unelaborated_free_block(adt, substs, target, unwind);
884 self.drop_flag_test_block(block, target, unwind)
887 fn unelaborated_free_block(
889 adt: &'tcx ty::AdtDef,
890 substs: SubstsRef<'tcx>,
894 let tcx = self.tcx();
895 let unit_temp = Place::Base(PlaceBase::Local(self.new_temp(tcx.mk_unit())));
896 let free_func = tcx.require_lang_item(lang_items::BoxFreeFnLangItem);
897 let args = adt.variants[VariantIdx::new(0)].fields.iter().enumerate().map(|(i, f)| {
898 let field = Field::new(i);
899 let field_ty = f.ty(self.tcx(), substs);
900 Operand::Move(self.place.clone().field(field, field_ty))
903 let call = TerminatorKind::Call {
904 func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
906 destination: Some((unit_temp, target)),
908 from_hir_call: false,
910 let free_block = self.new_block(unwind, call);
912 let block_start = Location { block: free_block, statement_index: 0 };
913 self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
917 fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
918 let block = TerminatorKind::Drop {
919 location: self.place.clone(),
921 unwind: unwind.into_option()
923 self.new_block(unwind, block)
926 fn drop_flag_test_block(&mut self,
928 on_unset: BasicBlock,
932 let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
933 debug!("drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
934 self, on_set, on_unset, unwind, style);
937 DropStyle::Dead => on_unset,
938 DropStyle::Static => on_set,
939 DropStyle::Conditional | DropStyle::Open => {
940 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
941 let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
942 self.new_block(unwind, term)
947 fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
948 self.elaborator.patch().new_block(BasicBlockData {
950 terminator: Some(Terminator {
951 source_info: self.source_info, kind: k
953 is_cleanup: unwind.is_cleanup()
957 fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
958 self.elaborator.patch().new_temp(ty, self.source_info.span)
961 fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
962 let body = self.elaborator.body();
963 self.elaborator.patch().terminator_loc(body, bb)
966 fn constant_usize(&self, val: u16) -> Operand<'tcx> {
967 Operand::Constant(box Constant {
968 span: self.source_info.span,
969 ty: self.tcx().types.usize,
971 literal: ty::Const::from_usize(self.tcx(), val.into()),
975 fn assign(&self, lhs: &Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
977 source_info: self.source_info,
978 kind: StatementKind::Assign(lhs.clone(), box rhs)