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