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>
95 D: DropElaborator<'b, 'tcx>,
97 elaborator: &'l mut D,
99 source_info: SourceInfo,
101 place: &'l Place<'tcx>,
107 pub fn elaborate_drop<'b, 'tcx, D>(
109 source_info: SourceInfo,
116 D: DropElaborator<'b, 'tcx>,
120 elaborator, source_info, place, path, succ, unwind
124 impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D>
126 D: DropElaborator<'b, 'tcx>,
129 fn place_ty(&self, place: &Place<'tcx>) -> Ty<'tcx> {
130 place.ty(self.elaborator.body(), self.tcx()).ty
133 fn tcx(&self) -> TyCtxt<'tcx> {
134 self.elaborator.tcx()
137 /// This elaborates a single drop instruction, located at `bb`, and
140 /// The elaborated drop checks the drop flags to only drop what
143 /// In addition, the relevant drop flags also need to be cleared
144 /// to avoid double-drops. However, in the middle of a complex
145 /// drop, one must avoid clearing some of the flags before they
146 /// are read, as that would cause a memory leak.
148 /// In particular, when dropping an ADT, multiple fields may be
149 /// joined together under the `rest` subpath. They are all controlled
150 /// by the primary drop flag, but only the last rest-field dropped
151 /// should clear it (and it must also not clear anything else).
153 // FIXME: I think we should just control the flags externally,
154 // and then we do not need this machinery.
155 pub fn elaborate_drop(&mut self, bb: BasicBlock) {
156 debug!("elaborate_drop({:?})", self);
157 let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
158 debug!("elaborate_drop({:?}): live - {:?}", self, style);
161 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
165 DropStyle::Static => {
166 let loc = self.terminator_loc(bb);
167 self.elaborator.clear_drop_flag(loc, self.path, DropFlagMode::Deep);
168 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop {
169 location: self.place.clone(),
171 unwind: self.unwind.into_option(),
174 DropStyle::Conditional => {
175 let unwind = self.unwind; // FIXME(#43234)
176 let succ = self.succ;
177 let drop_bb = self.complete_drop(Some(DropFlagMode::Deep), succ, unwind);
178 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
183 let drop_bb = self.open_drop();
184 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
191 /// Returns the place and move path for each field of `variant`,
192 /// (the move path is `None` if the field is a rest field).
193 fn move_paths_for_fields(&self,
194 base_place: &Place<'tcx>,
195 variant_path: D::Path,
196 variant: &'tcx ty::VariantDef,
197 substs: SubstsRef<'tcx>)
198 -> Vec<(Place<'tcx>, Option<D::Path>)>
200 variant.fields.iter().enumerate().map(|(i, f)| {
201 let field = Field::new(i);
202 let subpath = self.elaborator.field_subpath(variant_path, field);
204 assert_eq!(self.elaborator.param_env().reveal, Reveal::All);
205 let field_ty = self.tcx().normalize_erasing_regions(
206 self.elaborator.param_env(),
207 f.ty(self.tcx(), substs),
209 (base_place.clone().field(field, field_ty), subpath)
213 fn drop_subpath(&mut self,
215 path: Option<D::Path>,
220 if let Some(path) = path {
221 debug!("drop_subpath: for std field {:?}", place);
224 elaborator: self.elaborator,
225 source_info: self.source_info,
226 path, place, succ, unwind,
227 }.elaborated_drop_block()
229 debug!("drop_subpath: for rest field {:?}", place);
232 elaborator: self.elaborator,
233 source_info: self.source_info,
235 // Using `self.path` here to condition the drop on
236 // our own drop flag.
238 }.complete_drop(None, succ, unwind)
242 /// Creates one-half of the drop ladder for a list of fields, and return
243 /// the list of steps in it in reverse order, with the first step
244 /// dropping 0 fields and so on.
246 /// `unwind_ladder` is such a list of steps in reverse order,
247 /// which is called if the matching step of the drop glue panics.
248 fn drop_halfladder(&mut self,
249 unwind_ladder: &[Unwind],
250 mut succ: BasicBlock,
251 fields: &[(Place<'tcx>, Option<D::Path>)])
254 Some(succ).into_iter().chain(
255 fields.iter().rev().zip(unwind_ladder)
256 .map(|(&(ref place, path), &unwind_succ)| {
257 succ = self.drop_subpath(place, path, succ, unwind_succ);
263 fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind) {
264 // Clear the "master" drop flag at the end. This is needed
265 // because the "master" drop protects the ADT's discriminant,
266 // which is invalidated after the ADT is dropped.
267 let (succ, unwind) = (self.succ, self.unwind); // FIXME(#43234)
269 self.drop_flag_reset_block(DropFlagMode::Shallow, succ, unwind),
270 unwind.map(|unwind| {
271 self.drop_flag_reset_block(DropFlagMode::Shallow, unwind, Unwind::InCleanup)
276 /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
278 /// For example, with 3 fields, the drop ladder is
281 /// ELAB(drop location.0 [target=.d1, unwind=.c1])
283 /// ELAB(drop location.1 [target=.d2, unwind=.c2])
285 /// ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
287 /// ELAB(drop location.1 [target=.c2])
289 /// ELAB(drop location.2 [target=`self.unwind`])
291 /// NOTE: this does not clear the master drop flag, so you need
292 /// to point succ/unwind on a `drop_ladder_bottom`.
295 fields: Vec<(Place<'tcx>, Option<D::Path>)>,
298 ) -> (BasicBlock, Unwind) {
299 debug!("drop_ladder({:?}, {:?})", self, fields);
301 let mut fields = fields;
302 fields.retain(|&(ref place, _)| {
303 self.place_ty(place).needs_drop(self.tcx(), self.elaborator.param_env())
306 debug!("drop_ladder - fields needing drop: {:?}", fields);
308 let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
309 let unwind_ladder: Vec<_> = if let Unwind::To(target) = unwind {
310 let halfladder = self.drop_halfladder(&unwind_ladder, target, &fields);
311 halfladder.into_iter().map(Unwind::To).collect()
317 self.drop_halfladder(&unwind_ladder, succ, &fields);
319 (*normal_ladder.last().unwrap(), *unwind_ladder.last().unwrap())
322 fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
323 debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
325 let fields = tys.iter().enumerate().map(|(i, &ty)| {
326 (self.place.clone().field(Field::new(i), ty),
327 self.elaborator.field_subpath(self.path, Field::new(i)))
330 let (succ, unwind) = self.drop_ladder_bottom();
331 self.drop_ladder(fields, succ, unwind).0
334 fn open_drop_for_box(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
335 debug!("open_drop_for_box({:?}, {:?}, {:?})", self, adt, substs);
337 let interior = self.place.clone().deref();
338 let interior_path = self.elaborator.deref_subpath(self.path);
340 let succ = self.succ; // FIXME(#43234)
341 let unwind = self.unwind;
342 let succ = self.box_free_block(adt, substs, succ, unwind);
343 let unwind_succ = self.unwind.map(|unwind| {
344 self.box_free_block(adt, substs, unwind, Unwind::InCleanup)
347 self.drop_subpath(&interior, interior_path, succ, unwind_succ)
350 fn open_drop_for_adt(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
351 debug!("open_drop_for_adt({:?}, {:?}, {:?})", self, adt, substs);
352 if adt.variants.len() == 0 {
353 return self.elaborator.patch().new_block(BasicBlockData {
355 terminator: Some(Terminator {
356 source_info: self.source_info,
357 kind: TerminatorKind::Unreachable
359 is_cleanup: self.unwind.is_cleanup()
364 adt.is_union() || Some(adt.did) == self.tcx().lang_items().manually_drop();
365 let contents_drop = if skip_contents {
366 (self.succ, self.unwind)
368 self.open_drop_for_adt_contents(adt, substs)
371 if adt.has_dtor(self.tcx()) {
372 self.destructor_call_block(contents_drop)
378 fn open_drop_for_adt_contents(&mut self, adt: &'tcx ty::AdtDef,
379 substs: SubstsRef<'tcx>)
380 -> (BasicBlock, Unwind) {
381 let (succ, unwind) = self.drop_ladder_bottom();
383 let fields = self.move_paths_for_fields(
386 &adt.variants[VariantIdx::new(0)],
389 self.drop_ladder(fields, succ, unwind)
391 self.open_drop_for_multivariant(adt, substs, succ, unwind)
395 fn open_drop_for_multivariant(&mut self, adt: &'tcx ty::AdtDef,
396 substs: SubstsRef<'tcx>,
399 -> (BasicBlock, Unwind) {
400 let mut values = Vec::with_capacity(adt.variants.len());
401 let mut normal_blocks = Vec::with_capacity(adt.variants.len());
402 let mut unwind_blocks = if unwind.is_cleanup() {
405 Some(Vec::with_capacity(adt.variants.len()))
408 let mut have_otherwise = false;
410 for (variant_index, discr) in adt.discriminants(self.tcx()) {
411 let subpath = self.elaborator.downcast_subpath(
412 self.path, variant_index);
413 if let Some(variant_path) = subpath {
414 let base_place = self.place.clone().elem(
415 ProjectionElem::Downcast(Some(adt.variants[variant_index].ident.name),
417 let fields = self.move_paths_for_fields(
420 &adt.variants[variant_index],
422 values.push(discr.val);
423 if let Unwind::To(unwind) = unwind {
424 // We can't use the half-ladder from the original
425 // drop ladder, because this breaks the
426 // "funclet can't have 2 successor funclets"
427 // requirement from MSVC:
429 // switch unwind-switch
431 // v1.0 v2.0 v2.0-unwind v1.0-unwind
433 // v1.1-unwind v2.1-unwind |
435 // \-------------------------------/
437 // Create a duplicate half-ladder to avoid that. We
438 // could technically only do this on MSVC, but I
439 // I want to minimize the divergence between MSVC
442 let unwind_blocks = unwind_blocks.as_mut().unwrap();
443 let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
445 self.drop_halfladder(&unwind_ladder, unwind, &fields);
446 unwind_blocks.push(halfladder.last().cloned().unwrap());
448 let (normal, _) = self.drop_ladder(fields, succ, unwind);
449 normal_blocks.push(normal);
451 have_otherwise = true;
456 normal_blocks.push(self.drop_block(succ, unwind));
457 if let Unwind::To(unwind) = unwind {
458 unwind_blocks.as_mut().unwrap().push(
459 self.drop_block(unwind, Unwind::InCleanup)
466 (self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
467 unwind.map(|unwind| {
468 self.adt_switch_block(
469 adt, unwind_blocks.unwrap(), &values, unwind, Unwind::InCleanup
474 fn adt_switch_block(&mut self,
475 adt: &'tcx ty::AdtDef,
476 blocks: Vec<BasicBlock>,
481 // If there are multiple variants, then if something
482 // is present within the enum the discriminant, tracked
483 // by the rest path, must be initialized.
485 // Additionally, we do not want to switch on the
486 // discriminant after it is free-ed, because that
487 // way lies only trouble.
488 let discr_ty = adt.repr.discr_type().to_ty(self.tcx());
489 let discr = Place::from(self.new_temp(discr_ty));
490 let discr_rv = Rvalue::Discriminant(self.place.clone());
491 let switch_block = BasicBlockData {
492 statements: vec![self.assign(&discr, discr_rv)],
493 terminator: Some(Terminator {
494 source_info: self.source_info,
495 kind: TerminatorKind::SwitchInt {
496 discr: Operand::Move(discr),
498 values: From::from(values.to_owned()),
502 is_cleanup: unwind.is_cleanup(),
504 let switch_block = self.elaborator.patch().new_block(switch_block);
505 self.drop_flag_test_block(switch_block, succ, unwind)
508 fn destructor_call_block(&mut self, (succ, unwind): (BasicBlock, Unwind)) -> BasicBlock {
509 debug!("destructor_call_block({:?}, {:?})", self, succ);
510 let tcx = self.tcx();
511 let drop_trait = tcx.lang_items().drop_trait().unwrap();
512 let drop_fn = tcx.associated_items(drop_trait).next().unwrap();
513 let ty = self.place_ty(self.place);
514 let substs = tcx.mk_substs_trait(ty, &[]);
516 let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
518 mutbl: hir::Mutability::MutMutable
520 let ref_place = self.new_temp(ref_ty);
521 let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
523 let result = BasicBlockData {
524 statements: vec![self.assign(
525 &Place::from(ref_place),
526 Rvalue::Ref(tcx.lifetimes.re_erased,
527 BorrowKind::Mut { allow_two_phase_borrow: false },
530 terminator: Some(Terminator {
531 kind: TerminatorKind::Call {
532 func: Operand::function_handle(tcx, drop_fn.def_id, substs,
533 self.source_info.span),
534 args: vec![Operand::Move(Place::from(ref_place))],
535 destination: Some((unit_temp, succ)),
536 cleanup: unwind.into_option(),
539 source_info: self.source_info,
541 is_cleanup: unwind.is_cleanup(),
543 self.elaborator.patch().new_block(result)
546 /// Create a loop that drops an array:
550 /// can_go = cur == length_or_end
551 /// if can_go then succ else drop-block
555 /// cur = cur.offset(1)
557 /// ptr = &mut P[cur]
566 length_or_end: &Place<'tcx>,
571 let copy = |place: &Place<'tcx>| Operand::Copy(place.clone());
572 let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
573 let tcx = self.tcx();
575 let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
577 mutbl: hir::Mutability::MutMutable
579 let ptr = &Place::from(self.new_temp(ref_ty));
580 let can_go = &Place::from(self.new_temp(tcx.types.bool));
582 let one = self.constant_usize(1);
583 let (ptr_next, cur_next) = if ptr_based {
585 tcx.lifetimes.re_erased,
586 BorrowKind::Mut { allow_two_phase_borrow: false },
588 base: PlaceBase::Local(cur),
589 projection: Some(Box::new(Projection {
591 elem: ProjectionElem::Deref,
595 Rvalue::BinaryOp(BinOp::Offset, move_(&Place::from(cur)), one))
598 tcx.lifetimes.re_erased,
599 BorrowKind::Mut { allow_two_phase_borrow: false },
600 self.place.clone().index(cur)),
601 Rvalue::BinaryOp(BinOp::Add, move_(&Place::from(cur)), one))
604 let drop_block = BasicBlockData {
606 self.assign(ptr, ptr_next),
607 self.assign(&Place::from(cur), cur_next)
609 is_cleanup: unwind.is_cleanup(),
610 terminator: Some(Terminator {
611 source_info: self.source_info,
612 // this gets overwritten by drop elaboration.
613 kind: TerminatorKind::Unreachable,
616 let drop_block = self.elaborator.patch().new_block(drop_block);
618 let loop_block = BasicBlockData {
620 self.assign(can_go, Rvalue::BinaryOp(BinOp::Eq,
621 copy(&Place::from(cur)),
622 copy(length_or_end)))
624 is_cleanup: unwind.is_cleanup(),
625 terminator: Some(Terminator {
626 source_info: self.source_info,
627 kind: TerminatorKind::if_(tcx, move_(can_go), succ, drop_block)
630 let loop_block = self.elaborator.patch().new_block(loop_block);
632 self.elaborator.patch().patch_terminator(drop_block, TerminatorKind::Drop {
633 location: ptr.clone().deref(),
635 unwind: unwind.into_option()
641 fn open_drop_for_array(&mut self, ety: Ty<'tcx>, opt_size: Option<u64>) -> BasicBlock {
642 debug!("open_drop_for_array({:?}, {:?})", ety, opt_size);
644 // if size_of::<ety>() == 0 {
650 if let Some(size) = opt_size {
651 let size: u32 = size.try_into().unwrap_or_else(|_| {
652 bug!("move out check isn't implemented for array sizes bigger than u32::MAX");
654 let fields: Vec<(Place<'tcx>, Option<D::Path>)> = (0..size).map(|i| {
655 (self.place.clone().elem(ProjectionElem::ConstantIndex{
660 self.elaborator.array_subpath(self.path, i, size))
663 if fields.iter().any(|(_,path)| path.is_some()) {
664 let (succ, unwind) = self.drop_ladder_bottom();
665 return self.drop_ladder(fields, succ, unwind).0
669 let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
670 let tcx = self.tcx();
671 let elem_size = &Place::from(self.new_temp(tcx.types.usize));
672 let len = &Place::from(self.new_temp(tcx.types.usize));
674 static USIZE_SWITCH_ZERO: &[u128] = &[0];
676 let base_block = BasicBlockData {
678 self.assign(elem_size, Rvalue::NullaryOp(NullOp::SizeOf, ety)),
679 self.assign(len, Rvalue::Len(self.place.clone())),
681 is_cleanup: self.unwind.is_cleanup(),
682 terminator: Some(Terminator {
683 source_info: self.source_info,
684 kind: TerminatorKind::SwitchInt {
685 discr: move_(elem_size),
686 switch_ty: tcx.types.usize,
687 values: From::from(USIZE_SWITCH_ZERO),
689 self.drop_loop_pair(ety, false, len.clone()),
690 self.drop_loop_pair(ety, true, len.clone()),
695 self.elaborator.patch().new_block(base_block)
698 /// Ceates a pair of drop-loops of `place`, which drops its contents, even
699 /// in the case of 1 panic. If `ptr_based`, creates a pointer loop,
700 /// otherwise create an index loop.
707 debug!("drop_loop_pair({:?}, {:?})", ety, ptr_based);
708 let tcx = self.tcx();
709 let iter_ty = if ptr_based {
715 let cur = self.new_temp(iter_ty);
716 let length_or_end = if ptr_based {
717 // FIXME check if we want to make it return a `Place` directly
718 // if all use sites want a `Place::Base` anyway.
719 Place::from(self.new_temp(iter_ty))
724 let unwind = self.unwind.map(|unwind| {
725 self.drop_loop(unwind,
733 let loop_block = self.drop_loop(
741 let cur = Place::from(cur);
742 let drop_block_stmts = if ptr_based {
743 let tmp_ty = tcx.mk_mut_ptr(self.place_ty(self.place));
744 let tmp = Place::from(self.new_temp(tmp_ty));
746 // cur = tmp as *mut T;
747 // end = Offset(cur, len);
749 self.assign(&tmp, Rvalue::Ref(
750 tcx.lifetimes.re_erased,
751 BorrowKind::Mut { allow_two_phase_borrow: false },
756 Rvalue::Cast(CastKind::Misc, Operand::Move(tmp), iter_ty),
760 Rvalue::BinaryOp(BinOp::Offset, Operand::Copy(cur), Operand::Move(length)
764 // cur = 0 (length already pushed)
765 let zero = self.constant_usize(0);
766 vec![self.assign(&cur, Rvalue::Use(zero))]
768 let drop_block = self.elaborator.patch().new_block(BasicBlockData {
769 statements: drop_block_stmts,
770 is_cleanup: unwind.is_cleanup(),
771 terminator: Some(Terminator {
772 source_info: self.source_info,
773 kind: TerminatorKind::Goto { target: loop_block }
777 // FIXME(#34708): handle partially-dropped array/slice elements.
778 let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
779 self.drop_flag_test_block(reset_block, self.succ, unwind)
782 /// The slow-path - create an "open", elaborated drop for a type
783 /// which is moved-out-of only partially, and patch `bb` to a jump
784 /// to it. This must not be called on ADTs with a destructor,
785 /// as these can't be moved-out-of, except for `Box<T>`, which is
788 /// This creates a "drop ladder" that drops the needed fields of the
789 /// ADT, both in the success case or if one of the destructors fail.
790 fn open_drop(&mut self) -> BasicBlock {
791 let ty = self.place_ty(self.place);
793 ty::Closure(def_id, substs) => {
794 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
795 self.open_drop_for_tuple(&tys)
797 // Note that `elaborate_drops` only drops the upvars of a generator,
798 // and this is ok because `open_drop` here can only be reached
799 // within that own generator's resume function.
800 // This should only happen for the self argument on the resume function.
801 // It effetively only contains upvars until the generator transformation runs.
802 // See librustc_body/transform/generator.rs for more details.
803 ty::Generator(def_id, substs, _) => {
804 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
805 self.open_drop_for_tuple(&tys)
808 let tys: Vec<_> = ty.tuple_fields().collect();
809 self.open_drop_for_tuple(&tys)
811 ty::Adt(def, substs) => {
813 self.open_drop_for_box(def, substs)
815 self.open_drop_for_adt(def, substs)
819 let unwind = self.unwind; // FIXME(#43234)
820 let succ = self.succ;
821 self.complete_drop(Some(DropFlagMode::Deep), succ, unwind)
823 ty::Array(ety, size) => {
824 let size = size.try_eval_usize(self.tcx(), self.elaborator.param_env());
825 self.open_drop_for_array(ety, size)
827 ty::Slice(ety) => self.open_drop_for_array(ety, None),
829 _ => bug!("open drop from non-ADT `{:?}`", ty)
833 /// Returns a basic block that drop a place using the context
834 /// and path in `c`. If `mode` is something, also clear `c`
837 /// if FLAG(self.path)
838 /// if let Some(mode) = mode: FLAG(self.path)[mode] = false
842 drop_mode: Option<DropFlagMode>,
846 debug!("complete_drop({:?},{:?})", self, drop_mode);
848 let drop_block = self.drop_block(succ, unwind);
849 let drop_block = if let Some(mode) = drop_mode {
850 self.drop_flag_reset_block(mode, drop_block, unwind)
855 self.drop_flag_test_block(drop_block, succ, unwind)
858 fn drop_flag_reset_block(&mut self,
861 unwind: Unwind) -> BasicBlock
863 debug!("drop_flag_reset_block({:?},{:?})", self, mode);
865 let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
866 let block_start = Location { block: block, statement_index: 0 };
867 self.elaborator.clear_drop_flag(block_start, self.path, mode);
871 fn elaborated_drop_block(&mut self) -> BasicBlock {
872 debug!("elaborated_drop_block({:?})", self);
873 let unwind = self.unwind; // FIXME(#43234)
874 let succ = self.succ;
875 let blk = self.drop_block(succ, unwind);
876 self.elaborate_drop(blk);
882 adt: &'tcx ty::AdtDef,
883 substs: SubstsRef<'tcx>,
887 let block = self.unelaborated_free_block(adt, substs, target, unwind);
888 self.drop_flag_test_block(block, target, unwind)
891 fn unelaborated_free_block(
893 adt: &'tcx ty::AdtDef,
894 substs: SubstsRef<'tcx>,
898 let tcx = self.tcx();
899 let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
900 let free_func = tcx.require_lang_item(
901 lang_items::BoxFreeFnLangItem,
902 Some(self.source_info.span)
904 let args = adt.variants[VariantIdx::new(0)].fields.iter().enumerate().map(|(i, f)| {
905 let field = Field::new(i);
906 let field_ty = f.ty(self.tcx(), substs);
907 Operand::Move(self.place.clone().field(field, field_ty))
910 let call = TerminatorKind::Call {
911 func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
913 destination: Some((unit_temp, target)),
915 from_hir_call: false,
917 let free_block = self.new_block(unwind, call);
919 let block_start = Location { block: free_block, statement_index: 0 };
920 self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
924 fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
925 let block = TerminatorKind::Drop {
926 location: self.place.clone(),
928 unwind: unwind.into_option()
930 self.new_block(unwind, block)
933 fn drop_flag_test_block(&mut self,
935 on_unset: BasicBlock,
939 let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
940 debug!("drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
941 self, on_set, on_unset, unwind, style);
944 DropStyle::Dead => on_unset,
945 DropStyle::Static => on_set,
946 DropStyle::Conditional | DropStyle::Open => {
947 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
948 let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
949 self.new_block(unwind, term)
954 fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
955 self.elaborator.patch().new_block(BasicBlockData {
957 terminator: Some(Terminator {
958 source_info: self.source_info, kind: k
960 is_cleanup: unwind.is_cleanup()
964 fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
965 self.elaborator.patch().new_temp(ty, self.source_info.span)
968 fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
969 let body = self.elaborator.body();
970 self.elaborator.patch().terminator_loc(body, bb)
973 fn constant_usize(&self, val: u16) -> Operand<'tcx> {
974 Operand::Constant(box Constant {
975 span: self.source_info.span,
977 literal: ty::Const::from_usize(self.tcx(), val.into()),
981 fn assign(&self, lhs: &Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
983 source_info: self.source_info,
984 kind: StatementKind::Assign(lhs.clone(), box rhs)