]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/elaborate_drops.rs
Rollup merge of #65763 - ObsidianMinor:diag/65642, r=varkor
[rust.git] / src / librustc_mir / util / elaborate_drops.rs
1 use std::fmt;
2 use rustc::hir;
3 use rustc::mir::*;
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_index::vec::Idx;
11 use crate::util::patch::MirPatch;
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 where F: FnOnce(BasicBlock) -> BasicBlock {
66         match self {
67             Unwind::To(bb) => Unwind::To(f(bb)),
68             Unwind::InCleanup => Unwind::InCleanup
69         }
70     }
71 }
72
73 pub trait DropElaborator<'a, 'tcx>: fmt::Debug {
74     type Path : Copy + fmt::Debug;
75
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>;
80
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);
84
85
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>;
90 }
91
92 #[derive(Debug)]
93 struct DropCtxt<'l, 'b, 'tcx, D>
94 where
95     D: DropElaborator<'b, 'tcx>,
96 {
97     elaborator: &'l mut D,
98
99     source_info: SourceInfo,
100
101     place: &'l Place<'tcx>,
102     path: D::Path,
103     succ: BasicBlock,
104     unwind: Unwind,
105 }
106
107 pub fn elaborate_drop<'b, 'tcx, D>(
108     elaborator: &mut D,
109     source_info: SourceInfo,
110     place: &Place<'tcx>,
111     path: D::Path,
112     succ: BasicBlock,
113     unwind: Unwind,
114     bb: BasicBlock,
115 ) where
116     D: DropElaborator<'b, 'tcx>,
117     'tcx: 'b,
118 {
119     DropCtxt {
120         elaborator, source_info, place, path, succ, unwind
121     }.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({:?})", self);
157         let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
158         debug!("elaborate_drop({:?}): live - {:?}", self, style);
159         match style {
160             DropStyle::Dead => {
161                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
162                     target: self.succ
163                 });
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(bb, TerminatorKind::Drop {
169                     location: self.place.clone(),
170                     target: self.succ,
171                     unwind: self.unwind.into_option(),
172                 });
173             }
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 {
179                     target: drop_bb
180                 });
181             }
182             DropStyle::Open => {
183                 let drop_bb = self.open_drop();
184                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
185                     target: drop_bb
186                 });
187             }
188         }
189     }
190
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>)>
199     {
200         variant.fields.iter().enumerate().map(|(i, f)| {
201             let field = Field::new(i);
202             let subpath = self.elaborator.field_subpath(variant_path, field);
203
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),
208             );
209             (base_place.clone().field(field, field_ty), subpath)
210         }).collect()
211     }
212
213     fn drop_subpath(&mut self,
214                     place: &Place<'tcx>,
215                     path: Option<D::Path>,
216                     succ: BasicBlock,
217                     unwind: Unwind)
218                     -> BasicBlock
219     {
220         if let Some(path) = path {
221             debug!("drop_subpath: for std field {:?}", place);
222
223             DropCtxt {
224                 elaborator: self.elaborator,
225                 source_info: self.source_info,
226                 path, place, succ, unwind,
227             }.elaborated_drop_block()
228         } else {
229             debug!("drop_subpath: for rest field {:?}", place);
230
231             DropCtxt {
232                 elaborator: self.elaborator,
233                 source_info: self.source_info,
234                 place, succ, unwind,
235                 // Using `self.path` here to condition the drop on
236                 // our own drop flag.
237                 path: self.path
238             }.complete_drop(None, succ, unwind)
239         }
240     }
241
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.
245     ///
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>)])
252                        -> Vec<BasicBlock>
253     {
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);
258                     succ
259                 })
260         ).collect()
261     }
262
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)
268         (
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)
272             })
273         )
274     }
275
276     /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
277     ///
278     /// For example, with 3 fields, the drop ladder is
279     ///
280     /// .d0:
281     ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
282     /// .d1:
283     ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
284     /// .d2:
285     ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
286     /// .c1:
287     ///     ELAB(drop location.1 [target=.c2])
288     /// .c2:
289     ///     ELAB(drop location.2 [target=`self.unwind`])
290     ///
291     /// NOTE: this does not clear the master drop flag, so you need
292     /// to point succ/unwind on a `drop_ladder_bottom`.
293     fn drop_ladder(
294         &mut self,
295         fields: Vec<(Place<'tcx>, Option<D::Path>)>,
296         succ: BasicBlock,
297         unwind: Unwind,
298     ) -> (BasicBlock, Unwind) {
299         debug!("drop_ladder({:?}, {:?})", self, fields);
300
301         let mut fields = fields;
302         fields.retain(|&(ref place, _)| {
303             self.place_ty(place).needs_drop(self.tcx(), self.elaborator.param_env())
304         });
305
306         debug!("drop_ladder - fields needing drop: {:?}", fields);
307
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()
312         } else {
313             unwind_ladder
314         };
315
316         let normal_ladder =
317             self.drop_halfladder(&unwind_ladder, succ, &fields);
318
319         (*normal_ladder.last().unwrap(), *unwind_ladder.last().unwrap())
320     }
321
322     fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
323         debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
324
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)))
328         }).collect();
329
330         let (succ, unwind) = self.drop_ladder_bottom();
331         self.drop_ladder(fields, succ, unwind).0
332     }
333
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);
336
337         let interior = self.place.clone().deref();
338         let interior_path = self.elaborator.deref_subpath(self.path);
339
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)
345         });
346
347         self.drop_subpath(&interior, interior_path, succ, unwind_succ)
348     }
349
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 {
354                 statements: vec![],
355                 terminator: Some(Terminator {
356                     source_info: self.source_info,
357                     kind: TerminatorKind::Unreachable
358                 }),
359                 is_cleanup: self.unwind.is_cleanup()
360             });
361         }
362
363         let skip_contents =
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)
367         } else {
368             self.open_drop_for_adt_contents(adt, substs)
369         };
370
371         if adt.has_dtor(self.tcx()) {
372             self.destructor_call_block(contents_drop)
373         } else {
374             contents_drop.0
375         }
376     }
377
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();
382         if !adt.is_enum() {
383             let fields = self.move_paths_for_fields(
384                 self.place,
385                 self.path,
386                 &adt.variants[VariantIdx::new(0)],
387                 substs
388             );
389             self.drop_ladder(fields, succ, unwind)
390         } else {
391             self.open_drop_for_multivariant(adt, substs, succ, unwind)
392         }
393     }
394
395     fn open_drop_for_multivariant(&mut self, adt: &'tcx ty::AdtDef,
396                                   substs: SubstsRef<'tcx>,
397                                   succ: BasicBlock,
398                                   unwind: Unwind)
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() {
403             None
404         } else {
405             Some(Vec::with_capacity(adt.variants.len()))
406         };
407
408         let mut have_otherwise = false;
409
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),
416                                              variant_index));
417                 let fields = self.move_paths_for_fields(
418                     &base_place,
419                     variant_path,
420                     &adt.variants[variant_index],
421                     substs);
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:
428                     //
429                     //           switch       unwind-switch
430                     //          /      \         /        \
431                     //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
432                     //         |        |      /             |
433                     //    v1.1-unwind  v2.1-unwind           |
434                     //      ^                                |
435                     //       \-------------------------------/
436                     //
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
440                     // and non-MSVC.
441
442                     let unwind_blocks = unwind_blocks.as_mut().unwrap();
443                     let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
444                     let halfladder =
445                         self.drop_halfladder(&unwind_ladder, unwind, &fields);
446                     unwind_blocks.push(halfladder.last().cloned().unwrap());
447                 }
448                 let (normal, _) = self.drop_ladder(fields, succ, unwind);
449                 normal_blocks.push(normal);
450             } else {
451                 have_otherwise = true;
452             }
453         }
454
455         if have_otherwise {
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)
460                         );
461             }
462         } else {
463             values.pop();
464         }
465
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
470              )
471          }))
472     }
473
474     fn adt_switch_block(&mut self,
475                         adt: &'tcx ty::AdtDef,
476                         blocks: Vec<BasicBlock>,
477                         values: &[u128],
478                         succ: BasicBlock,
479                         unwind: Unwind)
480                         -> 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.
484         //
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),
497                     switch_ty: discr_ty,
498                     values: From::from(values.to_owned()),
499                     targets: blocks,
500                 }
501             }),
502             is_cleanup: unwind.is_cleanup(),
503         };
504         let switch_block = self.elaborator.patch().new_block(switch_block);
505         self.drop_flag_test_block(switch_block, succ, unwind)
506     }
507
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, &[]);
515
516         let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
517             ty,
518             mutbl: hir::Mutability::MutMutable
519         });
520         let ref_place = self.new_temp(ref_ty);
521         let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
522
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 },
528                             self.place.clone())
529             )],
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(),
537                     from_hir_call: true,
538                 },
539                 source_info: self.source_info,
540             }),
541             is_cleanup: unwind.is_cleanup(),
542         };
543         self.elaborator.patch().new_block(result)
544     }
545
546     /// Create a loop that drops an array:
547     ///
548     /// ```text
549     /// loop-block:
550     ///    can_go = cur == length_or_end
551     ///    if can_go then succ else drop-block
552     /// drop-block:
553     ///    if ptr_based {
554     ///        ptr = &mut *cur
555     ///        cur = cur.offset(1)
556     ///    } else {
557     ///        ptr = &mut P[cur]
558     ///        cur = cur + 1
559     ///    }
560     ///    drop(ptr)
561     /// ```
562     fn drop_loop(
563         &mut self,
564         succ: BasicBlock,
565         cur: Local,
566         length_or_end: &Place<'tcx>,
567         ety: Ty<'tcx>,
568         unwind: Unwind,
569         ptr_based: bool,
570     ) -> BasicBlock {
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();
574
575         let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
576             ty: ety,
577             mutbl: hir::Mutability::MutMutable
578         });
579         let ptr = &Place::from(self.new_temp(ref_ty));
580         let can_go = &Place::from(self.new_temp(tcx.types.bool));
581
582         let one = self.constant_usize(1);
583         let (ptr_next, cur_next) = if ptr_based {
584             (Rvalue::Ref(
585                 tcx.lifetimes.re_erased,
586                 BorrowKind::Mut { allow_two_phase_borrow: false },
587                 Place {
588                     base: PlaceBase::Local(cur),
589                     projection: Box::new([ProjectionElem::Deref]),
590                 }
591              ),
592              Rvalue::BinaryOp(BinOp::Offset, move_(&Place::from(cur)), one))
593         } else {
594             (Rvalue::Ref(
595                  tcx.lifetimes.re_erased,
596                  BorrowKind::Mut { allow_two_phase_borrow: false },
597                  self.place.clone().index(cur)),
598              Rvalue::BinaryOp(BinOp::Add, move_(&Place::from(cur)), one))
599         };
600
601         let drop_block = BasicBlockData {
602             statements: vec![
603                 self.assign(ptr, ptr_next),
604                 self.assign(&Place::from(cur), cur_next)
605             ],
606             is_cleanup: unwind.is_cleanup(),
607             terminator: Some(Terminator {
608                 source_info: self.source_info,
609                 // this gets overwritten by drop elaboration.
610                 kind: TerminatorKind::Unreachable,
611             })
612         };
613         let drop_block = self.elaborator.patch().new_block(drop_block);
614
615         let loop_block = BasicBlockData {
616             statements: vec![
617                 self.assign(can_go, Rvalue::BinaryOp(BinOp::Eq,
618                                                      copy(&Place::from(cur)),
619                                                      copy(length_or_end)))
620             ],
621             is_cleanup: unwind.is_cleanup(),
622             terminator: Some(Terminator {
623                 source_info: self.source_info,
624                 kind: TerminatorKind::if_(tcx, move_(can_go), succ, drop_block)
625             })
626         };
627         let loop_block = self.elaborator.patch().new_block(loop_block);
628
629         self.elaborator.patch().patch_terminator(drop_block, TerminatorKind::Drop {
630             location: ptr.clone().deref(),
631             target: loop_block,
632             unwind: unwind.into_option()
633         });
634
635         loop_block
636     }
637
638     fn open_drop_for_array(&mut self, ety: Ty<'tcx>, opt_size: Option<u64>) -> BasicBlock {
639         debug!("open_drop_for_array({:?}, {:?})", ety, opt_size);
640
641         // if size_of::<ety>() == 0 {
642         //     index_based_loop
643         // } else {
644         //     ptr_based_loop
645         // }
646
647         if let Some(size) = opt_size {
648             let size: u32 = size.try_into().unwrap_or_else(|_| {
649                 bug!("move out check isn't implemented for array sizes bigger than u32::MAX");
650             });
651             let fields: Vec<(Place<'tcx>, Option<D::Path>)> = (0..size).map(|i| {
652                 (self.place.clone().elem(ProjectionElem::ConstantIndex{
653                     offset: i,
654                     min_length: size,
655                     from_end: false
656                 }),
657                  self.elaborator.array_subpath(self.path, i, size))
658             }).collect();
659
660             if fields.iter().any(|(_,path)| path.is_some()) {
661                 let (succ, unwind) = self.drop_ladder_bottom();
662                 return self.drop_ladder(fields, succ, unwind).0
663             }
664         }
665
666         let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
667         let tcx = self.tcx();
668         let elem_size = &Place::from(self.new_temp(tcx.types.usize));
669         let len = &Place::from(self.new_temp(tcx.types.usize));
670
671         static USIZE_SWITCH_ZERO: &[u128] = &[0];
672
673         let base_block = BasicBlockData {
674             statements: vec![
675                 self.assign(elem_size, Rvalue::NullaryOp(NullOp::SizeOf, ety)),
676                 self.assign(len, Rvalue::Len(self.place.clone())),
677             ],
678             is_cleanup: self.unwind.is_cleanup(),
679             terminator: Some(Terminator {
680                 source_info: self.source_info,
681                 kind: TerminatorKind::SwitchInt {
682                     discr: move_(elem_size),
683                     switch_ty: tcx.types.usize,
684                     values: From::from(USIZE_SWITCH_ZERO),
685                     targets: vec![
686                         self.drop_loop_pair(ety, false, len.clone()),
687                         self.drop_loop_pair(ety, true, len.clone()),
688                     ],
689                 },
690             })
691         };
692         self.elaborator.patch().new_block(base_block)
693     }
694
695     /// Ceates a pair of drop-loops of `place`, which drops its contents, even
696     /// in the case of 1 panic. If `ptr_based`, creates a pointer loop,
697     /// otherwise create an index loop.
698     fn drop_loop_pair(
699         &mut self,
700         ety: Ty<'tcx>,
701         ptr_based: bool,
702         length: Place<'tcx>,
703     ) -> BasicBlock {
704         debug!("drop_loop_pair({:?}, {:?})", ety, ptr_based);
705         let tcx = self.tcx();
706         let iter_ty = if ptr_based {
707             tcx.mk_mut_ptr(ety)
708         } else {
709             tcx.types.usize
710         };
711
712         let cur = self.new_temp(iter_ty);
713         let length_or_end = if ptr_based {
714             // FIXME check if we want to make it return a `Place` directly
715             // if all use sites want a `Place::Base` anyway.
716             Place::from(self.new_temp(iter_ty))
717         } else {
718             length.clone()
719         };
720
721         let unwind = self.unwind.map(|unwind| {
722             self.drop_loop(unwind,
723                            cur,
724                            &length_or_end,
725                            ety,
726                            Unwind::InCleanup,
727                            ptr_based)
728         });
729
730         let loop_block = self.drop_loop(
731             self.succ,
732             cur,
733             &length_or_end,
734             ety,
735             unwind,
736             ptr_based);
737
738         let cur = Place::from(cur);
739         let drop_block_stmts = if ptr_based {
740             let tmp_ty = tcx.mk_mut_ptr(self.place_ty(self.place));
741             let tmp = Place::from(self.new_temp(tmp_ty));
742             // tmp = &mut P;
743             // cur = tmp as *mut T;
744             // end = Offset(cur, len);
745             vec![
746                 self.assign(&tmp, Rvalue::Ref(
747                     tcx.lifetimes.re_erased,
748                     BorrowKind::Mut { allow_two_phase_borrow: false },
749                     self.place.clone()
750                 )),
751                 self.assign(
752                     &cur,
753                     Rvalue::Cast(CastKind::Misc, Operand::Move(tmp), iter_ty),
754                 ),
755                 self.assign(
756                     &length_or_end,
757                     Rvalue::BinaryOp(BinOp::Offset, Operand::Copy(cur), Operand::Move(length)
758                 )),
759             ]
760         } else {
761             // cur = 0 (length already pushed)
762             let zero = self.constant_usize(0);
763             vec![self.assign(&cur, Rvalue::Use(zero))]
764         };
765         let drop_block = self.elaborator.patch().new_block(BasicBlockData {
766             statements: drop_block_stmts,
767             is_cleanup: unwind.is_cleanup(),
768             terminator: Some(Terminator {
769                 source_info: self.source_info,
770                 kind: TerminatorKind::Goto { target: loop_block }
771             })
772         });
773
774         // FIXME(#34708): handle partially-dropped array/slice elements.
775         let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
776         self.drop_flag_test_block(reset_block, self.succ, unwind)
777     }
778
779     /// The slow-path - create an "open", elaborated drop for a type
780     /// which is moved-out-of only partially, and patch `bb` to a jump
781     /// to it. This must not be called on ADTs with a destructor,
782     /// as these can't be moved-out-of, except for `Box<T>`, which is
783     /// special-cased.
784     ///
785     /// This creates a "drop ladder" that drops the needed fields of the
786     /// ADT, both in the success case or if one of the destructors fail.
787     fn open_drop(&mut self) -> BasicBlock {
788         let ty = self.place_ty(self.place);
789         match ty.kind {
790             ty::Closure(def_id, substs) => {
791                 let tys : Vec<_> = substs.as_closure().upvar_tys(def_id, self.tcx()).collect();
792                 self.open_drop_for_tuple(&tys)
793             }
794             // Note that `elaborate_drops` only drops the upvars of a generator,
795             // and this is ok because `open_drop` here can only be reached
796             // within that own generator's resume function.
797             // This should only happen for the self argument on the resume function.
798             // It effetively only contains upvars until the generator transformation runs.
799             // See librustc_body/transform/generator.rs for more details.
800             ty::Generator(def_id, substs, _) => {
801                 let tys : Vec<_> = substs.as_generator().upvar_tys(def_id, self.tcx()).collect();
802                 self.open_drop_for_tuple(&tys)
803             }
804             ty::Tuple(..) => {
805                 let tys: Vec<_> = ty.tuple_fields().collect();
806                 self.open_drop_for_tuple(&tys)
807             }
808             ty::Adt(def, substs) => {
809                 if def.is_box() {
810                     self.open_drop_for_box(def, substs)
811                 } else {
812                     self.open_drop_for_adt(def, substs)
813                 }
814             }
815             ty::Dynamic(..) => {
816                 let unwind = self.unwind; // FIXME(#43234)
817                 let succ = self.succ;
818                 self.complete_drop(Some(DropFlagMode::Deep), succ, unwind)
819             }
820             ty::Array(ety, size) => {
821                 let size = size.try_eval_usize(self.tcx(), self.elaborator.param_env());
822                 self.open_drop_for_array(ety, size)
823             },
824             ty::Slice(ety) => self.open_drop_for_array(ety, None),
825
826             _ => bug!("open drop from non-ADT `{:?}`", ty)
827         }
828     }
829
830     /// Returns a basic block that drop a place using the context
831     /// and path in `c`. If `mode` is something, also clear `c`
832     /// according to it.
833     ///
834     /// if FLAG(self.path)
835     ///     if let Some(mode) = mode: FLAG(self.path)[mode] = false
836     ///     drop(self.place)
837     fn complete_drop(
838         &mut self,
839         drop_mode: Option<DropFlagMode>,
840         succ: BasicBlock,
841         unwind: Unwind,
842     ) -> BasicBlock {
843         debug!("complete_drop({:?},{:?})", self, drop_mode);
844
845         let drop_block = self.drop_block(succ, unwind);
846         let drop_block = if let Some(mode) = drop_mode {
847             self.drop_flag_reset_block(mode, drop_block, unwind)
848         } else {
849             drop_block
850         };
851
852         self.drop_flag_test_block(drop_block, succ, unwind)
853     }
854
855     fn drop_flag_reset_block(&mut self,
856                              mode: DropFlagMode,
857                              succ: BasicBlock,
858                              unwind: Unwind) -> BasicBlock
859     {
860         debug!("drop_flag_reset_block({:?},{:?})", self, mode);
861
862         let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
863         let block_start = Location { block: block, statement_index: 0 };
864         self.elaborator.clear_drop_flag(block_start, self.path, mode);
865         block
866     }
867
868     fn elaborated_drop_block(&mut self) -> BasicBlock {
869         debug!("elaborated_drop_block({:?})", self);
870         let unwind = self.unwind; // FIXME(#43234)
871         let succ = self.succ;
872         let blk = self.drop_block(succ, unwind);
873         self.elaborate_drop(blk);
874         blk
875     }
876
877     fn box_free_block(
878         &mut self,
879         adt: &'tcx ty::AdtDef,
880         substs: SubstsRef<'tcx>,
881         target: BasicBlock,
882         unwind: Unwind,
883     ) -> BasicBlock {
884         let block = self.unelaborated_free_block(adt, substs, target, unwind);
885         self.drop_flag_test_block(block, target, unwind)
886     }
887
888     fn unelaborated_free_block(
889         &mut self,
890         adt: &'tcx ty::AdtDef,
891         substs: SubstsRef<'tcx>,
892         target: BasicBlock,
893         unwind: Unwind,
894     ) -> BasicBlock {
895         let tcx = self.tcx();
896         let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
897         let free_func = tcx.require_lang_item(
898             lang_items::BoxFreeFnLangItem,
899             Some(self.source_info.span)
900         );
901         let args = adt.variants[VariantIdx::new(0)].fields.iter().enumerate().map(|(i, f)| {
902             let field = Field::new(i);
903             let field_ty = f.ty(self.tcx(), substs);
904             Operand::Move(self.place.clone().field(field, field_ty))
905         }).collect();
906
907         let call = TerminatorKind::Call {
908             func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
909             args: args,
910             destination: Some((unit_temp, target)),
911             cleanup: None,
912             from_hir_call: false,
913         }; // FIXME(#43234)
914         let free_block = self.new_block(unwind, call);
915
916         let block_start = Location { block: free_block, statement_index: 0 };
917         self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
918         free_block
919     }
920
921     fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
922         let block = TerminatorKind::Drop {
923             location: self.place.clone(),
924             target,
925             unwind: unwind.into_option()
926         };
927         self.new_block(unwind, block)
928     }
929
930     fn drop_flag_test_block(&mut self,
931                             on_set: BasicBlock,
932                             on_unset: BasicBlock,
933                             unwind: Unwind)
934                             -> BasicBlock
935     {
936         let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
937         debug!("drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
938                self, on_set, on_unset, unwind, style);
939
940         match style {
941             DropStyle::Dead => on_unset,
942             DropStyle::Static => on_set,
943             DropStyle::Conditional | DropStyle::Open => {
944                 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
945                 let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
946                 self.new_block(unwind, term)
947             }
948         }
949     }
950
951     fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
952         self.elaborator.patch().new_block(BasicBlockData {
953             statements: vec![],
954             terminator: Some(Terminator {
955                 source_info: self.source_info, kind: k
956             }),
957             is_cleanup: unwind.is_cleanup()
958         })
959     }
960
961     fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
962         self.elaborator.patch().new_temp(ty, self.source_info.span)
963     }
964
965     fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
966         let body = self.elaborator.body();
967         self.elaborator.patch().terminator_loc(body, bb)
968     }
969
970     fn constant_usize(&self, val: u16) -> Operand<'tcx> {
971         Operand::Constant(box Constant {
972             span: self.source_info.span,
973             user_ty: None,
974             literal: ty::Const::from_usize(self.tcx(), val.into()),
975         })
976     }
977
978     fn assign(&self, lhs: &Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
979         Statement {
980             source_info: self.source_info,
981             kind: StatementKind::Assign(box(lhs.clone(), rhs))
982         }
983     }
984 }