]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/block.rs
Rollup merge of #76825 - lcnr:array-windows-apply, r=varkor
[rust.git] / compiler / rustc_codegen_ssa / src / mir / block.rs
1 use super::operand::OperandRef;
2 use super::operand::OperandValue::{Immediate, Pair, Ref};
3 use super::place::PlaceRef;
4 use super::{FunctionCx, LocalRef};
5
6 use crate::base;
7 use crate::common::{self, IntPredicate};
8 use crate::meth;
9 use crate::traits::*;
10 use crate::MemFlags;
11
12 use rustc_ast as ast;
13 use rustc_hir::lang_items::LangItem;
14 use rustc_index::vec::Idx;
15 use rustc_middle::mir;
16 use rustc_middle::mir::interpret::{AllocId, ConstValue, Pointer, Scalar};
17 use rustc_middle::mir::AssertKind;
18 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
19 use rustc_middle::ty::print::with_no_trimmed_paths;
20 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
21 use rustc_span::source_map::Span;
22 use rustc_span::{sym, Symbol};
23 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
24 use rustc_target::abi::{self, LayoutOf};
25 use rustc_target::spec::abi::Abi;
26
27 use std::borrow::Cow;
28
29 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
30 /// e.g., creating a basic block, calling a function, etc.
31 struct TerminatorCodegenHelper<'tcx> {
32     bb: mir::BasicBlock,
33     terminator: &'tcx mir::Terminator<'tcx>,
34     funclet_bb: Option<mir::BasicBlock>,
35 }
36
37 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
38     /// Returns the associated funclet from `FunctionCx::funclets` for the
39     /// `funclet_bb` member if it is not `None`.
40     fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
41         &self,
42         fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
43     ) -> Option<&'b Bx::Funclet> {
44         match self.funclet_bb {
45             Some(funcl) => fx.funclets[funcl].as_ref(),
46             None => None,
47         }
48     }
49
50     fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
51         &self,
52         fx: &mut FunctionCx<'a, 'tcx, Bx>,
53         target: mir::BasicBlock,
54     ) -> (Bx::BasicBlock, bool) {
55         let span = self.terminator.source_info.span;
56         let lltarget = fx.blocks[target];
57         let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
58         match (self.funclet_bb, target_funclet) {
59             (None, None) => (lltarget, false),
60             (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) => {
61                 (lltarget, false)
62             }
63             // jump *into* cleanup - need a landing pad if GNU
64             (None, Some(_)) => (fx.landing_pad_to(target), false),
65             (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
66             (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
67         }
68     }
69
70     /// Create a basic block.
71     fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
72         &self,
73         fx: &mut FunctionCx<'a, 'tcx, Bx>,
74         target: mir::BasicBlock,
75     ) -> Bx::BasicBlock {
76         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
77         if is_cleanupret {
78             // MSVC cross-funclet jump - need a trampoline
79
80             debug!("llblock: creating cleanup trampoline for {:?}", target);
81             let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
82             let mut trampoline = fx.new_block(name);
83             trampoline.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
84             trampoline.llbb()
85         } else {
86             lltarget
87         }
88     }
89
90     fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
91         &self,
92         fx: &mut FunctionCx<'a, 'tcx, Bx>,
93         bx: &mut Bx,
94         target: mir::BasicBlock,
95     ) {
96         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
97         if is_cleanupret {
98             // micro-optimization: generate a `ret` rather than a jump
99             // to a trampoline.
100             bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
101         } else {
102             bx.br(lltarget);
103         }
104     }
105
106     /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
107     /// return destination `destination` and the cleanup function `cleanup`.
108     fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
109         &self,
110         fx: &mut FunctionCx<'a, 'tcx, Bx>,
111         bx: &mut Bx,
112         fn_abi: FnAbi<'tcx, Ty<'tcx>>,
113         fn_ptr: Bx::Value,
114         llargs: &[Bx::Value],
115         destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
116         cleanup: Option<mir::BasicBlock>,
117     ) {
118         // If there is a cleanup block and the function we're calling can unwind, then
119         // do an invoke, otherwise do a call.
120         if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
121             let ret_bx = if let Some((_, target)) = destination {
122                 fx.blocks[target]
123             } else {
124                 fx.unreachable_block()
125             };
126             let invokeret =
127                 bx.invoke(fn_ptr, &llargs, ret_bx, self.llblock(fx, cleanup), self.funclet(fx));
128             bx.apply_attrs_callsite(&fn_abi, invokeret);
129
130             if let Some((ret_dest, target)) = destination {
131                 let mut ret_bx = fx.build_block(target);
132                 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
133                 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
134             }
135         } else {
136             let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
137             bx.apply_attrs_callsite(&fn_abi, llret);
138             if fx.mir[self.bb].is_cleanup {
139                 // Cleanup is always the cold path. Don't inline
140                 // drop glue. Also, when there is a deeply-nested
141                 // struct, there are "symmetry" issues that cause
142                 // exponential inlining - see issue #41696.
143                 bx.do_not_inline(llret);
144             }
145
146             if let Some((ret_dest, target)) = destination {
147                 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
148                 self.funclet_br(fx, bx, target);
149             } else {
150                 bx.unreachable();
151             }
152         }
153     }
154
155     // Generate sideeffect intrinsic if jumping to any of the targets can form
156     // a loop.
157     fn maybe_sideeffect<Bx: BuilderMethods<'a, 'tcx>>(
158         &self,
159         mir: &'tcx mir::Body<'tcx>,
160         bx: &mut Bx,
161         targets: &[mir::BasicBlock],
162     ) {
163         if bx.tcx().sess.opts.debugging_opts.insert_sideeffect {
164             if targets.iter().any(|&target| {
165                 target <= self.bb
166                     && target.start_location().is_predecessor_of(self.bb.start_location(), mir)
167             }) {
168                 bx.sideeffect();
169             }
170         }
171     }
172 }
173
174 /// Codegen implementations for some terminator variants.
175 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
176     /// Generates code for a `Resume` terminator.
177     fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
178         if let Some(funclet) = helper.funclet(self) {
179             bx.cleanup_ret(funclet, None);
180         } else {
181             let slot = self.get_personality_slot(&mut bx);
182             let lp0 = slot.project_field(&mut bx, 0);
183             let lp0 = bx.load_operand(lp0).immediate();
184             let lp1 = slot.project_field(&mut bx, 1);
185             let lp1 = bx.load_operand(lp1).immediate();
186             slot.storage_dead(&mut bx);
187
188             let mut lp = bx.const_undef(self.landing_pad_type());
189             lp = bx.insert_value(lp, lp0, 0);
190             lp = bx.insert_value(lp, lp1, 1);
191             bx.resume(lp);
192         }
193     }
194
195     fn codegen_switchint_terminator(
196         &mut self,
197         helper: TerminatorCodegenHelper<'tcx>,
198         mut bx: Bx,
199         discr: &mir::Operand<'tcx>,
200         switch_ty: Ty<'tcx>,
201         values: &Cow<'tcx, [u128]>,
202         targets: &Vec<mir::BasicBlock>,
203     ) {
204         let discr = self.codegen_operand(&mut bx, &discr);
205         // `switch_ty` is redundant, sanity-check that.
206         assert_eq!(discr.layout.ty, switch_ty);
207         if targets.len() == 2 {
208             // If there are two targets, emit br instead of switch
209             let lltrue = helper.llblock(self, targets[0]);
210             let llfalse = helper.llblock(self, targets[1]);
211             if switch_ty == bx.tcx().types.bool {
212                 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
213                 // Don't generate trivial icmps when switching on bool
214                 if let [0] = values[..] {
215                     bx.cond_br(discr.immediate(), llfalse, lltrue);
216                 } else {
217                     assert_eq!(&values[..], &[1]);
218                     bx.cond_br(discr.immediate(), lltrue, llfalse);
219                 }
220             } else {
221                 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
222                 let llval = bx.const_uint_big(switch_llty, values[0]);
223                 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
224                 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
225                 bx.cond_br(cmp, lltrue, llfalse);
226             }
227         } else {
228             helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
229             let (otherwise, targets) = targets.split_last().unwrap();
230             bx.switch(
231                 discr.immediate(),
232                 helper.llblock(self, *otherwise),
233                 values
234                     .iter()
235                     .zip(targets)
236                     .map(|(&value, target)| (value, helper.llblock(self, *target))),
237             );
238         }
239     }
240
241     fn codegen_return_terminator(&mut self, mut bx: Bx) {
242         // Call `va_end` if this is the definition of a C-variadic function.
243         if self.fn_abi.c_variadic {
244             // The `VaList` "spoofed" argument is just after all the real arguments.
245             let va_list_arg_idx = self.fn_abi.args.len();
246             match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
247                 LocalRef::Place(va_list) => {
248                     bx.va_end(va_list.llval);
249                 }
250                 _ => bug!("C-variadic function must have a `VaList` place"),
251             }
252         }
253         if self.fn_abi.ret.layout.abi.is_uninhabited() {
254             // Functions with uninhabited return values are marked `noreturn`,
255             // so we should make sure that we never actually do.
256             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
257             // if that turns out to be helpful.
258             bx.abort();
259             // `abort` does not terminate the block, so we still need to generate
260             // an `unreachable` terminator after it.
261             bx.unreachable();
262             return;
263         }
264         let llval = match self.fn_abi.ret.mode {
265             PassMode::Ignore | PassMode::Indirect(..) => {
266                 bx.ret_void();
267                 return;
268             }
269
270             PassMode::Direct(_) | PassMode::Pair(..) => {
271                 let op = self.codegen_consume(&mut bx, mir::Place::return_place().as_ref());
272                 if let Ref(llval, _, align) = op.val {
273                     bx.load(llval, align)
274                 } else {
275                     op.immediate_or_packed_pair(&mut bx)
276                 }
277             }
278
279             PassMode::Cast(cast_ty) => {
280                 let op = match self.locals[mir::RETURN_PLACE] {
281                     LocalRef::Operand(Some(op)) => op,
282                     LocalRef::Operand(None) => bug!("use of return before def"),
283                     LocalRef::Place(cg_place) => OperandRef {
284                         val: Ref(cg_place.llval, None, cg_place.align),
285                         layout: cg_place.layout,
286                     },
287                     LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
288                 };
289                 let llslot = match op.val {
290                     Immediate(_) | Pair(..) => {
291                         let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
292                         op.val.store(&mut bx, scratch);
293                         scratch.llval
294                     }
295                     Ref(llval, _, align) => {
296                         assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
297                         llval
298                     }
299                 };
300                 let addr = bx.pointercast(llslot, bx.type_ptr_to(bx.cast_backend_type(&cast_ty)));
301                 bx.load(addr, self.fn_abi.ret.layout.align.abi)
302             }
303         };
304         bx.ret(llval);
305     }
306
307     fn codegen_drop_terminator(
308         &mut self,
309         helper: TerminatorCodegenHelper<'tcx>,
310         mut bx: Bx,
311         location: mir::Place<'tcx>,
312         target: mir::BasicBlock,
313         unwind: Option<mir::BasicBlock>,
314     ) {
315         let ty = location.ty(self.mir, bx.tcx()).ty;
316         let ty = self.monomorphize(&ty);
317         let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
318
319         if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
320             // we don't actually need to drop anything.
321             helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
322             helper.funclet_br(self, &mut bx, target);
323             return;
324         }
325
326         let place = self.codegen_place(&mut bx, location.as_ref());
327         let (args1, args2);
328         let mut args = if let Some(llextra) = place.llextra {
329             args2 = [place.llval, llextra];
330             &args2[..]
331         } else {
332             args1 = [place.llval];
333             &args1[..]
334         };
335         let (drop_fn, fn_abi) = match ty.kind() {
336             // FIXME(eddyb) perhaps move some of this logic into
337             // `Instance::resolve_drop_in_place`?
338             ty::Dynamic(..) => {
339                 let virtual_drop = Instance {
340                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
341                     substs: drop_fn.substs,
342                 };
343                 let fn_abi = FnAbi::of_instance(&bx, virtual_drop, &[]);
344                 let vtable = args[1];
345                 args = &args[..1];
346                 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
347             }
348             _ => (bx.get_fn_addr(drop_fn), FnAbi::of_instance(&bx, drop_fn, &[])),
349         };
350         helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
351         helper.do_call(
352             self,
353             &mut bx,
354             fn_abi,
355             drop_fn,
356             args,
357             Some((ReturnDest::Nothing, target)),
358             unwind,
359         );
360     }
361
362     fn codegen_assert_terminator(
363         &mut self,
364         helper: TerminatorCodegenHelper<'tcx>,
365         mut bx: Bx,
366         terminator: &mir::Terminator<'tcx>,
367         cond: &mir::Operand<'tcx>,
368         expected: bool,
369         msg: &mir::AssertMessage<'tcx>,
370         target: mir::BasicBlock,
371         cleanup: Option<mir::BasicBlock>,
372     ) {
373         let span = terminator.source_info.span;
374         let cond = self.codegen_operand(&mut bx, cond).immediate();
375         let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
376
377         // This case can currently arise only from functions marked
378         // with #[rustc_inherit_overflow_checks] and inlined from
379         // another crate (mostly core::num generic/#[inline] fns),
380         // while the current crate doesn't use overflow checks.
381         // NOTE: Unlike binops, negation doesn't have its own
382         // checked operation, just a comparison with the minimum
383         // value, so we have to check for the assert message.
384         if !bx.check_overflow() {
385             if let AssertKind::OverflowNeg(_) = *msg {
386                 const_cond = Some(expected);
387             }
388         }
389
390         // Don't codegen the panic block if success if known.
391         if const_cond == Some(expected) {
392             helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
393             helper.funclet_br(self, &mut bx, target);
394             return;
395         }
396
397         // Pass the condition through llvm.expect for branch hinting.
398         let cond = bx.expect(cond, expected);
399
400         // Create the failure block and the conditional branch to it.
401         let lltarget = helper.llblock(self, target);
402         let panic_block = self.new_block("panic");
403         helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
404         if expected {
405             bx.cond_br(cond, lltarget, panic_block.llbb());
406         } else {
407             bx.cond_br(cond, panic_block.llbb(), lltarget);
408         }
409
410         // After this point, bx is the block for the call to panic.
411         bx = panic_block;
412         self.set_debug_loc(&mut bx, terminator.source_info);
413
414         // Get the location information.
415         let location = self.get_caller_location(&mut bx, span).immediate();
416
417         // Put together the arguments to the panic entry point.
418         let (lang_item, args) = match msg {
419             AssertKind::BoundsCheck { ref len, ref index } => {
420                 let len = self.codegen_operand(&mut bx, len).immediate();
421                 let index = self.codegen_operand(&mut bx, index).immediate();
422                 // It's `fn panic_bounds_check(index: usize, len: usize)`,
423                 // and `#[track_caller]` adds an implicit third argument.
424                 (LangItem::PanicBoundsCheck, vec![index, len, location])
425             }
426             _ => {
427                 let msg_str = Symbol::intern(msg.description());
428                 let msg = bx.const_str(msg_str);
429                 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
430                 // as two arguments, and `#[track_caller]` adds an implicit third argument.
431                 (LangItem::Panic, vec![msg.0, msg.1, location])
432             }
433         };
434
435         // Obtain the panic entry point.
436         let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
437         let instance = ty::Instance::mono(bx.tcx(), def_id);
438         let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
439         let llfn = bx.get_fn_addr(instance);
440
441         // Codegen the actual panic invoke/call.
442         helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
443     }
444
445     /// Returns `true` if this is indeed a panic intrinsic and codegen is done.
446     fn codegen_panic_intrinsic(
447         &mut self,
448         helper: &TerminatorCodegenHelper<'tcx>,
449         bx: &mut Bx,
450         intrinsic: Option<Symbol>,
451         instance: Option<Instance<'tcx>>,
452         span: Span,
453         destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
454         cleanup: Option<mir::BasicBlock>,
455     ) -> bool {
456         // Emit a panic or a no-op for `assert_*` intrinsics.
457         // These are intrinsics that compile to panics so that we can get a message
458         // which mentions the offending type, even from a const context.
459         #[derive(Debug, PartialEq)]
460         enum AssertIntrinsic {
461             Inhabited,
462             ZeroValid,
463             UninitValid,
464         };
465         let panic_intrinsic = intrinsic.and_then(|i| match i {
466             sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
467             sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
468             sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
469             _ => None,
470         });
471         if let Some(intrinsic) = panic_intrinsic {
472             use AssertIntrinsic::*;
473             let ty = instance.unwrap().substs.type_at(0);
474             let layout = bx.layout_of(ty);
475             let do_panic = match intrinsic {
476                 Inhabited => layout.abi.is_uninhabited(),
477                 // We unwrap as the error type is `!`.
478                 ZeroValid => !layout.might_permit_raw_init(bx, /*zero:*/ true).unwrap(),
479                 // We unwrap as the error type is `!`.
480                 UninitValid => !layout.might_permit_raw_init(bx, /*zero:*/ false).unwrap(),
481             };
482             if do_panic {
483                 let msg_str = with_no_trimmed_paths(|| {
484                     if layout.abi.is_uninhabited() {
485                         // Use this error even for the other intrinsics as it is more precise.
486                         format!("attempted to instantiate uninhabited type `{}`", ty)
487                     } else if intrinsic == ZeroValid {
488                         format!("attempted to zero-initialize type `{}`, which is invalid", ty)
489                     } else {
490                         format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
491                     }
492                 });
493                 let msg = bx.const_str(Symbol::intern(&msg_str));
494                 let location = self.get_caller_location(bx, span).immediate();
495
496                 // Obtain the panic entry point.
497                 // FIXME: dedup this with `codegen_assert_terminator` above.
498                 let def_id = common::langcall(bx.tcx(), Some(span), "", LangItem::Panic);
499                 let instance = ty::Instance::mono(bx.tcx(), def_id);
500                 let fn_abi = FnAbi::of_instance(bx, instance, &[]);
501                 let llfn = bx.get_fn_addr(instance);
502
503                 if let Some((_, target)) = destination.as_ref() {
504                     helper.maybe_sideeffect(self.mir, bx, &[*target]);
505                 }
506                 // Codegen the actual panic invoke/call.
507                 helper.do_call(
508                     self,
509                     bx,
510                     fn_abi,
511                     llfn,
512                     &[msg.0, msg.1, location],
513                     destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
514                     cleanup,
515                 );
516             } else {
517                 // a NOP
518                 let target = destination.as_ref().unwrap().1;
519                 helper.maybe_sideeffect(self.mir, bx, &[target]);
520                 helper.funclet_br(self, bx, target)
521             }
522             true
523         } else {
524             false
525         }
526     }
527
528     fn codegen_call_terminator(
529         &mut self,
530         helper: TerminatorCodegenHelper<'tcx>,
531         mut bx: Bx,
532         terminator: &mir::Terminator<'tcx>,
533         func: &mir::Operand<'tcx>,
534         args: &Vec<mir::Operand<'tcx>>,
535         destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
536         cleanup: Option<mir::BasicBlock>,
537         fn_span: Span,
538     ) {
539         let span = terminator.source_info.span;
540         // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
541         let callee = self.codegen_operand(&mut bx, func);
542
543         let (instance, mut llfn) = match *callee.layout.ty.kind() {
544             ty::FnDef(def_id, substs) => (
545                 Some(
546                     ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
547                         .unwrap()
548                         .unwrap()
549                         .polymorphize(bx.tcx()),
550                 ),
551                 None,
552             ),
553             ty::FnPtr(_) => (None, Some(callee.immediate())),
554             _ => bug!("{} is not callable", callee.layout.ty),
555         };
556         let def = instance.map(|i| i.def);
557
558         if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
559             // Empty drop glue; a no-op.
560             let &(_, target) = destination.as_ref().unwrap();
561             helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
562             helper.funclet_br(self, &mut bx, target);
563             return;
564         }
565
566         // FIXME(eddyb) avoid computing this if possible, when `instance` is
567         // available - right now `sig` is only needed for getting the `abi`
568         // and figuring out how many extra args were passed to a C-variadic `fn`.
569         let sig = callee.layout.ty.fn_sig(bx.tcx());
570         let abi = sig.abi();
571
572         // Handle intrinsics old codegen wants Expr's for, ourselves.
573         let intrinsic = match def {
574             Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
575             _ => None,
576         };
577
578         let extra_args = &args[sig.inputs().skip_binder().len()..];
579         let extra_args = extra_args
580             .iter()
581             .map(|op_arg| {
582                 let op_ty = op_arg.ty(self.mir, bx.tcx());
583                 self.monomorphize(&op_ty)
584             })
585             .collect::<Vec<_>>();
586
587         let fn_abi = match instance {
588             Some(instance) => FnAbi::of_instance(&bx, instance, &extra_args),
589             None => FnAbi::of_fn_ptr(&bx, sig, &extra_args),
590         };
591
592         if intrinsic == Some(sym::transmute) {
593             if let Some(destination_ref) = destination.as_ref() {
594                 let &(dest, target) = destination_ref;
595                 self.codegen_transmute(&mut bx, &args[0], dest);
596                 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
597                 helper.funclet_br(self, &mut bx, target);
598             } else {
599                 // If we are trying to transmute to an uninhabited type,
600                 // it is likely there is no allotted destination. In fact,
601                 // transmuting to an uninhabited type is UB, which means
602                 // we can do what we like. Here, we declare that transmuting
603                 // into an uninhabited type is impossible, so anything following
604                 // it must be unreachable.
605                 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
606                 bx.unreachable();
607             }
608             return;
609         }
610
611         if self.codegen_panic_intrinsic(
612             &helper,
613             &mut bx,
614             intrinsic,
615             instance,
616             span,
617             destination,
618             cleanup,
619         ) {
620             return;
621         }
622
623         // The arguments we'll be passing. Plus one to account for outptr, if used.
624         let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
625         let mut llargs = Vec::with_capacity(arg_count);
626
627         // Prepare the return value destination
628         let ret_dest = if let Some((dest, _)) = *destination {
629             let is_intrinsic = intrinsic.is_some();
630             self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs, is_intrinsic)
631         } else {
632             ReturnDest::Nothing
633         };
634
635         if intrinsic == Some(sym::caller_location) {
636             if let Some((_, target)) = destination.as_ref() {
637                 let location = self.get_caller_location(&mut bx, fn_span);
638
639                 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
640                     location.val.store(&mut bx, tmp);
641                 }
642                 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
643
644                 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
645                 helper.funclet_br(self, &mut bx, *target);
646             }
647             return;
648         }
649
650         if intrinsic.is_some() && intrinsic != Some(sym::drop_in_place) {
651             let intrinsic = intrinsic.unwrap();
652             let dest = match ret_dest {
653                 _ if fn_abi.ret.is_indirect() => llargs[0],
654                 ReturnDest::Nothing => {
655                     bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
656                 }
657                 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
658                 ReturnDest::DirectOperand(_) => {
659                     bug!("Cannot use direct operand with an intrinsic call")
660                 }
661             };
662
663             let args: Vec<_> = args
664                 .iter()
665                 .enumerate()
666                 .map(|(i, arg)| {
667                     // The indices passed to simd_shuffle* in the
668                     // third argument must be constant. This is
669                     // checked by const-qualification, which also
670                     // promotes any complex rvalues to constants.
671                     if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
672                         if let mir::Operand::Constant(constant) = arg {
673                             let c = self.eval_mir_constant(constant);
674                             let (llval, ty) = self.simd_shuffle_indices(
675                                 &bx,
676                                 constant.span,
677                                 constant.literal.ty,
678                                 c,
679                             );
680                             return OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) };
681                         } else {
682                             span_bug!(span, "shuffle indices must be constant");
683                         }
684                     }
685
686                     self.codegen_operand(&mut bx, arg)
687                 })
688                 .collect();
689
690             Self::codegen_intrinsic_call(
691                 &mut bx,
692                 *instance.as_ref().unwrap(),
693                 &fn_abi,
694                 &args,
695                 dest,
696                 terminator.source_info.span,
697             );
698
699             if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
700                 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
701             }
702
703             if let Some((_, target)) = *destination {
704                 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
705                 helper.funclet_br(self, &mut bx, target);
706             } else {
707                 bx.unreachable();
708             }
709
710             return;
711         }
712
713         // Split the rust-call tupled arguments off.
714         let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
715             let (tup, args) = args.split_last().unwrap();
716             (args, Some(tup))
717         } else {
718             (&args[..], None)
719         };
720
721         'make_args: for (i, arg) in first_args.iter().enumerate() {
722             let mut op = self.codegen_operand(&mut bx, arg);
723
724             if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
725                 if let Pair(..) = op.val {
726                     // In the case of Rc<Self>, we need to explicitly pass a
727                     // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
728                     // that is understood elsewhere in the compiler as a method on
729                     // `dyn Trait`.
730                     // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
731                     // we get a value of a built-in pointer type
732                     'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
733                         && !op.layout.ty.is_region_ptr()
734                     {
735                         for i in 0..op.layout.fields.count() {
736                             let field = op.extract_field(&mut bx, i);
737                             if !field.layout.is_zst() {
738                                 // we found the one non-zero-sized field that is allowed
739                                 // now find *its* non-zero-sized field, or stop if it's a
740                                 // pointer
741                                 op = field;
742                                 continue 'descend_newtypes;
743                             }
744                         }
745
746                         span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
747                     }
748
749                     // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
750                     // data pointer and vtable. Look up the method in the vtable, and pass
751                     // the data pointer as the first argument
752                     match op.val {
753                         Pair(data_ptr, meta) => {
754                             llfn = Some(
755                                 meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi),
756                             );
757                             llargs.push(data_ptr);
758                             continue 'make_args;
759                         }
760                         other => bug!("expected a Pair, got {:?}", other),
761                     }
762                 } else if let Ref(data_ptr, Some(meta), _) = op.val {
763                     // by-value dynamic dispatch
764                     llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi));
765                     llargs.push(data_ptr);
766                     continue;
767                 } else {
768                     span_bug!(span, "can't codegen a virtual call on {:?}", op);
769                 }
770             }
771
772             // The callee needs to own the argument memory if we pass it
773             // by-ref, so make a local copy of non-immediate constants.
774             match (arg, op.val) {
775                 (&mir::Operand::Copy(_), Ref(_, None, _))
776                 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
777                     let tmp = PlaceRef::alloca(&mut bx, op.layout);
778                     op.val.store(&mut bx, tmp);
779                     op.val = Ref(tmp.llval, None, tmp.align);
780                 }
781                 _ => {}
782             }
783
784             self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
785         }
786         if let Some(tup) = untuple {
787             self.codegen_arguments_untupled(
788                 &mut bx,
789                 tup,
790                 &mut llargs,
791                 &fn_abi.args[first_args.len()..],
792             )
793         }
794
795         let needs_location =
796             instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
797         if needs_location {
798             assert_eq!(
799                 fn_abi.args.len(),
800                 args.len() + 1,
801                 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
802             );
803             let location = self.get_caller_location(&mut bx, fn_span);
804             debug!(
805                 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
806                 terminator, location, fn_span
807             );
808
809             let last_arg = fn_abi.args.last().unwrap();
810             self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
811         }
812
813         let fn_ptr = match (llfn, instance) {
814             (Some(llfn), _) => llfn,
815             (None, Some(instance)) => bx.get_fn_addr(instance),
816             _ => span_bug!(span, "no llfn for call"),
817         };
818
819         if let Some((_, target)) = destination.as_ref() {
820             helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
821         }
822         helper.do_call(
823             self,
824             &mut bx,
825             fn_abi,
826             fn_ptr,
827             &llargs,
828             destination.as_ref().map(|&(_, target)| (ret_dest, target)),
829             cleanup,
830         );
831     }
832
833     fn codegen_asm_terminator(
834         &mut self,
835         helper: TerminatorCodegenHelper<'tcx>,
836         mut bx: Bx,
837         terminator: &mir::Terminator<'tcx>,
838         template: &[ast::InlineAsmTemplatePiece],
839         operands: &[mir::InlineAsmOperand<'tcx>],
840         options: ast::InlineAsmOptions,
841         line_spans: &[Span],
842         destination: Option<mir::BasicBlock>,
843     ) {
844         let span = terminator.source_info.span;
845
846         let operands: Vec<_> = operands
847             .iter()
848             .map(|op| match *op {
849                 mir::InlineAsmOperand::In { reg, ref value } => {
850                     let value = self.codegen_operand(&mut bx, value);
851                     InlineAsmOperandRef::In { reg, value }
852                 }
853                 mir::InlineAsmOperand::Out { reg, late, ref place } => {
854                     let place = place.map(|place| self.codegen_place(&mut bx, place.as_ref()));
855                     InlineAsmOperandRef::Out { reg, late, place }
856                 }
857                 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
858                     let in_value = self.codegen_operand(&mut bx, in_value);
859                     let out_place =
860                         out_place.map(|out_place| self.codegen_place(&mut bx, out_place.as_ref()));
861                     InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
862                 }
863                 mir::InlineAsmOperand::Const { ref value } => {
864                     if let mir::Operand::Constant(constant) = value {
865                         let const_value = self
866                             .eval_mir_constant(constant)
867                             .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
868                         let ty = constant.literal.ty;
869                         let size = bx.layout_of(ty).size;
870                         let scalar = match const_value {
871                             // Promoted constants are evaluated into a ByRef instead of a Scalar,
872                             // but we want the scalar value here.
873                             ConstValue::ByRef { alloc, offset } => {
874                                 let ptr = Pointer::new(AllocId(0), offset);
875                                 alloc
876                                     .read_scalar(&bx, ptr, size)
877                                     .and_then(|s| s.check_init())
878                                     .unwrap_or_else(|e| {
879                                         bx.tcx().sess.span_err(
880                                             span,
881                                             &format!("Could not evaluate asm const: {}", e),
882                                         );
883
884                                         // We are erroring out, just emit a dummy constant.
885                                         Scalar::from_u64(0)
886                                     })
887                             }
888                             _ => span_bug!(span, "expected ByRef for promoted asm const"),
889                         };
890                         let value = scalar.assert_bits(size);
891                         let string = match ty.kind() {
892                             ty::Uint(_) => value.to_string(),
893                             ty::Int(int_ty) => {
894                                 match int_ty.normalize(bx.tcx().sess.target.ptr_width) {
895                                     ast::IntTy::I8 => (value as i8).to_string(),
896                                     ast::IntTy::I16 => (value as i16).to_string(),
897                                     ast::IntTy::I32 => (value as i32).to_string(),
898                                     ast::IntTy::I64 => (value as i64).to_string(),
899                                     ast::IntTy::I128 => (value as i128).to_string(),
900                                     ast::IntTy::Isize => unreachable!(),
901                                 }
902                             }
903                             ty::Float(ast::FloatTy::F32) => {
904                                 f32::from_bits(value as u32).to_string()
905                             }
906                             ty::Float(ast::FloatTy::F64) => {
907                                 f64::from_bits(value as u64).to_string()
908                             }
909                             _ => span_bug!(span, "asm const has bad type {}", ty),
910                         };
911                         InlineAsmOperandRef::Const { string }
912                     } else {
913                         span_bug!(span, "asm const is not a constant");
914                     }
915                 }
916                 mir::InlineAsmOperand::SymFn { ref value } => {
917                     let literal = self.monomorphize(&value.literal);
918                     if let ty::FnDef(def_id, substs) = *literal.ty.kind() {
919                         let instance = ty::Instance::resolve_for_fn_ptr(
920                             bx.tcx(),
921                             ty::ParamEnv::reveal_all(),
922                             def_id,
923                             substs,
924                         )
925                         .unwrap();
926                         InlineAsmOperandRef::SymFn { instance }
927                     } else {
928                         span_bug!(span, "invalid type for asm sym (fn)");
929                     }
930                 }
931                 mir::InlineAsmOperand::SymStatic { def_id } => {
932                     InlineAsmOperandRef::SymStatic { def_id }
933                 }
934             })
935             .collect();
936
937         bx.codegen_inline_asm(template, &operands, options, line_spans);
938
939         if let Some(target) = destination {
940             helper.funclet_br(self, &mut bx, target);
941         } else {
942             bx.unreachable();
943         }
944     }
945 }
946
947 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
948     pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
949         let mut bx = self.build_block(bb);
950         let mir = self.mir;
951         let data = &mir[bb];
952
953         debug!("codegen_block({:?}={:?})", bb, data);
954
955         for statement in &data.statements {
956             bx = self.codegen_statement(bx, statement);
957         }
958
959         self.codegen_terminator(bx, bb, data.terminator());
960     }
961
962     fn codegen_terminator(
963         &mut self,
964         mut bx: Bx,
965         bb: mir::BasicBlock,
966         terminator: &'tcx mir::Terminator<'tcx>,
967     ) {
968         debug!("codegen_terminator: {:?}", terminator);
969
970         // Create the cleanup bundle, if needed.
971         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
972         let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
973
974         self.set_debug_loc(&mut bx, terminator.source_info);
975         match terminator.kind {
976             mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
977
978             mir::TerminatorKind::Abort => {
979                 bx.abort();
980                 // `abort` does not terminate the block, so we still need to generate
981                 // an `unreachable` terminator after it.
982                 bx.unreachable();
983             }
984
985             mir::TerminatorKind::Goto { target } => {
986                 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
987                 helper.funclet_br(self, &mut bx, target);
988             }
989
990             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
991                 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, values, targets);
992             }
993
994             mir::TerminatorKind::Return => {
995                 self.codegen_return_terminator(bx);
996             }
997
998             mir::TerminatorKind::Unreachable => {
999                 bx.unreachable();
1000             }
1001
1002             mir::TerminatorKind::Drop { place, target, unwind } => {
1003                 self.codegen_drop_terminator(helper, bx, place, target, unwind);
1004             }
1005
1006             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
1007                 self.codegen_assert_terminator(
1008                     helper, bx, terminator, cond, expected, msg, target, cleanup,
1009                 );
1010             }
1011
1012             mir::TerminatorKind::DropAndReplace { .. } => {
1013                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1014             }
1015
1016             mir::TerminatorKind::Call {
1017                 ref func,
1018                 ref args,
1019                 ref destination,
1020                 cleanup,
1021                 from_hir_call: _,
1022                 fn_span,
1023             } => {
1024                 self.codegen_call_terminator(
1025                     helper,
1026                     bx,
1027                     terminator,
1028                     func,
1029                     args,
1030                     destination,
1031                     cleanup,
1032                     fn_span,
1033                 );
1034             }
1035             mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1036                 bug!("generator ops in codegen")
1037             }
1038             mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1039                 bug!("borrowck false edges in codegen")
1040             }
1041
1042             mir::TerminatorKind::InlineAsm {
1043                 template,
1044                 ref operands,
1045                 options,
1046                 line_spans,
1047                 destination,
1048             } => {
1049                 self.codegen_asm_terminator(
1050                     helper,
1051                     bx,
1052                     terminator,
1053                     template,
1054                     operands,
1055                     options,
1056                     line_spans,
1057                     destination,
1058                 );
1059             }
1060         }
1061     }
1062
1063     fn codegen_argument(
1064         &mut self,
1065         bx: &mut Bx,
1066         op: OperandRef<'tcx, Bx::Value>,
1067         llargs: &mut Vec<Bx::Value>,
1068         arg: &ArgAbi<'tcx, Ty<'tcx>>,
1069     ) {
1070         // Fill padding with undef value, where applicable.
1071         if let Some(ty) = arg.pad {
1072             llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
1073         }
1074
1075         if arg.is_ignore() {
1076             return;
1077         }
1078
1079         if let PassMode::Pair(..) = arg.mode {
1080             match op.val {
1081                 Pair(a, b) => {
1082                     llargs.push(a);
1083                     llargs.push(b);
1084                     return;
1085                 }
1086                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1087             }
1088         } else if arg.is_unsized_indirect() {
1089             match op.val {
1090                 Ref(a, Some(b), _) => {
1091                     llargs.push(a);
1092                     llargs.push(b);
1093                     return;
1094                 }
1095                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1096             }
1097         }
1098
1099         // Force by-ref if we have to load through a cast pointer.
1100         let (mut llval, align, by_ref) = match op.val {
1101             Immediate(_) | Pair(..) => match arg.mode {
1102                 PassMode::Indirect(..) | PassMode::Cast(_) => {
1103                     let scratch = PlaceRef::alloca(bx, arg.layout);
1104                     op.val.store(bx, scratch);
1105                     (scratch.llval, scratch.align, true)
1106                 }
1107                 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1108             },
1109             Ref(llval, _, align) => {
1110                 if arg.is_indirect() && align < arg.layout.align.abi {
1111                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1112                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1113                     // have scary latent bugs around.
1114
1115                     let scratch = PlaceRef::alloca(bx, arg.layout);
1116                     base::memcpy_ty(
1117                         bx,
1118                         scratch.llval,
1119                         scratch.align,
1120                         llval,
1121                         align,
1122                         op.layout,
1123                         MemFlags::empty(),
1124                     );
1125                     (scratch.llval, scratch.align, true)
1126                 } else {
1127                     (llval, align, true)
1128                 }
1129             }
1130         };
1131
1132         if by_ref && !arg.is_indirect() {
1133             // Have to load the argument, maybe while casting it.
1134             if let PassMode::Cast(ty) = arg.mode {
1135                 let addr = bx.pointercast(llval, bx.type_ptr_to(bx.cast_backend_type(&ty)));
1136                 llval = bx.load(addr, align.min(arg.layout.align.abi));
1137             } else {
1138                 // We can't use `PlaceRef::load` here because the argument
1139                 // may have a type we don't treat as immediate, but the ABI
1140                 // used for this call is passing it by-value. In that case,
1141                 // the load would just produce `OperandValue::Ref` instead
1142                 // of the `OperandValue::Immediate` we need for the call.
1143                 llval = bx.load(llval, align);
1144                 if let abi::Abi::Scalar(ref scalar) = arg.layout.abi {
1145                     if scalar.is_bool() {
1146                         bx.range_metadata(llval, 0..2);
1147                     }
1148                 }
1149                 // We store bools as `i8` so we need to truncate to `i1`.
1150                 llval = bx.to_immediate(llval, arg.layout);
1151             }
1152         }
1153
1154         llargs.push(llval);
1155     }
1156
1157     fn codegen_arguments_untupled(
1158         &mut self,
1159         bx: &mut Bx,
1160         operand: &mir::Operand<'tcx>,
1161         llargs: &mut Vec<Bx::Value>,
1162         args: &[ArgAbi<'tcx, Ty<'tcx>>],
1163     ) {
1164         let tuple = self.codegen_operand(bx, operand);
1165
1166         // Handle both by-ref and immediate tuples.
1167         if let Ref(llval, None, align) = tuple.val {
1168             let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1169             for i in 0..tuple.layout.fields.count() {
1170                 let field_ptr = tuple_ptr.project_field(bx, i);
1171                 let field = bx.load_operand(field_ptr);
1172                 self.codegen_argument(bx, field, llargs, &args[i]);
1173             }
1174         } else if let Ref(_, Some(_), _) = tuple.val {
1175             bug!("closure arguments must be sized")
1176         } else {
1177             // If the tuple is immediate, the elements are as well.
1178             for i in 0..tuple.layout.fields.count() {
1179                 let op = tuple.extract_field(bx, i);
1180                 self.codegen_argument(bx, op, llargs, &args[i]);
1181             }
1182         }
1183     }
1184
1185     fn get_caller_location(&mut self, bx: &mut Bx, span: Span) -> OperandRef<'tcx, Bx::Value> {
1186         self.caller_location.unwrap_or_else(|| {
1187             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1188             let caller = bx.tcx().sess.source_map().lookup_char_pos(topmost.lo());
1189             let const_loc = bx.tcx().const_caller_location((
1190                 Symbol::intern(&caller.file.name.to_string()),
1191                 caller.line as u32,
1192                 caller.col_display as u32 + 1,
1193             ));
1194             OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1195         })
1196     }
1197
1198     fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1199         let cx = bx.cx();
1200         if let Some(slot) = self.personality_slot {
1201             slot
1202         } else {
1203             let layout = cx.layout_of(
1204                 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1205             );
1206             let slot = PlaceRef::alloca(bx, layout);
1207             self.personality_slot = Some(slot);
1208             slot
1209         }
1210     }
1211
1212     /// Returns the landing-pad wrapper around the given basic block.
1213     ///
1214     /// No-op in MSVC SEH scheme.
1215     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Bx::BasicBlock {
1216         if let Some(block) = self.landing_pads[target_bb] {
1217             return block;
1218         }
1219
1220         let block = self.blocks[target_bb];
1221         let landing_pad = self.landing_pad_uncached(block);
1222         self.landing_pads[target_bb] = Some(landing_pad);
1223         landing_pad
1224     }
1225
1226     fn landing_pad_uncached(&mut self, target_bb: Bx::BasicBlock) -> Bx::BasicBlock {
1227         if base::wants_msvc_seh(self.cx.sess()) {
1228             span_bug!(self.mir.span, "landing pad was not inserted?")
1229         }
1230
1231         let mut bx = self.new_block("cleanup");
1232
1233         let llpersonality = self.cx.eh_personality();
1234         let llretty = self.landing_pad_type();
1235         let lp = bx.landing_pad(llretty, llpersonality, 1);
1236         bx.set_cleanup(lp);
1237
1238         let slot = self.get_personality_slot(&mut bx);
1239         slot.storage_live(&mut bx);
1240         Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1241
1242         bx.br(target_bb);
1243         bx.llbb()
1244     }
1245
1246     fn landing_pad_type(&self) -> Bx::Type {
1247         let cx = self.cx;
1248         cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1249     }
1250
1251     fn unreachable_block(&mut self) -> Bx::BasicBlock {
1252         self.unreachable_block.unwrap_or_else(|| {
1253             let mut bx = self.new_block("unreachable");
1254             bx.unreachable();
1255             self.unreachable_block = Some(bx.llbb());
1256             bx.llbb()
1257         })
1258     }
1259
1260     pub fn new_block(&self, name: &str) -> Bx {
1261         Bx::new_block(self.cx, self.llfn, name)
1262     }
1263
1264     pub fn build_block(&self, bb: mir::BasicBlock) -> Bx {
1265         let mut bx = Bx::with_cx(self.cx);
1266         bx.position_at_end(self.blocks[bb]);
1267         bx
1268     }
1269
1270     fn make_return_dest(
1271         &mut self,
1272         bx: &mut Bx,
1273         dest: mir::Place<'tcx>,
1274         fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1275         llargs: &mut Vec<Bx::Value>,
1276         is_intrinsic: bool,
1277     ) -> ReturnDest<'tcx, Bx::Value> {
1278         // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1279         if fn_ret.is_ignore() {
1280             return ReturnDest::Nothing;
1281         }
1282         let dest = if let Some(index) = dest.as_local() {
1283             match self.locals[index] {
1284                 LocalRef::Place(dest) => dest,
1285                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1286                 LocalRef::Operand(None) => {
1287                     // Handle temporary places, specifically `Operand` ones, as
1288                     // they don't have `alloca`s.
1289                     return if fn_ret.is_indirect() {
1290                         // Odd, but possible, case, we have an operand temporary,
1291                         // but the calling convention has an indirect return.
1292                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1293                         tmp.storage_live(bx);
1294                         llargs.push(tmp.llval);
1295                         ReturnDest::IndirectOperand(tmp, index)
1296                     } else if is_intrinsic {
1297                         // Currently, intrinsics always need a location to store
1298                         // the result, so we create a temporary `alloca` for the
1299                         // result.
1300                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1301                         tmp.storage_live(bx);
1302                         ReturnDest::IndirectOperand(tmp, index)
1303                     } else {
1304                         ReturnDest::DirectOperand(index)
1305                     };
1306                 }
1307                 LocalRef::Operand(Some(_)) => {
1308                     bug!("place local already assigned to");
1309                 }
1310             }
1311         } else {
1312             self.codegen_place(
1313                 bx,
1314                 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1315             )
1316         };
1317         if fn_ret.is_indirect() {
1318             if dest.align < dest.layout.align.abi {
1319                 // Currently, MIR code generation does not create calls
1320                 // that store directly to fields of packed structs (in
1321                 // fact, the calls it creates write only to temps).
1322                 //
1323                 // If someone changes that, please update this code path
1324                 // to create a temporary.
1325                 span_bug!(self.mir.span, "can't directly store to unaligned value");
1326             }
1327             llargs.push(dest.llval);
1328             ReturnDest::Nothing
1329         } else {
1330             ReturnDest::Store(dest)
1331         }
1332     }
1333
1334     fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1335         if let Some(index) = dst.as_local() {
1336             match self.locals[index] {
1337                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1338                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1339                 LocalRef::Operand(None) => {
1340                     let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1341                     assert!(!dst_layout.ty.has_erasable_regions());
1342                     let place = PlaceRef::alloca(bx, dst_layout);
1343                     place.storage_live(bx);
1344                     self.codegen_transmute_into(bx, src, place);
1345                     let op = bx.load_operand(place);
1346                     place.storage_dead(bx);
1347                     self.locals[index] = LocalRef::Operand(Some(op));
1348                     self.debug_introduce_local(bx, index);
1349                 }
1350                 LocalRef::Operand(Some(op)) => {
1351                     assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1352                 }
1353             }
1354         } else {
1355             let dst = self.codegen_place(bx, dst.as_ref());
1356             self.codegen_transmute_into(bx, src, dst);
1357         }
1358     }
1359
1360     fn codegen_transmute_into(
1361         &mut self,
1362         bx: &mut Bx,
1363         src: &mir::Operand<'tcx>,
1364         dst: PlaceRef<'tcx, Bx::Value>,
1365     ) {
1366         let src = self.codegen_operand(bx, src);
1367         let llty = bx.backend_type(src.layout);
1368         let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1369         let align = src.layout.align.abi.min(dst.align);
1370         src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1371     }
1372
1373     // Stores the return value of a function call into it's final location.
1374     fn store_return(
1375         &mut self,
1376         bx: &mut Bx,
1377         dest: ReturnDest<'tcx, Bx::Value>,
1378         ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1379         llval: Bx::Value,
1380     ) {
1381         use self::ReturnDest::*;
1382
1383         match dest {
1384             Nothing => (),
1385             Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1386             IndirectOperand(tmp, index) => {
1387                 let op = bx.load_operand(tmp);
1388                 tmp.storage_dead(bx);
1389                 self.locals[index] = LocalRef::Operand(Some(op));
1390                 self.debug_introduce_local(bx, index);
1391             }
1392             DirectOperand(index) => {
1393                 // If there is a cast, we have to store and reload.
1394                 let op = if let PassMode::Cast(_) = ret_abi.mode {
1395                     let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1396                     tmp.storage_live(bx);
1397                     bx.store_arg(&ret_abi, llval, tmp);
1398                     let op = bx.load_operand(tmp);
1399                     tmp.storage_dead(bx);
1400                     op
1401                 } else {
1402                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1403                 };
1404                 self.locals[index] = LocalRef::Operand(Some(op));
1405                 self.debug_introduce_local(bx, index);
1406             }
1407         }
1408     }
1409 }
1410
1411 enum ReturnDest<'tcx, V> {
1412     // Do nothing; the return value is indirect or ignored.
1413     Nothing,
1414     // Store the return value to the pointer.
1415     Store(PlaceRef<'tcx, V>),
1416     // Store an indirect return value to an operand local place.
1417     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1418     // Store a direct return value to an operand local place.
1419     DirectOperand(mir::Local),
1420 }