]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/elaborate_drops.rs
direct imports for langitem stuff
[rust.git] / src / librustc_mir / util / elaborate_drops.rs
1 use crate::util::patch::MirPatch;
2 use rustc_hir as hir;
3 use rustc_hir::lang_items;
4 use rustc_index::vec::Idx;
5 use rustc_middle::mir::*;
6 use rustc_middle::traits::Reveal;
7 use rustc_middle::ty::subst::SubstsRef;
8 use rustc_middle::ty::util::IntTypeExt;
9 use rustc_middle::ty::{self, Ty, TyCtxt};
10 use rustc_target::abi::VariantIdx;
11 use std::fmt;
12
13 use std::convert::TryInto;
14
15 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
16 pub enum DropFlagState {
17     Present, // i.e., initialized
18     Absent,  // i.e., deinitialized or "moved"
19 }
20
21 impl DropFlagState {
22     pub fn value(self) -> bool {
23         match self {
24             DropFlagState::Present => true,
25             DropFlagState::Absent => false,
26         }
27     }
28 }
29
30 #[derive(Debug)]
31 pub enum DropStyle {
32     Dead,
33     Static,
34     Conditional,
35     Open,
36 }
37
38 #[derive(Debug)]
39 pub enum DropFlagMode {
40     Shallow,
41     Deep,
42 }
43
44 #[derive(Copy, Clone, Debug)]
45 pub enum Unwind {
46     To(BasicBlock),
47     InCleanup,
48 }
49
50 impl Unwind {
51     fn is_cleanup(self) -> bool {
52         match self {
53             Unwind::To(..) => false,
54             Unwind::InCleanup => true,
55         }
56     }
57
58     fn into_option(self) -> Option<BasicBlock> {
59         match self {
60             Unwind::To(bb) => Some(bb),
61             Unwind::InCleanup => None,
62         }
63     }
64
65     fn map<F>(self, f: F) -> Self
66     where
67         F: FnOnce(BasicBlock) -> BasicBlock,
68     {
69         match self {
70             Unwind::To(bb) => Unwind::To(f(bb)),
71             Unwind::InCleanup => Unwind::InCleanup,
72         }
73     }
74 }
75
76 pub trait DropElaborator<'a, 'tcx>: fmt::Debug {
77     type Path: Copy + fmt::Debug;
78
79     fn patch(&mut self) -> &mut MirPatch<'tcx>;
80     fn body(&self) -> &'a Body<'tcx>;
81     fn tcx(&self) -> TyCtxt<'tcx>;
82     fn param_env(&self) -> ty::ParamEnv<'tcx>;
83
84     fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
85     fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
86     fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
87
88     fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path>;
89     fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
90     fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
91     fn array_subpath(&self, path: Self::Path, index: u32, size: u32) -> Option<Self::Path>;
92 }
93
94 #[derive(Debug)]
95 struct DropCtxt<'l, 'b, 'tcx, D>
96 where
97     D: DropElaborator<'b, 'tcx>,
98 {
99     elaborator: &'l mut D,
100
101     source_info: SourceInfo,
102
103     place: Place<'tcx>,
104     path: D::Path,
105     succ: BasicBlock,
106     unwind: Unwind,
107 }
108
109 pub fn elaborate_drop<'b, 'tcx, D>(
110     elaborator: &mut D,
111     source_info: SourceInfo,
112     place: Place<'tcx>,
113     path: D::Path,
114     succ: BasicBlock,
115     unwind: Unwind,
116     bb: BasicBlock,
117 ) where
118     D: DropElaborator<'b, 'tcx>,
119     'tcx: 'b,
120 {
121     DropCtxt { elaborator, source_info, place, path, succ, unwind }.elaborate_drop(bb)
122 }
123
124 impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D>
125 where
126     D: DropElaborator<'b, 'tcx>,
127     'tcx: 'b,
128 {
129     fn place_ty(&self, place: Place<'tcx>) -> Ty<'tcx> {
130         place.ty(self.elaborator.body(), self.tcx()).ty
131     }
132
133     fn tcx(&self) -> TyCtxt<'tcx> {
134         self.elaborator.tcx()
135     }
136
137     /// This elaborates a single drop instruction, located at `bb`, and
138     /// patches over it.
139     ///
140     /// The elaborated drop checks the drop flags to only drop what
141     /// is initialized.
142     ///
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.
147     ///
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).
152     //
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({:?}, {:?})", bb, self);
157         let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
158         debug!("elaborate_drop({:?}, {:?}): live - {:?}", bb, self, style);
159         match style {
160             DropStyle::Dead => {
161                 self.elaborator
162                     .patch()
163                     .patch_terminator(bb, TerminatorKind::Goto { target: self.succ });
164             }
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(
169                     bb,
170                     TerminatorKind::Drop {
171                         location: self.place,
172                         target: self.succ,
173                         unwind: self.unwind.into_option(),
174                     },
175                 );
176             }
177             DropStyle::Conditional => {
178                 let unwind = self.unwind; // FIXME(#43234)
179                 let succ = self.succ;
180                 let drop_bb = self.complete_drop(Some(DropFlagMode::Deep), succ, unwind);
181                 self.elaborator
182                     .patch()
183                     .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
184             }
185             DropStyle::Open => {
186                 let drop_bb = self.open_drop();
187                 self.elaborator
188                     .patch()
189                     .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
190             }
191         }
192     }
193
194     /// Returns the place and move path for each field of `variant`,
195     /// (the move path is `None` if the field is a rest field).
196     fn move_paths_for_fields(
197         &self,
198         base_place: Place<'tcx>,
199         variant_path: D::Path,
200         variant: &'tcx ty::VariantDef,
201         substs: SubstsRef<'tcx>,
202     ) -> Vec<(Place<'tcx>, Option<D::Path>)> {
203         variant
204             .fields
205             .iter()
206             .enumerate()
207             .map(|(i, f)| {
208                 let field = Field::new(i);
209                 let subpath = self.elaborator.field_subpath(variant_path, field);
210                 let tcx = self.tcx();
211
212                 assert_eq!(self.elaborator.param_env().reveal, Reveal::All);
213                 let field_ty =
214                     tcx.normalize_erasing_regions(self.elaborator.param_env(), f.ty(tcx, substs));
215                 (tcx.mk_place_field(base_place.clone(), field, field_ty), subpath)
216             })
217             .collect()
218     }
219
220     fn drop_subpath(
221         &mut self,
222         place: Place<'tcx>,
223         path: Option<D::Path>,
224         succ: BasicBlock,
225         unwind: Unwind,
226     ) -> BasicBlock {
227         if let Some(path) = path {
228             debug!("drop_subpath: for std field {:?}", place);
229
230             DropCtxt {
231                 elaborator: self.elaborator,
232                 source_info: self.source_info,
233                 path,
234                 place,
235                 succ,
236                 unwind,
237             }
238             .elaborated_drop_block()
239         } else {
240             debug!("drop_subpath: for rest field {:?}", place);
241
242             DropCtxt {
243                 elaborator: self.elaborator,
244                 source_info: self.source_info,
245                 place,
246                 succ,
247                 unwind,
248                 // Using `self.path` here to condition the drop on
249                 // our own drop flag.
250                 path: self.path,
251             }
252             .complete_drop(None, succ, unwind)
253         }
254     }
255
256     /// Creates one-half of the drop ladder for a list of fields, and return
257     /// the list of steps in it in reverse order, with the first step
258     /// dropping 0 fields and so on.
259     ///
260     /// `unwind_ladder` is such a list of steps in reverse order,
261     /// which is called if the matching step of the drop glue panics.
262     fn drop_halfladder(
263         &mut self,
264         unwind_ladder: &[Unwind],
265         mut succ: BasicBlock,
266         fields: &[(Place<'tcx>, Option<D::Path>)],
267     ) -> Vec<BasicBlock> {
268         Some(succ)
269             .into_iter()
270             .chain(fields.iter().rev().zip(unwind_ladder).map(|(&(place, path), &unwind_succ)| {
271                 succ = self.drop_subpath(place, path, succ, unwind_succ);
272                 succ
273             }))
274             .collect()
275     }
276
277     fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind) {
278         // Clear the "master" drop flag at the end. This is needed
279         // because the "master" drop protects the ADT's discriminant,
280         // which is invalidated after the ADT is dropped.
281         let (succ, unwind) = (self.succ, self.unwind); // FIXME(#43234)
282         (
283             self.drop_flag_reset_block(DropFlagMode::Shallow, succ, unwind),
284             unwind.map(|unwind| {
285                 self.drop_flag_reset_block(DropFlagMode::Shallow, unwind, Unwind::InCleanup)
286             }),
287         )
288     }
289
290     /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
291     ///
292     /// For example, with 3 fields, the drop ladder is
293     ///
294     /// .d0:
295     ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
296     /// .d1:
297     ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
298     /// .d2:
299     ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
300     /// .c1:
301     ///     ELAB(drop location.1 [target=.c2])
302     /// .c2:
303     ///     ELAB(drop location.2 [target=`self.unwind`])
304     ///
305     /// NOTE: this does not clear the master drop flag, so you need
306     /// to point succ/unwind on a `drop_ladder_bottom`.
307     fn drop_ladder(
308         &mut self,
309         fields: Vec<(Place<'tcx>, Option<D::Path>)>,
310         succ: BasicBlock,
311         unwind: Unwind,
312     ) -> (BasicBlock, Unwind) {
313         debug!("drop_ladder({:?}, {:?})", self, fields);
314
315         let mut fields = fields;
316         fields.retain(|&(place, _)| {
317             self.place_ty(place).needs_drop(self.tcx(), self.elaborator.param_env())
318         });
319
320         debug!("drop_ladder - fields needing drop: {:?}", fields);
321
322         let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
323         let unwind_ladder: Vec<_> = if let Unwind::To(target) = unwind {
324             let halfladder = self.drop_halfladder(&unwind_ladder, target, &fields);
325             halfladder.into_iter().map(Unwind::To).collect()
326         } else {
327             unwind_ladder
328         };
329
330         let normal_ladder = self.drop_halfladder(&unwind_ladder, succ, &fields);
331
332         (*normal_ladder.last().unwrap(), *unwind_ladder.last().unwrap())
333     }
334
335     fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
336         debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
337
338         let fields = tys
339             .iter()
340             .enumerate()
341             .map(|(i, &ty)| {
342                 (
343                     self.tcx().mk_place_field(self.place.clone(), Field::new(i), ty),
344                     self.elaborator.field_subpath(self.path, Field::new(i)),
345                 )
346             })
347             .collect();
348
349         let (succ, unwind) = self.drop_ladder_bottom();
350         self.drop_ladder(fields, succ, unwind).0
351     }
352
353     fn open_drop_for_box(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
354         debug!("open_drop_for_box({:?}, {:?}, {:?})", self, adt, substs);
355
356         let interior = self.tcx().mk_place_deref(self.place.clone());
357         let interior_path = self.elaborator.deref_subpath(self.path);
358
359         let succ = self.succ; // FIXME(#43234)
360         let unwind = self.unwind;
361         let succ = self.box_free_block(adt, substs, succ, unwind);
362         let unwind_succ =
363             self.unwind.map(|unwind| self.box_free_block(adt, substs, unwind, Unwind::InCleanup));
364
365         self.drop_subpath(interior, interior_path, succ, unwind_succ)
366     }
367
368     fn open_drop_for_adt(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
369         debug!("open_drop_for_adt({:?}, {:?}, {:?})", self, adt, substs);
370         if adt.variants.is_empty() {
371             return self.elaborator.patch().new_block(BasicBlockData {
372                 statements: vec![],
373                 terminator: Some(Terminator {
374                     source_info: self.source_info,
375                     kind: TerminatorKind::Unreachable,
376                 }),
377                 is_cleanup: self.unwind.is_cleanup(),
378             });
379         }
380
381         let skip_contents =
382             adt.is_union() || Some(adt.did) == self.tcx().lang_items().manually_drop();
383         let contents_drop = if skip_contents {
384             (self.succ, self.unwind)
385         } else {
386             self.open_drop_for_adt_contents(adt, substs)
387         };
388
389         if adt.has_dtor(self.tcx()) {
390             self.destructor_call_block(contents_drop)
391         } else {
392             contents_drop.0
393         }
394     }
395
396     fn open_drop_for_adt_contents(
397         &mut self,
398         adt: &'tcx ty::AdtDef,
399         substs: SubstsRef<'tcx>,
400     ) -> (BasicBlock, Unwind) {
401         let (succ, unwind) = self.drop_ladder_bottom();
402         if !adt.is_enum() {
403             let fields = self.move_paths_for_fields(
404                 self.place,
405                 self.path,
406                 &adt.variants[VariantIdx::new(0)],
407                 substs,
408             );
409             self.drop_ladder(fields, succ, unwind)
410         } else {
411             self.open_drop_for_multivariant(adt, substs, succ, unwind)
412         }
413     }
414
415     fn open_drop_for_multivariant(
416         &mut self,
417         adt: &'tcx ty::AdtDef,
418         substs: SubstsRef<'tcx>,
419         succ: BasicBlock,
420         unwind: Unwind,
421     ) -> (BasicBlock, Unwind) {
422         let mut values = Vec::with_capacity(adt.variants.len());
423         let mut normal_blocks = Vec::with_capacity(adt.variants.len());
424         let mut unwind_blocks =
425             if unwind.is_cleanup() { None } else { Some(Vec::with_capacity(adt.variants.len())) };
426
427         let mut have_otherwise_with_drop_glue = false;
428         let mut have_otherwise = false;
429         let tcx = self.tcx();
430
431         for (variant_index, discr) in adt.discriminants(tcx) {
432             let variant = &adt.variants[variant_index];
433             let subpath = self.elaborator.downcast_subpath(self.path, variant_index);
434
435             if let Some(variant_path) = subpath {
436                 let base_place = tcx.mk_place_elem(
437                     self.place.clone(),
438                     ProjectionElem::Downcast(Some(variant.ident.name), variant_index),
439                 );
440                 let fields = self.move_paths_for_fields(base_place, variant_path, &variant, substs);
441                 values.push(discr.val);
442                 if let Unwind::To(unwind) = unwind {
443                     // We can't use the half-ladder from the original
444                     // drop ladder, because this breaks the
445                     // "funclet can't have 2 successor funclets"
446                     // requirement from MSVC:
447                     //
448                     //           switch       unwind-switch
449                     //          /      \         /        \
450                     //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
451                     //         |        |      /             |
452                     //    v1.1-unwind  v2.1-unwind           |
453                     //      ^                                |
454                     //       \-------------------------------/
455                     //
456                     // Create a duplicate half-ladder to avoid that. We
457                     // could technically only do this on MSVC, but I
458                     // I want to minimize the divergence between MSVC
459                     // and non-MSVC.
460
461                     let unwind_blocks = unwind_blocks.as_mut().unwrap();
462                     let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
463                     let halfladder = self.drop_halfladder(&unwind_ladder, unwind, &fields);
464                     unwind_blocks.push(halfladder.last().cloned().unwrap());
465                 }
466                 let (normal, _) = self.drop_ladder(fields, succ, unwind);
467                 normal_blocks.push(normal);
468             } else {
469                 have_otherwise = true;
470
471                 let param_env = self.elaborator.param_env();
472                 let have_field_with_drop_glue = variant
473                     .fields
474                     .iter()
475                     .any(|field| field.ty(tcx, substs).needs_drop(tcx, param_env));
476                 if have_field_with_drop_glue {
477                     have_otherwise_with_drop_glue = true;
478                 }
479             }
480         }
481
482         if !have_otherwise {
483             values.pop();
484         } else if !have_otherwise_with_drop_glue {
485             normal_blocks.push(self.goto_block(succ, unwind));
486             if let Unwind::To(unwind) = unwind {
487                 unwind_blocks.as_mut().unwrap().push(self.goto_block(unwind, Unwind::InCleanup));
488             }
489         } else {
490             normal_blocks.push(self.drop_block(succ, unwind));
491             if let Unwind::To(unwind) = unwind {
492                 unwind_blocks.as_mut().unwrap().push(self.drop_block(unwind, Unwind::InCleanup));
493             }
494         }
495
496         (
497             self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
498             unwind.map(|unwind| {
499                 self.adt_switch_block(
500                     adt,
501                     unwind_blocks.unwrap(),
502                     &values,
503                     unwind,
504                     Unwind::InCleanup,
505                 )
506             }),
507         )
508     }
509
510     fn adt_switch_block(
511         &mut self,
512         adt: &'tcx ty::AdtDef,
513         blocks: Vec<BasicBlock>,
514         values: &[u128],
515         succ: BasicBlock,
516         unwind: Unwind,
517     ) -> BasicBlock {
518         // If there are multiple variants, then if something
519         // is present within the enum the discriminant, tracked
520         // by the rest path, must be initialized.
521         //
522         // Additionally, we do not want to switch on the
523         // discriminant after it is free-ed, because that
524         // way lies only trouble.
525         let discr_ty = adt.repr.discr_type().to_ty(self.tcx());
526         let discr = Place::from(self.new_temp(discr_ty));
527         let discr_rv = Rvalue::Discriminant(self.place);
528         let switch_block = BasicBlockData {
529             statements: vec![self.assign(discr, discr_rv)],
530             terminator: Some(Terminator {
531                 source_info: self.source_info,
532                 kind: TerminatorKind::SwitchInt {
533                     discr: Operand::Move(discr),
534                     switch_ty: discr_ty,
535                     values: From::from(values.to_owned()),
536                     targets: blocks,
537                 },
538             }),
539             is_cleanup: unwind.is_cleanup(),
540         };
541         let switch_block = self.elaborator.patch().new_block(switch_block);
542         self.drop_flag_test_block(switch_block, succ, unwind)
543     }
544
545     fn destructor_call_block(&mut self, (succ, unwind): (BasicBlock, Unwind)) -> BasicBlock {
546         debug!("destructor_call_block({:?}, {:?})", self, succ);
547         let tcx = self.tcx();
548         let drop_trait = tcx.lang_items().drop_trait().unwrap();
549         let drop_fn = tcx.associated_items(drop_trait).in_definition_order().next().unwrap();
550         let ty = self.place_ty(self.place);
551         let substs = tcx.mk_substs_trait(ty, &[]);
552
553         let ref_ty =
554             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Mut });
555         let ref_place = self.new_temp(ref_ty);
556         let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
557
558         let result = BasicBlockData {
559             statements: vec![self.assign(
560                 Place::from(ref_place),
561                 Rvalue::Ref(
562                     tcx.lifetimes.re_erased,
563                     BorrowKind::Mut { allow_two_phase_borrow: false },
564                     self.place,
565                 ),
566             )],
567             terminator: Some(Terminator {
568                 kind: TerminatorKind::Call {
569                     func: Operand::function_handle(
570                         tcx,
571                         drop_fn.def_id,
572                         substs,
573                         self.source_info.span,
574                     ),
575                     args: vec![Operand::Move(Place::from(ref_place))],
576                     destination: Some((unit_temp, succ)),
577                     cleanup: unwind.into_option(),
578                     from_hir_call: true,
579                 },
580                 source_info: self.source_info,
581             }),
582             is_cleanup: unwind.is_cleanup(),
583         };
584         self.elaborator.patch().new_block(result)
585     }
586
587     /// Create a loop that drops an array:
588     ///
589     /// ```text
590     /// loop-block:
591     ///    can_go = cur == length_or_end
592     ///    if can_go then succ else drop-block
593     /// drop-block:
594     ///    if ptr_based {
595     ///        ptr = cur
596     ///        cur = cur.offset(1)
597     ///    } else {
598     ///        ptr = &raw mut P[cur]
599     ///        cur = cur + 1
600     ///    }
601     ///    drop(ptr)
602     /// ```
603     fn drop_loop(
604         &mut self,
605         succ: BasicBlock,
606         cur: Local,
607         length_or_end: Place<'tcx>,
608         ety: Ty<'tcx>,
609         unwind: Unwind,
610         ptr_based: bool,
611     ) -> BasicBlock {
612         let copy = |place: Place<'tcx>| Operand::Copy(place);
613         let move_ = |place: Place<'tcx>| Operand::Move(place);
614         let tcx = self.tcx();
615
616         let ptr_ty = tcx.mk_ptr(ty::TypeAndMut { ty: ety, mutbl: hir::Mutability::Mut });
617         let ptr = Place::from(self.new_temp(ptr_ty));
618         let can_go = Place::from(self.new_temp(tcx.types.bool));
619
620         let one = self.constant_usize(1);
621         let (ptr_next, cur_next) = if ptr_based {
622             (Rvalue::Use(copy(cur.into())), Rvalue::BinaryOp(BinOp::Offset, move_(cur.into()), one))
623         } else {
624             (
625                 Rvalue::AddressOf(Mutability::Mut, tcx.mk_place_index(self.place.clone(), cur)),
626                 Rvalue::BinaryOp(BinOp::Add, move_(cur.into()), one),
627             )
628         };
629
630         let drop_block = BasicBlockData {
631             statements: vec![self.assign(ptr, ptr_next), self.assign(Place::from(cur), cur_next)],
632             is_cleanup: unwind.is_cleanup(),
633             terminator: Some(Terminator {
634                 source_info: self.source_info,
635                 // this gets overwritten by drop elaboration.
636                 kind: TerminatorKind::Unreachable,
637             }),
638         };
639         let drop_block = self.elaborator.patch().new_block(drop_block);
640
641         let loop_block = BasicBlockData {
642             statements: vec![self.assign(
643                 can_go,
644                 Rvalue::BinaryOp(BinOp::Eq, copy(Place::from(cur)), copy(length_or_end)),
645             )],
646             is_cleanup: unwind.is_cleanup(),
647             terminator: Some(Terminator {
648                 source_info: self.source_info,
649                 kind: TerminatorKind::if_(tcx, move_(can_go), succ, drop_block),
650             }),
651         };
652         let loop_block = self.elaborator.patch().new_block(loop_block);
653
654         self.elaborator.patch().patch_terminator(
655             drop_block,
656             TerminatorKind::Drop {
657                 location: tcx.mk_place_deref(ptr.clone()),
658                 target: loop_block,
659                 unwind: unwind.into_option(),
660             },
661         );
662
663         loop_block
664     }
665
666     fn open_drop_for_array(&mut self, ety: Ty<'tcx>, opt_size: Option<u64>) -> BasicBlock {
667         debug!("open_drop_for_array({:?}, {:?})", ety, opt_size);
668
669         // if size_of::<ety>() == 0 {
670         //     index_based_loop
671         // } else {
672         //     ptr_based_loop
673         // }
674
675         let tcx = self.tcx();
676
677         if let Some(size) = opt_size {
678             let size: u32 = size.try_into().unwrap_or_else(|_| {
679                 bug!("move out check isn't implemented for array sizes bigger than u32::MAX");
680             });
681             let fields: Vec<(Place<'tcx>, Option<D::Path>)> = (0..size)
682                 .map(|i| {
683                     (
684                         tcx.mk_place_elem(
685                             self.place.clone(),
686                             ProjectionElem::ConstantIndex {
687                                 offset: i,
688                                 min_length: size,
689                                 from_end: false,
690                             },
691                         ),
692                         self.elaborator.array_subpath(self.path, i, size),
693                     )
694                 })
695                 .collect();
696
697             if fields.iter().any(|(_, path)| path.is_some()) {
698                 let (succ, unwind) = self.drop_ladder_bottom();
699                 return self.drop_ladder(fields, succ, unwind).0;
700             }
701         }
702
703         let move_ = |place: Place<'tcx>| Operand::Move(place);
704         let elem_size = Place::from(self.new_temp(tcx.types.usize));
705         let len = Place::from(self.new_temp(tcx.types.usize));
706
707         static USIZE_SWITCH_ZERO: &[u128] = &[0];
708
709         let base_block = BasicBlockData {
710             statements: vec![
711                 self.assign(elem_size, Rvalue::NullaryOp(NullOp::SizeOf, ety)),
712                 self.assign(len, Rvalue::Len(self.place)),
713             ],
714             is_cleanup: self.unwind.is_cleanup(),
715             terminator: Some(Terminator {
716                 source_info: self.source_info,
717                 kind: TerminatorKind::SwitchInt {
718                     discr: move_(elem_size),
719                     switch_ty: tcx.types.usize,
720                     values: From::from(USIZE_SWITCH_ZERO),
721                     targets: vec![
722                         self.drop_loop_pair(ety, false, len.clone()),
723                         self.drop_loop_pair(ety, true, len.clone()),
724                     ],
725                 },
726             }),
727         };
728         self.elaborator.patch().new_block(base_block)
729     }
730
731     /// Creates a pair of drop-loops of `place`, which drops its contents, even
732     /// in the case of 1 panic. If `ptr_based`, creates a pointer loop,
733     /// otherwise create an index loop.
734     fn drop_loop_pair(
735         &mut self,
736         ety: Ty<'tcx>,
737         ptr_based: bool,
738         length: Place<'tcx>,
739     ) -> BasicBlock {
740         debug!("drop_loop_pair({:?}, {:?})", ety, ptr_based);
741         let tcx = self.tcx();
742         let iter_ty = if ptr_based { tcx.mk_mut_ptr(ety) } else { tcx.types.usize };
743
744         let cur = self.new_temp(iter_ty);
745         let length_or_end = if ptr_based { Place::from(self.new_temp(iter_ty)) } else { length };
746
747         let unwind = self.unwind.map(|unwind| {
748             self.drop_loop(unwind, cur, length_or_end, ety, Unwind::InCleanup, ptr_based)
749         });
750
751         let loop_block = self.drop_loop(self.succ, cur, length_or_end, ety, unwind, ptr_based);
752
753         let cur = Place::from(cur);
754         let drop_block_stmts = if ptr_based {
755             let tmp_ty = tcx.mk_mut_ptr(self.place_ty(self.place));
756             let tmp = Place::from(self.new_temp(tmp_ty));
757             // tmp = &raw mut P;
758             // cur = tmp as *mut T;
759             // end = Offset(cur, len);
760             vec![
761                 self.assign(tmp, Rvalue::AddressOf(Mutability::Mut, self.place)),
762                 self.assign(cur, Rvalue::Cast(CastKind::Misc, Operand::Move(tmp), iter_ty)),
763                 self.assign(
764                     length_or_end,
765                     Rvalue::BinaryOp(BinOp::Offset, Operand::Copy(cur), Operand::Move(length)),
766                 ),
767             ]
768         } else {
769             // cur = 0 (length already pushed)
770             let zero = self.constant_usize(0);
771             vec![self.assign(cur, Rvalue::Use(zero))]
772         };
773         let drop_block = self.elaborator.patch().new_block(BasicBlockData {
774             statements: drop_block_stmts,
775             is_cleanup: unwind.is_cleanup(),
776             terminator: Some(Terminator {
777                 source_info: self.source_info,
778                 kind: TerminatorKind::Goto { target: loop_block },
779             }),
780         });
781
782         // FIXME(#34708): handle partially-dropped array/slice elements.
783         let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
784         self.drop_flag_test_block(reset_block, self.succ, unwind)
785     }
786
787     /// The slow-path - create an "open", elaborated drop for a type
788     /// which is moved-out-of only partially, and patch `bb` to a jump
789     /// to it. This must not be called on ADTs with a destructor,
790     /// as these can't be moved-out-of, except for `Box<T>`, which is
791     /// special-cased.
792     ///
793     /// This creates a "drop ladder" that drops the needed fields of the
794     /// ADT, both in the success case or if one of the destructors fail.
795     fn open_drop(&mut self) -> BasicBlock {
796         let ty = self.place_ty(self.place);
797         match ty.kind {
798             ty::Closure(_, substs) => {
799                 let tys: Vec<_> = substs.as_closure().upvar_tys().collect();
800                 self.open_drop_for_tuple(&tys)
801             }
802             // Note that `elaborate_drops` only drops the upvars of a generator,
803             // and this is ok because `open_drop` here can only be reached
804             // within that own generator's resume function.
805             // This should only happen for the self argument on the resume function.
806             // It effetively only contains upvars until the generator transformation runs.
807             // See librustc_body/transform/generator.rs for more details.
808             ty::Generator(_, substs, _) => {
809                 let tys: Vec<_> = substs.as_generator().upvar_tys().collect();
810                 self.open_drop_for_tuple(&tys)
811             }
812             ty::Tuple(..) => {
813                 let tys: Vec<_> = ty.tuple_fields().collect();
814                 self.open_drop_for_tuple(&tys)
815             }
816             ty::Adt(def, substs) => {
817                 if def.is_box() {
818                     self.open_drop_for_box(def, substs)
819                 } else {
820                     self.open_drop_for_adt(def, substs)
821                 }
822             }
823             ty::Dynamic(..) => {
824                 let unwind = self.unwind; // FIXME(#43234)
825                 let succ = self.succ;
826                 self.complete_drop(Some(DropFlagMode::Deep), succ, unwind)
827             }
828             ty::Array(ety, size) => {
829                 let size = size.try_eval_usize(self.tcx(), self.elaborator.param_env());
830                 self.open_drop_for_array(ety, size)
831             }
832             ty::Slice(ety) => self.open_drop_for_array(ety, None),
833
834             _ => bug!("open drop from non-ADT `{:?}`", ty),
835         }
836     }
837
838     /// Returns a basic block that drop a place using the context
839     /// and path in `c`. If `mode` is something, also clear `c`
840     /// according to it.
841     ///
842     /// if FLAG(self.path)
843     ///     if let Some(mode) = mode: FLAG(self.path)[mode] = false
844     ///     drop(self.place)
845     fn complete_drop(
846         &mut self,
847         drop_mode: Option<DropFlagMode>,
848         succ: BasicBlock,
849         unwind: Unwind,
850     ) -> BasicBlock {
851         debug!("complete_drop({:?},{:?})", self, drop_mode);
852
853         let drop_block = self.drop_block(succ, unwind);
854         let drop_block = if let Some(mode) = drop_mode {
855             self.drop_flag_reset_block(mode, drop_block, unwind)
856         } else {
857             drop_block
858         };
859
860         self.drop_flag_test_block(drop_block, succ, unwind)
861     }
862
863     fn drop_flag_reset_block(
864         &mut self,
865         mode: DropFlagMode,
866         succ: BasicBlock,
867         unwind: Unwind,
868     ) -> BasicBlock {
869         debug!("drop_flag_reset_block({:?},{:?})", self, mode);
870
871         let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
872         let block_start = Location { block, statement_index: 0 };
873         self.elaborator.clear_drop_flag(block_start, self.path, mode);
874         block
875     }
876
877     fn elaborated_drop_block(&mut self) -> BasicBlock {
878         debug!("elaborated_drop_block({:?})", self);
879         let unwind = self.unwind; // FIXME(#43234)
880         let succ = self.succ;
881         let blk = self.drop_block(succ, unwind);
882         self.elaborate_drop(blk);
883         blk
884     }
885
886     fn box_free_block(
887         &mut self,
888         adt: &'tcx ty::AdtDef,
889         substs: SubstsRef<'tcx>,
890         target: BasicBlock,
891         unwind: Unwind,
892     ) -> BasicBlock {
893         let block = self.unelaborated_free_block(adt, substs, target, unwind);
894         self.drop_flag_test_block(block, target, unwind)
895     }
896
897     fn unelaborated_free_block(
898         &mut self,
899         adt: &'tcx ty::AdtDef,
900         substs: SubstsRef<'tcx>,
901         target: BasicBlock,
902         unwind: Unwind,
903     ) -> BasicBlock {
904         let tcx = self.tcx();
905         let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
906         let free_func =
907             tcx.require_lang_item(lang_items::BoxFreeFnLangItem, Some(self.source_info.span));
908         let args = adt.variants[VariantIdx::new(0)]
909             .fields
910             .iter()
911             .enumerate()
912             .map(|(i, f)| {
913                 let field = Field::new(i);
914                 let field_ty = f.ty(tcx, substs);
915                 Operand::Move(tcx.mk_place_field(self.place.clone(), field, field_ty))
916             })
917             .collect();
918
919         let call = TerminatorKind::Call {
920             func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
921             args,
922             destination: Some((unit_temp, target)),
923             cleanup: None,
924             from_hir_call: false,
925         }; // FIXME(#43234)
926         let free_block = self.new_block(unwind, call);
927
928         let block_start = Location { block: free_block, statement_index: 0 };
929         self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
930         free_block
931     }
932
933     fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
934         let block =
935             TerminatorKind::Drop { location: self.place, target, unwind: unwind.into_option() };
936         self.new_block(unwind, block)
937     }
938
939     fn goto_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
940         let block = TerminatorKind::Goto { target };
941         self.new_block(unwind, block)
942     }
943
944     fn drop_flag_test_block(
945         &mut self,
946         on_set: BasicBlock,
947         on_unset: BasicBlock,
948         unwind: Unwind,
949     ) -> BasicBlock {
950         let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
951         debug!(
952             "drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
953             self, on_set, on_unset, unwind, style
954         );
955
956         match style {
957             DropStyle::Dead => on_unset,
958             DropStyle::Static => on_set,
959             DropStyle::Conditional | DropStyle::Open => {
960                 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
961                 let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
962                 self.new_block(unwind, term)
963             }
964         }
965     }
966
967     fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
968         self.elaborator.patch().new_block(BasicBlockData {
969             statements: vec![],
970             terminator: Some(Terminator { source_info: self.source_info, kind: k }),
971             is_cleanup: unwind.is_cleanup(),
972         })
973     }
974
975     fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
976         self.elaborator.patch().new_temp(ty, self.source_info.span)
977     }
978
979     fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
980         let body = self.elaborator.body();
981         self.elaborator.patch().terminator_loc(body, bb)
982     }
983
984     fn constant_usize(&self, val: u16) -> Operand<'tcx> {
985         Operand::Constant(box Constant {
986             span: self.source_info.span,
987             user_ty: None,
988             literal: ty::Const::from_usize(self.tcx(), val.into()),
989         })
990     }
991
992     fn assign(&self, lhs: Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
993         Statement { source_info: self.source_info, kind: StatementKind::Assign(box (lhs, rhs)) }
994     }
995 }