]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/block.rs
Auto merge of #105220 - oli-obk:feeding, r=cjgillot
[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::{CachedLlbb, 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_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
14 use rustc_hir::lang_items::LangItem;
15 use rustc_index::vec::Idx;
16 use rustc_middle::mir::{self, AssertKind, SwitchTargets};
17 use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
18 use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
19 use rustc_middle::ty::{self, Instance, Ty, TypeVisitable};
20 use rustc_session::config::OptLevel;
21 use rustc_span::source_map::Span;
22 use rustc_span::{sym, Symbol};
23 use rustc_symbol_mangling::typeid::typeid_for_fnabi;
24 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode, Reg};
25 use rustc_target::abi::{self, HasDataLayout, WrappingRange};
26 use rustc_target::spec::abi::Abi;
27
28 // Indicates if we are in the middle of merging a BB's successor into it. This
29 // can happen when BB jumps directly to its successor and the successor has no
30 // other predecessors.
31 #[derive(Debug, PartialEq)]
32 enum MergingSucc {
33     False,
34     True,
35 }
36
37 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
38 /// e.g., creating a basic block, calling a function, etc.
39 struct TerminatorCodegenHelper<'tcx> {
40     bb: mir::BasicBlock,
41     terminator: &'tcx mir::Terminator<'tcx>,
42     funclet_bb: Option<mir::BasicBlock>,
43 }
44
45 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
46     /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
47     /// either already previously cached, or newly created, by `landing_pad_for`.
48     fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
49         &self,
50         fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
51     ) -> Option<&'b Bx::Funclet> {
52         let funclet_bb = self.funclet_bb?;
53         if base::wants_msvc_seh(fx.cx.tcx().sess) {
54             // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
55             // it has to be now. This may not seem necessary, as RPO should lead
56             // to all the unwind edges being visited (and so to `landing_pad_for`
57             // getting called for them), before building any of the blocks inside
58             // the funclet itself - however, if MIR contains edges that end up not
59             // being needed in the LLVM IR after monomorphization, the funclet may
60             // be unreachable, and we don't have yet a way to skip building it in
61             // such an eventuality (which may be a better solution than this).
62             if fx.funclets[funclet_bb].is_none() {
63                 fx.landing_pad_for(funclet_bb);
64             }
65
66             Some(
67                 fx.funclets[funclet_bb]
68                     .as_ref()
69                     .expect("landing_pad_for didn't also create funclets entry"),
70             )
71         } else {
72             None
73         }
74     }
75
76     /// Get a basic block (creating it if necessary), possibly with cleanup
77     /// stuff in it or next to it.
78     fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
79         &self,
80         fx: &mut FunctionCx<'a, 'tcx, Bx>,
81         target: mir::BasicBlock,
82     ) -> Bx::BasicBlock {
83         let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
84         let mut lltarget = fx.llbb(target);
85         if needs_landing_pad {
86             lltarget = fx.landing_pad_for(target);
87         }
88         if is_cleanupret {
89             // MSVC cross-funclet jump - need a trampoline
90             debug_assert!(base::wants_msvc_seh(fx.cx.tcx().sess));
91             debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
92             let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
93             let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
94             let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
95             trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
96             trampoline_llbb
97         } else {
98             lltarget
99         }
100     }
101
102     fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
103         &self,
104         fx: &mut FunctionCx<'a, 'tcx, Bx>,
105         target: mir::BasicBlock,
106     ) -> (bool, bool) {
107         let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
108         let (needs_landing_pad, is_cleanupret) = match (self.funclet_bb, target_funclet) {
109             (None, None) => (false, false),
110             (None, Some(_)) => (true, false),
111             (Some(_), None) => {
112                 let span = self.terminator.source_info.span;
113                 span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
114             }
115             (Some(f), Some(t_f)) => {
116                 if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) {
117                     (false, false)
118                 } else {
119                     (true, true)
120                 }
121             }
122         };
123         (needs_landing_pad, is_cleanupret)
124     }
125
126     fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
127         &self,
128         fx: &mut FunctionCx<'a, 'tcx, Bx>,
129         bx: &mut Bx,
130         target: mir::BasicBlock,
131         mergeable_succ: bool,
132     ) -> MergingSucc {
133         let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
134         if mergeable_succ && !needs_landing_pad && !is_cleanupret {
135             // We can merge the successor into this bb, so no need for a `br`.
136             MergingSucc::True
137         } else {
138             let mut lltarget = fx.llbb(target);
139             if needs_landing_pad {
140                 lltarget = fx.landing_pad_for(target);
141             }
142             if is_cleanupret {
143                 // micro-optimization: generate a `ret` rather than a jump
144                 // to a trampoline.
145                 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
146             } else {
147                 bx.br(lltarget);
148             }
149             MergingSucc::False
150         }
151     }
152
153     /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
154     /// return destination `destination` and the cleanup function `cleanup`.
155     fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
156         &self,
157         fx: &mut FunctionCx<'a, 'tcx, Bx>,
158         bx: &mut Bx,
159         fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
160         fn_ptr: Bx::Value,
161         llargs: &[Bx::Value],
162         destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
163         cleanup: Option<mir::BasicBlock>,
164         copied_constant_arguments: &[PlaceRef<'tcx, <Bx as BackendTypes>::Value>],
165         mergeable_succ: bool,
166     ) -> MergingSucc {
167         // If there is a cleanup block and the function we're calling can unwind, then
168         // do an invoke, otherwise do a call.
169         let fn_ty = bx.fn_decl_backend_type(&fn_abi);
170
171         let unwind_block = if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
172             Some(self.llbb_with_cleanup(fx, cleanup))
173         } else if fx.mir[self.bb].is_cleanup
174             && fn_abi.can_unwind
175             && !base::wants_msvc_seh(fx.cx.tcx().sess)
176         {
177             // Exception must not propagate out of the execution of a cleanup (doing so
178             // can cause undefined behaviour). We insert a double unwind guard for
179             // functions that can potentially unwind to protect against this.
180             //
181             // This is not necessary for SEH which does not use successive unwinding
182             // like Itanium EH. EH frames in SEH are different from normal function
183             // frames and SEH will abort automatically if an exception tries to
184             // propagate out from cleanup.
185             Some(fx.double_unwind_guard())
186         } else {
187             None
188         };
189
190         if let Some(unwind_block) = unwind_block {
191             let ret_llbb = if let Some((_, target)) = destination {
192                 fx.llbb(target)
193             } else {
194                 fx.unreachable_block()
195             };
196             let invokeret = bx.invoke(
197                 fn_ty,
198                 Some(&fn_abi),
199                 fn_ptr,
200                 &llargs,
201                 ret_llbb,
202                 unwind_block,
203                 self.funclet(fx),
204             );
205             if fx.mir[self.bb].is_cleanup {
206                 bx.do_not_inline(invokeret);
207             }
208
209             if let Some((ret_dest, target)) = destination {
210                 bx.switch_to_block(fx.llbb(target));
211                 fx.set_debug_loc(bx, self.terminator.source_info);
212                 for tmp in copied_constant_arguments {
213                     bx.lifetime_end(tmp.llval, tmp.layout.size);
214                 }
215                 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
216             }
217             MergingSucc::False
218         } else {
219             let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &llargs, self.funclet(fx));
220             if fx.mir[self.bb].is_cleanup {
221                 // Cleanup is always the cold path. Don't inline
222                 // drop glue. Also, when there is a deeply-nested
223                 // struct, there are "symmetry" issues that cause
224                 // exponential inlining - see issue #41696.
225                 bx.do_not_inline(llret);
226             }
227
228             if let Some((ret_dest, target)) = destination {
229                 for tmp in copied_constant_arguments {
230                     bx.lifetime_end(tmp.llval, tmp.layout.size);
231                 }
232                 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
233                 self.funclet_br(fx, bx, target, mergeable_succ)
234             } else {
235                 bx.unreachable();
236                 MergingSucc::False
237             }
238         }
239     }
240
241     /// Generates inline assembly with optional `destination` and `cleanup`.
242     fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
243         &self,
244         fx: &mut FunctionCx<'a, 'tcx, Bx>,
245         bx: &mut Bx,
246         template: &[InlineAsmTemplatePiece],
247         operands: &[InlineAsmOperandRef<'tcx, Bx>],
248         options: InlineAsmOptions,
249         line_spans: &[Span],
250         destination: Option<mir::BasicBlock>,
251         cleanup: Option<mir::BasicBlock>,
252         instance: Instance<'_>,
253         mergeable_succ: bool,
254     ) -> MergingSucc {
255         if let Some(cleanup) = cleanup {
256             let ret_llbb = if let Some(target) = destination {
257                 fx.llbb(target)
258             } else {
259                 fx.unreachable_block()
260             };
261
262             bx.codegen_inline_asm(
263                 template,
264                 &operands,
265                 options,
266                 line_spans,
267                 instance,
268                 Some((ret_llbb, self.llbb_with_cleanup(fx, cleanup), self.funclet(fx))),
269             );
270             MergingSucc::False
271         } else {
272             bx.codegen_inline_asm(template, &operands, options, line_spans, instance, None);
273
274             if let Some(target) = destination {
275                 self.funclet_br(fx, bx, target, mergeable_succ)
276             } else {
277                 bx.unreachable();
278                 MergingSucc::False
279             }
280         }
281     }
282 }
283
284 /// Codegen implementations for some terminator variants.
285 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
286     /// Generates code for a `Resume` terminator.
287     fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
288         if let Some(funclet) = helper.funclet(self) {
289             bx.cleanup_ret(funclet, None);
290         } else {
291             let slot = self.get_personality_slot(bx);
292             let lp0 = slot.project_field(bx, 0);
293             let lp0 = bx.load_operand(lp0).immediate();
294             let lp1 = slot.project_field(bx, 1);
295             let lp1 = bx.load_operand(lp1).immediate();
296             slot.storage_dead(bx);
297
298             let mut lp = bx.const_undef(self.landing_pad_type());
299             lp = bx.insert_value(lp, lp0, 0);
300             lp = bx.insert_value(lp, lp1, 1);
301             bx.resume(lp);
302         }
303     }
304
305     fn codegen_switchint_terminator(
306         &mut self,
307         helper: TerminatorCodegenHelper<'tcx>,
308         bx: &mut Bx,
309         discr: &mir::Operand<'tcx>,
310         switch_ty: Ty<'tcx>,
311         targets: &SwitchTargets,
312     ) {
313         let discr = self.codegen_operand(bx, &discr);
314         // `switch_ty` is redundant, sanity-check that.
315         assert_eq!(discr.layout.ty, switch_ty);
316         let mut target_iter = targets.iter();
317         if target_iter.len() == 1 {
318             // If there are two targets (one conditional, one fallback), emit `br` instead of
319             // `switch`.
320             let (test_value, target) = target_iter.next().unwrap();
321             let lltrue = helper.llbb_with_cleanup(self, target);
322             let llfalse = helper.llbb_with_cleanup(self, targets.otherwise());
323             if switch_ty == bx.tcx().types.bool {
324                 // Don't generate trivial icmps when switching on bool.
325                 match test_value {
326                     0 => bx.cond_br(discr.immediate(), llfalse, lltrue),
327                     1 => bx.cond_br(discr.immediate(), lltrue, llfalse),
328                     _ => bug!(),
329                 }
330             } else {
331                 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
332                 let llval = bx.const_uint_big(switch_llty, test_value);
333                 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
334                 bx.cond_br(cmp, lltrue, llfalse);
335             }
336         } else if self.cx.sess().opts.optimize == OptLevel::No
337             && target_iter.len() == 2
338             && self.mir[targets.otherwise()].is_empty_unreachable()
339         {
340             // In unoptimized builds, if there are two normal targets and the `otherwise` target is
341             // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
342             // BB, which will usually (but not always) be dead code.
343             //
344             // Why only in unoptimized builds?
345             // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
346             //   must fall back to the to the slower SelectionDAG isel. Therefore, using `br` gives
347             //   significant compile time speedups for unoptimized builds.
348             // - In optimized builds the above doesn't hold, and using `br` sometimes results in
349             //   worse generated code because LLVM can no longer tell that the value being switched
350             //   on can only have two values, e.g. 0 and 1.
351             //
352             let (test_value1, target1) = target_iter.next().unwrap();
353             let (_test_value2, target2) = target_iter.next().unwrap();
354             let ll1 = helper.llbb_with_cleanup(self, target1);
355             let ll2 = helper.llbb_with_cleanup(self, target2);
356             let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
357             let llval = bx.const_uint_big(switch_llty, test_value1);
358             let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
359             bx.cond_br(cmp, ll1, ll2);
360         } else {
361             bx.switch(
362                 discr.immediate(),
363                 helper.llbb_with_cleanup(self, targets.otherwise()),
364                 target_iter.map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
365             );
366         }
367     }
368
369     fn codegen_return_terminator(&mut self, bx: &mut Bx) {
370         // Call `va_end` if this is the definition of a C-variadic function.
371         if self.fn_abi.c_variadic {
372             // The `VaList` "spoofed" argument is just after all the real arguments.
373             let va_list_arg_idx = self.fn_abi.args.len();
374             match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
375                 LocalRef::Place(va_list) => {
376                     bx.va_end(va_list.llval);
377                 }
378                 _ => bug!("C-variadic function must have a `VaList` place"),
379             }
380         }
381         if self.fn_abi.ret.layout.abi.is_uninhabited() {
382             // Functions with uninhabited return values are marked `noreturn`,
383             // so we should make sure that we never actually do.
384             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
385             // if that turns out to be helpful.
386             bx.abort();
387             // `abort` does not terminate the block, so we still need to generate
388             // an `unreachable` terminator after it.
389             bx.unreachable();
390             return;
391         }
392         let llval = match &self.fn_abi.ret.mode {
393             PassMode::Ignore | PassMode::Indirect { .. } => {
394                 bx.ret_void();
395                 return;
396             }
397
398             PassMode::Direct(_) | PassMode::Pair(..) => {
399                 let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
400                 if let Ref(llval, _, align) = op.val {
401                     bx.load(bx.backend_type(op.layout), llval, align)
402                 } else {
403                     op.immediate_or_packed_pair(bx)
404                 }
405             }
406
407             PassMode::Cast(cast_ty, _) => {
408                 let op = match self.locals[mir::RETURN_PLACE] {
409                     LocalRef::Operand(Some(op)) => op,
410                     LocalRef::Operand(None) => bug!("use of return before def"),
411                     LocalRef::Place(cg_place) => OperandRef {
412                         val: Ref(cg_place.llval, None, cg_place.align),
413                         layout: cg_place.layout,
414                     },
415                     LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
416                 };
417                 let llslot = match op.val {
418                     Immediate(_) | Pair(..) => {
419                         let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
420                         op.val.store(bx, scratch);
421                         scratch.llval
422                     }
423                     Ref(llval, _, align) => {
424                         assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
425                         llval
426                     }
427                 };
428                 let ty = bx.cast_backend_type(cast_ty);
429                 let addr = bx.pointercast(llslot, bx.type_ptr_to(ty));
430                 bx.load(ty, addr, self.fn_abi.ret.layout.align.abi)
431             }
432         };
433         bx.ret(llval);
434     }
435
436     #[tracing::instrument(level = "trace", skip(self, helper, bx))]
437     fn codegen_drop_terminator(
438         &mut self,
439         helper: TerminatorCodegenHelper<'tcx>,
440         bx: &mut Bx,
441         location: mir::Place<'tcx>,
442         target: mir::BasicBlock,
443         unwind: Option<mir::BasicBlock>,
444         mergeable_succ: bool,
445     ) -> MergingSucc {
446         let ty = location.ty(self.mir, bx.tcx()).ty;
447         let ty = self.monomorphize(ty);
448         let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
449
450         if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
451             // we don't actually need to drop anything.
452             return helper.funclet_br(self, bx, target, mergeable_succ);
453         }
454
455         let place = self.codegen_place(bx, location.as_ref());
456         let (args1, args2);
457         let mut args = if let Some(llextra) = place.llextra {
458             args2 = [place.llval, llextra];
459             &args2[..]
460         } else {
461             args1 = [place.llval];
462             &args1[..]
463         };
464         let (drop_fn, fn_abi) = match ty.kind() {
465             // FIXME(eddyb) perhaps move some of this logic into
466             // `Instance::resolve_drop_in_place`?
467             ty::Dynamic(_, _, ty::Dyn) => {
468                 // IN THIS ARM, WE HAVE:
469                 // ty = *mut (dyn Trait)
470                 // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
471                 //                       args[0]    args[1]
472                 //
473                 // args = ( Data, Vtable )
474                 //                  |
475                 //                  v
476                 //                /-------\
477                 //                | ...   |
478                 //                \-------/
479                 //
480                 let virtual_drop = Instance {
481                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
482                     substs: drop_fn.substs,
483                 };
484                 debug!("ty = {:?}", ty);
485                 debug!("drop_fn = {:?}", drop_fn);
486                 debug!("args = {:?}", args);
487                 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
488                 let vtable = args[1];
489                 // Truncate vtable off of args list
490                 args = &args[..1];
491                 (
492                     meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
493                         .get_fn(bx, vtable, ty, &fn_abi),
494                     fn_abi,
495                 )
496             }
497             ty::Dynamic(_, _, ty::DynStar) => {
498                 // IN THIS ARM, WE HAVE:
499                 // ty = *mut (dyn* Trait)
500                 // which is: *mut exists<T: sizeof(T) == sizeof(usize)> (T, Vtable<T: Trait>)
501                 //
502                 // args = [ * ]
503                 //          |
504                 //          v
505                 //      ( Data, Vtable )
506                 //                |
507                 //                v
508                 //              /-------\
509                 //              | ...   |
510                 //              \-------/
511                 //
512                 //
513                 // WE CAN CONVERT THIS INTO THE ABOVE LOGIC BY DOING
514                 //
515                 // data = &(*args[0]).0    // gives a pointer to Data above (really the same pointer)
516                 // vtable = (*args[0]).1   // loads the vtable out
517                 // (data, vtable)          // an equivalent Rust `*mut dyn Trait`
518                 //
519                 // SO THEN WE CAN USE THE ABOVE CODE.
520                 let virtual_drop = Instance {
521                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
522                     substs: drop_fn.substs,
523                 };
524                 debug!("ty = {:?}", ty);
525                 debug!("drop_fn = {:?}", drop_fn);
526                 debug!("args = {:?}", args);
527                 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
528                 let data = args[0];
529                 let data_ty = bx.cx().backend_type(place.layout);
530                 let vtable_ptr =
531                     bx.gep(data_ty, data, &[bx.cx().const_i32(0), bx.cx().const_i32(1)]);
532                 let vtable = bx.load(bx.type_i8p(), vtable_ptr, abi::Align::ONE);
533                 // Truncate vtable off of args list
534                 args = &args[..1];
535                 debug!("args' = {:?}", args);
536                 (
537                     meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
538                         .get_fn(bx, vtable, ty, &fn_abi),
539                     fn_abi,
540                 )
541             }
542             _ => (bx.get_fn_addr(drop_fn), bx.fn_abi_of_instance(drop_fn, ty::List::empty())),
543         };
544         helper.do_call(
545             self,
546             bx,
547             fn_abi,
548             drop_fn,
549             args,
550             Some((ReturnDest::Nothing, target)),
551             unwind,
552             &[],
553             mergeable_succ,
554         )
555     }
556
557     fn codegen_assert_terminator(
558         &mut self,
559         helper: TerminatorCodegenHelper<'tcx>,
560         bx: &mut Bx,
561         terminator: &mir::Terminator<'tcx>,
562         cond: &mir::Operand<'tcx>,
563         expected: bool,
564         msg: &mir::AssertMessage<'tcx>,
565         target: mir::BasicBlock,
566         cleanup: Option<mir::BasicBlock>,
567         mergeable_succ: bool,
568     ) -> MergingSucc {
569         let span = terminator.source_info.span;
570         let cond = self.codegen_operand(bx, cond).immediate();
571         let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
572
573         // This case can currently arise only from functions marked
574         // with #[rustc_inherit_overflow_checks] and inlined from
575         // another crate (mostly core::num generic/#[inline] fns),
576         // while the current crate doesn't use overflow checks.
577         // NOTE: Unlike binops, negation doesn't have its own
578         // checked operation, just a comparison with the minimum
579         // value, so we have to check for the assert message.
580         if !bx.check_overflow() {
581             if let AssertKind::OverflowNeg(_) = *msg {
582                 const_cond = Some(expected);
583             }
584         }
585
586         // Don't codegen the panic block if success if known.
587         if const_cond == Some(expected) {
588             return helper.funclet_br(self, bx, target, mergeable_succ);
589         }
590
591         // Pass the condition through llvm.expect for branch hinting.
592         let cond = bx.expect(cond, expected);
593
594         // Create the failure block and the conditional branch to it.
595         let lltarget = helper.llbb_with_cleanup(self, target);
596         let panic_block = bx.append_sibling_block("panic");
597         if expected {
598             bx.cond_br(cond, lltarget, panic_block);
599         } else {
600             bx.cond_br(cond, panic_block, lltarget);
601         }
602
603         // After this point, bx is the block for the call to panic.
604         bx.switch_to_block(panic_block);
605         self.set_debug_loc(bx, terminator.source_info);
606
607         // Get the location information.
608         let location = self.get_caller_location(bx, terminator.source_info).immediate();
609
610         // Put together the arguments to the panic entry point.
611         let (lang_item, args) = match msg {
612             AssertKind::BoundsCheck { ref len, ref index } => {
613                 let len = self.codegen_operand(bx, len).immediate();
614                 let index = self.codegen_operand(bx, index).immediate();
615                 // It's `fn panic_bounds_check(index: usize, len: usize)`,
616                 // and `#[track_caller]` adds an implicit third argument.
617                 (LangItem::PanicBoundsCheck, vec![index, len, location])
618             }
619             _ => {
620                 let msg = bx.const_str(msg.description());
621                 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
622                 // as two arguments, and `#[track_caller]` adds an implicit third argument.
623                 (LangItem::Panic, vec![msg.0, msg.1, location])
624             }
625         };
626
627         let (fn_abi, llfn) = common::build_langcall(bx, Some(span), lang_item);
628
629         // Codegen the actual panic invoke/call.
630         let merging_succ = helper.do_call(self, bx, fn_abi, llfn, &args, None, cleanup, &[], false);
631         assert_eq!(merging_succ, MergingSucc::False);
632         MergingSucc::False
633     }
634
635     fn codegen_abort_terminator(
636         &mut self,
637         helper: TerminatorCodegenHelper<'tcx>,
638         bx: &mut Bx,
639         terminator: &mir::Terminator<'tcx>,
640     ) {
641         let span = terminator.source_info.span;
642         self.set_debug_loc(bx, terminator.source_info);
643
644         // Obtain the panic entry point.
645         let (fn_abi, llfn) = common::build_langcall(bx, Some(span), LangItem::PanicNoUnwind);
646
647         // Codegen the actual panic invoke/call.
648         let merging_succ = helper.do_call(self, bx, fn_abi, llfn, &[], None, None, &[], false);
649         assert_eq!(merging_succ, MergingSucc::False);
650     }
651
652     /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
653     fn codegen_panic_intrinsic(
654         &mut self,
655         helper: &TerminatorCodegenHelper<'tcx>,
656         bx: &mut Bx,
657         intrinsic: Option<Symbol>,
658         instance: Option<Instance<'tcx>>,
659         source_info: mir::SourceInfo,
660         target: Option<mir::BasicBlock>,
661         cleanup: Option<mir::BasicBlock>,
662         mergeable_succ: bool,
663     ) -> Option<MergingSucc> {
664         // Emit a panic or a no-op for `assert_*` intrinsics.
665         // These are intrinsics that compile to panics so that we can get a message
666         // which mentions the offending type, even from a const context.
667         #[derive(Debug, PartialEq)]
668         enum AssertIntrinsic {
669             Inhabited,
670             ZeroValid,
671             UninitValid,
672         }
673         let panic_intrinsic = intrinsic.and_then(|i| match i {
674             sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
675             sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
676             sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
677             _ => None,
678         });
679         if let Some(intrinsic) = panic_intrinsic {
680             use AssertIntrinsic::*;
681
682             let ty = instance.unwrap().substs.type_at(0);
683             let layout = bx.layout_of(ty);
684             let do_panic = match intrinsic {
685                 Inhabited => layout.abi.is_uninhabited(),
686                 ZeroValid => !bx.tcx().permits_zero_init(layout),
687                 UninitValid => !bx.tcx().permits_uninit_init(layout),
688             };
689             Some(if do_panic {
690                 let msg_str = with_no_visible_paths!({
691                     with_no_trimmed_paths!({
692                         if layout.abi.is_uninhabited() {
693                             // Use this error even for the other intrinsics as it is more precise.
694                             format!("attempted to instantiate uninhabited type `{}`", ty)
695                         } else if intrinsic == ZeroValid {
696                             format!("attempted to zero-initialize type `{}`, which is invalid", ty)
697                         } else {
698                             format!(
699                                 "attempted to leave type `{}` uninitialized, which is invalid",
700                                 ty
701                             )
702                         }
703                     })
704                 });
705                 let msg = bx.const_str(&msg_str);
706                 let location = self.get_caller_location(bx, source_info).immediate();
707
708                 // Obtain the panic entry point.
709                 let (fn_abi, llfn) =
710                     common::build_langcall(bx, Some(source_info.span), LangItem::Panic);
711
712                 // Codegen the actual panic invoke/call.
713                 helper.do_call(
714                     self,
715                     bx,
716                     fn_abi,
717                     llfn,
718                     &[msg.0, msg.1, location],
719                     target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
720                     cleanup,
721                     &[],
722                     mergeable_succ,
723                 )
724             } else {
725                 // a NOP
726                 let target = target.unwrap();
727                 helper.funclet_br(self, bx, target, mergeable_succ)
728             })
729         } else {
730             None
731         }
732     }
733
734     fn codegen_call_terminator(
735         &mut self,
736         helper: TerminatorCodegenHelper<'tcx>,
737         bx: &mut Bx,
738         terminator: &mir::Terminator<'tcx>,
739         func: &mir::Operand<'tcx>,
740         args: &[mir::Operand<'tcx>],
741         destination: mir::Place<'tcx>,
742         target: Option<mir::BasicBlock>,
743         cleanup: Option<mir::BasicBlock>,
744         fn_span: Span,
745         mergeable_succ: bool,
746     ) -> MergingSucc {
747         let source_info = terminator.source_info;
748         let span = source_info.span;
749
750         // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
751         let callee = self.codegen_operand(bx, func);
752
753         let (instance, mut llfn) = match *callee.layout.ty.kind() {
754             ty::FnDef(def_id, substs) => (
755                 Some(
756                     ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
757                         .unwrap()
758                         .unwrap()
759                         .polymorphize(bx.tcx()),
760                 ),
761                 None,
762             ),
763             ty::FnPtr(_) => (None, Some(callee.immediate())),
764             _ => bug!("{} is not callable", callee.layout.ty),
765         };
766         let def = instance.map(|i| i.def);
767
768         if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
769             // Empty drop glue; a no-op.
770             let target = target.unwrap();
771             return helper.funclet_br(self, bx, target, mergeable_succ);
772         }
773
774         // FIXME(eddyb) avoid computing this if possible, when `instance` is
775         // available - right now `sig` is only needed for getting the `abi`
776         // and figuring out how many extra args were passed to a C-variadic `fn`.
777         let sig = callee.layout.ty.fn_sig(bx.tcx());
778         let abi = sig.abi();
779
780         // Handle intrinsics old codegen wants Expr's for, ourselves.
781         let intrinsic = match def {
782             Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
783             _ => None,
784         };
785
786         let extra_args = &args[sig.inputs().skip_binder().len()..];
787         let extra_args = bx.tcx().mk_type_list(extra_args.iter().map(|op_arg| {
788             let op_ty = op_arg.ty(self.mir, bx.tcx());
789             self.monomorphize(op_ty)
790         }));
791
792         let fn_abi = match instance {
793             Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
794             None => bx.fn_abi_of_fn_ptr(sig, extra_args),
795         };
796
797         if intrinsic == Some(sym::transmute) {
798             return if let Some(target) = target {
799                 self.codegen_transmute(bx, &args[0], destination);
800                 helper.funclet_br(self, bx, target, mergeable_succ)
801             } else {
802                 // If we are trying to transmute to an uninhabited type,
803                 // it is likely there is no allotted destination. In fact,
804                 // transmuting to an uninhabited type is UB, which means
805                 // we can do what we like. Here, we declare that transmuting
806                 // into an uninhabited type is impossible, so anything following
807                 // it must be unreachable.
808                 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
809                 bx.unreachable();
810                 MergingSucc::False
811             };
812         }
813
814         if let Some(merging_succ) = self.codegen_panic_intrinsic(
815             &helper,
816             bx,
817             intrinsic,
818             instance,
819             source_info,
820             target,
821             cleanup,
822             mergeable_succ,
823         ) {
824             return merging_succ;
825         }
826
827         // The arguments we'll be passing. Plus one to account for outptr, if used.
828         let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
829         let mut llargs = Vec::with_capacity(arg_count);
830
831         // Prepare the return value destination
832         let ret_dest = if target.is_some() {
833             let is_intrinsic = intrinsic.is_some();
834             self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs, is_intrinsic)
835         } else {
836             ReturnDest::Nothing
837         };
838
839         if intrinsic == Some(sym::caller_location) {
840             return if let Some(target) = target {
841                 let location =
842                     self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
843
844                 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
845                     location.val.store(bx, tmp);
846                 }
847                 self.store_return(bx, ret_dest, &fn_abi.ret, location.immediate());
848                 helper.funclet_br(self, bx, target, mergeable_succ)
849             } else {
850                 MergingSucc::False
851             };
852         }
853
854         match intrinsic {
855             None | Some(sym::drop_in_place) => {}
856             Some(sym::copy_nonoverlapping) => unreachable!(),
857             Some(intrinsic) => {
858                 let dest = match ret_dest {
859                     _ if fn_abi.ret.is_indirect() => llargs[0],
860                     ReturnDest::Nothing => {
861                         bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
862                     }
863                     ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
864                     ReturnDest::DirectOperand(_) => {
865                         bug!("Cannot use direct operand with an intrinsic call")
866                     }
867                 };
868
869                 let args: Vec<_> = args
870                     .iter()
871                     .enumerate()
872                     .map(|(i, arg)| {
873                         // The indices passed to simd_shuffle* in the
874                         // third argument must be constant. This is
875                         // checked by const-qualification, which also
876                         // promotes any complex rvalues to constants.
877                         if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
878                             if let mir::Operand::Constant(constant) = arg {
879                                 let c = self.eval_mir_constant(constant);
880                                 let (llval, ty) = self.simd_shuffle_indices(
881                                     &bx,
882                                     constant.span,
883                                     self.monomorphize(constant.ty()),
884                                     c,
885                                 );
886                                 return OperandRef {
887                                     val: Immediate(llval),
888                                     layout: bx.layout_of(ty),
889                                 };
890                             } else {
891                                 span_bug!(span, "shuffle indices must be constant");
892                             }
893                         }
894
895                         self.codegen_operand(bx, arg)
896                     })
897                     .collect();
898
899                 Self::codegen_intrinsic_call(
900                     bx,
901                     *instance.as_ref().unwrap(),
902                     &fn_abi,
903                     &args,
904                     dest,
905                     span,
906                 );
907
908                 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
909                     self.store_return(bx, ret_dest, &fn_abi.ret, dst.llval);
910                 }
911
912                 return if let Some(target) = target {
913                     helper.funclet_br(self, bx, target, mergeable_succ)
914                 } else {
915                     bx.unreachable();
916                     MergingSucc::False
917                 };
918             }
919         }
920
921         // Split the rust-call tupled arguments off.
922         let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
923             let (tup, args) = args.split_last().unwrap();
924             (args, Some(tup))
925         } else {
926             (args, None)
927         };
928
929         let mut copied_constant_arguments = vec![];
930         'make_args: for (i, arg) in first_args.iter().enumerate() {
931             let mut op = self.codegen_operand(bx, arg);
932
933             if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
934                 match op.val {
935                     Pair(data_ptr, meta) => {
936                         // In the case of Rc<Self>, we need to explicitly pass a
937                         // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
938                         // that is understood elsewhere in the compiler as a method on
939                         // `dyn Trait`.
940                         // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
941                         // we get a value of a built-in pointer type.
942                         //
943                         // This is also relevant for `Pin<&mut Self>`, where we need to peel the `Pin`.
944                         'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
945                             && !op.layout.ty.is_region_ptr()
946                         {
947                             for i in 0..op.layout.fields.count() {
948                                 let field = op.extract_field(bx, i);
949                                 if !field.layout.is_zst() {
950                                     // we found the one non-zero-sized field that is allowed
951                                     // now find *its* non-zero-sized field, or stop if it's a
952                                     // pointer
953                                     op = field;
954                                     continue 'descend_newtypes;
955                                 }
956                             }
957
958                             span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
959                         }
960
961                         // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
962                         // data pointer and vtable. Look up the method in the vtable, and pass
963                         // the data pointer as the first argument
964                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
965                             bx,
966                             meta,
967                             op.layout.ty,
968                             &fn_abi,
969                         ));
970                         llargs.push(data_ptr);
971                         continue 'make_args;
972                     }
973                     Ref(data_ptr, Some(meta), _) => {
974                         // by-value dynamic dispatch
975                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
976                             bx,
977                             meta,
978                             op.layout.ty,
979                             &fn_abi,
980                         ));
981                         llargs.push(data_ptr);
982                         continue;
983                     }
984                     Immediate(_) => {
985                         // See comment above explaining why we peel these newtypes
986                         'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
987                             && !op.layout.ty.is_region_ptr()
988                         {
989                             for i in 0..op.layout.fields.count() {
990                                 let field = op.extract_field(bx, i);
991                                 if !field.layout.is_zst() {
992                                     // we found the one non-zero-sized field that is allowed
993                                     // now find *its* non-zero-sized field, or stop if it's a
994                                     // pointer
995                                     op = field;
996                                     continue 'descend_newtypes;
997                                 }
998                             }
999
1000                             span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
1001                         }
1002
1003                         // Make sure that we've actually unwrapped the rcvr down
1004                         // to a pointer or ref to `dyn* Trait`.
1005                         if !op.layout.ty.builtin_deref(true).unwrap().ty.is_dyn_star() {
1006                             span_bug!(span, "can't codegen a virtual call on {:#?}", op);
1007                         }
1008                         let place = op.deref(bx.cx());
1009                         let data_ptr = place.project_field(bx, 0);
1010                         let meta_ptr = place.project_field(bx, 1);
1011                         let meta = bx.load_operand(meta_ptr);
1012                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1013                             bx,
1014                             meta.immediate(),
1015                             op.layout.ty,
1016                             &fn_abi,
1017                         ));
1018                         llargs.push(data_ptr.llval);
1019                         continue;
1020                     }
1021                     _ => {
1022                         span_bug!(span, "can't codegen a virtual call on {:#?}", op);
1023                     }
1024                 }
1025             }
1026
1027             // The callee needs to own the argument memory if we pass it
1028             // by-ref, so make a local copy of non-immediate constants.
1029             match (arg, op.val) {
1030                 (&mir::Operand::Copy(_), Ref(_, None, _))
1031                 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
1032                     let tmp = PlaceRef::alloca(bx, op.layout);
1033                     bx.lifetime_start(tmp.llval, tmp.layout.size);
1034                     op.val.store(bx, tmp);
1035                     op.val = Ref(tmp.llval, None, tmp.align);
1036                     copied_constant_arguments.push(tmp);
1037                 }
1038                 _ => {}
1039             }
1040
1041             self.codegen_argument(bx, op, &mut llargs, &fn_abi.args[i]);
1042         }
1043         let num_untupled = untuple.map(|tup| {
1044             self.codegen_arguments_untupled(bx, tup, &mut llargs, &fn_abi.args[first_args.len()..])
1045         });
1046
1047         let needs_location =
1048             instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
1049         if needs_location {
1050             let mir_args = if let Some(num_untupled) = num_untupled {
1051                 first_args.len() + num_untupled
1052             } else {
1053                 args.len()
1054             };
1055             assert_eq!(
1056                 fn_abi.args.len(),
1057                 mir_args + 1,
1058                 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {:?} {:?} {:?}",
1059                 instance,
1060                 fn_span,
1061                 fn_abi,
1062             );
1063             let location =
1064                 self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
1065             debug!(
1066                 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1067                 terminator, location, fn_span
1068             );
1069
1070             let last_arg = fn_abi.args.last().unwrap();
1071             self.codegen_argument(bx, location, &mut llargs, last_arg);
1072         }
1073
1074         let (is_indirect_call, fn_ptr) = match (llfn, instance) {
1075             (Some(llfn), _) => (true, llfn),
1076             (None, Some(instance)) => (false, bx.get_fn_addr(instance)),
1077             _ => span_bug!(span, "no llfn for call"),
1078         };
1079
1080         // For backends that support CFI using type membership (i.e., testing whether a given
1081         // pointer is associated with a type identifier).
1082         if bx.tcx().sess.is_sanitizer_cfi_enabled() && is_indirect_call {
1083             // Emit type metadata and checks.
1084             // FIXME(rcvalle): Add support for generalized identifiers.
1085             // FIXME(rcvalle): Create distinct unnamed MDNodes for internal identifiers.
1086             let typeid = typeid_for_fnabi(bx.tcx(), fn_abi);
1087             let typeid_metadata = self.cx.typeid_metadata(typeid);
1088
1089             // Test whether the function pointer is associated with the type identifier.
1090             let cond = bx.type_test(fn_ptr, typeid_metadata);
1091             let bb_pass = bx.append_sibling_block("type_test.pass");
1092             let bb_fail = bx.append_sibling_block("type_test.fail");
1093             bx.cond_br(cond, bb_pass, bb_fail);
1094
1095             bx.switch_to_block(bb_pass);
1096             let merging_succ = helper.do_call(
1097                 self,
1098                 bx,
1099                 fn_abi,
1100                 fn_ptr,
1101                 &llargs,
1102                 target.as_ref().map(|&target| (ret_dest, target)),
1103                 cleanup,
1104                 &copied_constant_arguments,
1105                 false,
1106             );
1107             assert_eq!(merging_succ, MergingSucc::False);
1108
1109             bx.switch_to_block(bb_fail);
1110             bx.abort();
1111             bx.unreachable();
1112
1113             return MergingSucc::False;
1114         }
1115
1116         helper.do_call(
1117             self,
1118             bx,
1119             fn_abi,
1120             fn_ptr,
1121             &llargs,
1122             target.as_ref().map(|&target| (ret_dest, target)),
1123             cleanup,
1124             &copied_constant_arguments,
1125             mergeable_succ,
1126         )
1127     }
1128
1129     fn codegen_asm_terminator(
1130         &mut self,
1131         helper: TerminatorCodegenHelper<'tcx>,
1132         bx: &mut Bx,
1133         terminator: &mir::Terminator<'tcx>,
1134         template: &[ast::InlineAsmTemplatePiece],
1135         operands: &[mir::InlineAsmOperand<'tcx>],
1136         options: ast::InlineAsmOptions,
1137         line_spans: &[Span],
1138         destination: Option<mir::BasicBlock>,
1139         cleanup: Option<mir::BasicBlock>,
1140         instance: Instance<'_>,
1141         mergeable_succ: bool,
1142     ) -> MergingSucc {
1143         let span = terminator.source_info.span;
1144
1145         let operands: Vec<_> = operands
1146             .iter()
1147             .map(|op| match *op {
1148                 mir::InlineAsmOperand::In { reg, ref value } => {
1149                     let value = self.codegen_operand(bx, value);
1150                     InlineAsmOperandRef::In { reg, value }
1151                 }
1152                 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1153                     let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1154                     InlineAsmOperandRef::Out { reg, late, place }
1155                 }
1156                 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1157                     let in_value = self.codegen_operand(bx, in_value);
1158                     let out_place =
1159                         out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1160                     InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1161                 }
1162                 mir::InlineAsmOperand::Const { ref value } => {
1163                     let const_value = self
1164                         .eval_mir_constant(value)
1165                         .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
1166                     let string = common::asm_const_to_str(
1167                         bx.tcx(),
1168                         span,
1169                         const_value,
1170                         bx.layout_of(value.ty()),
1171                     );
1172                     InlineAsmOperandRef::Const { string }
1173                 }
1174                 mir::InlineAsmOperand::SymFn { ref value } => {
1175                     let literal = self.monomorphize(value.literal);
1176                     if let ty::FnDef(def_id, substs) = *literal.ty().kind() {
1177                         let instance = ty::Instance::resolve_for_fn_ptr(
1178                             bx.tcx(),
1179                             ty::ParamEnv::reveal_all(),
1180                             def_id,
1181                             substs,
1182                         )
1183                         .unwrap();
1184                         InlineAsmOperandRef::SymFn { instance }
1185                     } else {
1186                         span_bug!(span, "invalid type for asm sym (fn)");
1187                     }
1188                 }
1189                 mir::InlineAsmOperand::SymStatic { def_id } => {
1190                     InlineAsmOperandRef::SymStatic { def_id }
1191                 }
1192             })
1193             .collect();
1194
1195         helper.do_inlineasm(
1196             self,
1197             bx,
1198             template,
1199             &operands,
1200             options,
1201             line_spans,
1202             destination,
1203             cleanup,
1204             instance,
1205             mergeable_succ,
1206         )
1207     }
1208 }
1209
1210 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1211     pub fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1212         let llbb = match self.try_llbb(bb) {
1213             Some(llbb) => llbb,
1214             None => return,
1215         };
1216         let bx = &mut Bx::build(self.cx, llbb);
1217         let mir = self.mir;
1218
1219         // MIR basic blocks stop at any function call. This may not be the case
1220         // for the backend's basic blocks, in which case we might be able to
1221         // combine multiple MIR basic blocks into a single backend basic block.
1222         loop {
1223             let data = &mir[bb];
1224
1225             debug!("codegen_block({:?}={:?})", bb, data);
1226
1227             for statement in &data.statements {
1228                 self.codegen_statement(bx, statement);
1229             }
1230
1231             let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1232             if let MergingSucc::False = merging_succ {
1233                 break;
1234             }
1235
1236             // We are merging the successor into the produced backend basic
1237             // block. Record that the successor should be skipped when it is
1238             // reached.
1239             //
1240             // Note: we must not have already generated code for the successor.
1241             // This is implicitly ensured by the reverse postorder traversal,
1242             // and the assertion explicitly guarantees that.
1243             let mut successors = data.terminator().successors();
1244             let succ = successors.next().unwrap();
1245             assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1246             self.cached_llbbs[succ] = CachedLlbb::Skip;
1247             bb = succ;
1248         }
1249     }
1250
1251     fn codegen_terminator(
1252         &mut self,
1253         bx: &mut Bx,
1254         bb: mir::BasicBlock,
1255         terminator: &'tcx mir::Terminator<'tcx>,
1256     ) -> MergingSucc {
1257         debug!("codegen_terminator: {:?}", terminator);
1258
1259         // Create the cleanup bundle, if needed.
1260         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
1261         let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
1262
1263         let mergeable_succ = || {
1264             // Note: any call to `switch_to_block` will invalidate a `true` value
1265             // of `mergeable_succ`.
1266             let mut successors = terminator.successors();
1267             if let Some(succ) = successors.next()
1268                 && successors.next().is_none()
1269                 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1270             {
1271                 // bb has a single successor, and bb is its only predecessor. This
1272                 // makes it a candidate for merging.
1273                 assert_eq!(succ_pred, bb);
1274                 true
1275             } else {
1276                 false
1277             }
1278         };
1279
1280         self.set_debug_loc(bx, terminator.source_info);
1281         match terminator.kind {
1282             mir::TerminatorKind::Resume => {
1283                 self.codegen_resume_terminator(helper, bx);
1284                 MergingSucc::False
1285             }
1286
1287             mir::TerminatorKind::Abort => {
1288                 self.codegen_abort_terminator(helper, bx, terminator);
1289                 MergingSucc::False
1290             }
1291
1292             mir::TerminatorKind::Goto { target } => {
1293                 helper.funclet_br(self, bx, target, mergeable_succ())
1294             }
1295
1296             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref targets } => {
1297                 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, targets);
1298                 MergingSucc::False
1299             }
1300
1301             mir::TerminatorKind::Return => {
1302                 self.codegen_return_terminator(bx);
1303                 MergingSucc::False
1304             }
1305
1306             mir::TerminatorKind::Unreachable => {
1307                 bx.unreachable();
1308                 MergingSucc::False
1309             }
1310
1311             mir::TerminatorKind::Drop { place, target, unwind } => {
1312                 self.codegen_drop_terminator(helper, bx, place, target, unwind, mergeable_succ())
1313             }
1314
1315             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => self
1316                 .codegen_assert_terminator(
1317                     helper,
1318                     bx,
1319                     terminator,
1320                     cond,
1321                     expected,
1322                     msg,
1323                     target,
1324                     cleanup,
1325                     mergeable_succ(),
1326                 ),
1327
1328             mir::TerminatorKind::DropAndReplace { .. } => {
1329                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1330             }
1331
1332             mir::TerminatorKind::Call {
1333                 ref func,
1334                 ref args,
1335                 destination,
1336                 target,
1337                 cleanup,
1338                 from_hir_call: _,
1339                 fn_span,
1340             } => self.codegen_call_terminator(
1341                 helper,
1342                 bx,
1343                 terminator,
1344                 func,
1345                 args,
1346                 destination,
1347                 target,
1348                 cleanup,
1349                 fn_span,
1350                 mergeable_succ(),
1351             ),
1352             mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1353                 bug!("generator ops in codegen")
1354             }
1355             mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1356                 bug!("borrowck false edges in codegen")
1357             }
1358
1359             mir::TerminatorKind::InlineAsm {
1360                 template,
1361                 ref operands,
1362                 options,
1363                 line_spans,
1364                 destination,
1365                 cleanup,
1366             } => self.codegen_asm_terminator(
1367                 helper,
1368                 bx,
1369                 terminator,
1370                 template,
1371                 operands,
1372                 options,
1373                 line_spans,
1374                 destination,
1375                 cleanup,
1376                 self.instance,
1377                 mergeable_succ(),
1378             ),
1379         }
1380     }
1381
1382     fn codegen_argument(
1383         &mut self,
1384         bx: &mut Bx,
1385         op: OperandRef<'tcx, Bx::Value>,
1386         llargs: &mut Vec<Bx::Value>,
1387         arg: &ArgAbi<'tcx, Ty<'tcx>>,
1388     ) {
1389         match arg.mode {
1390             PassMode::Ignore => return,
1391             PassMode::Cast(_, true) => {
1392                 // Fill padding with undef value, where applicable.
1393                 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1394             }
1395             PassMode::Pair(..) => match op.val {
1396                 Pair(a, b) => {
1397                     llargs.push(a);
1398                     llargs.push(b);
1399                     return;
1400                 }
1401                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1402             },
1403             PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => match op.val {
1404                 Ref(a, Some(b), _) => {
1405                     llargs.push(a);
1406                     llargs.push(b);
1407                     return;
1408                 }
1409                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1410             },
1411             _ => {}
1412         }
1413
1414         // Force by-ref if we have to load through a cast pointer.
1415         let (mut llval, align, by_ref) = match op.val {
1416             Immediate(_) | Pair(..) => match arg.mode {
1417                 PassMode::Indirect { .. } | PassMode::Cast(..) => {
1418                     let scratch = PlaceRef::alloca(bx, arg.layout);
1419                     op.val.store(bx, scratch);
1420                     (scratch.llval, scratch.align, true)
1421                 }
1422                 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1423             },
1424             Ref(llval, _, align) => {
1425                 if arg.is_indirect() && align < arg.layout.align.abi {
1426                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1427                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1428                     // have scary latent bugs around.
1429
1430                     let scratch = PlaceRef::alloca(bx, arg.layout);
1431                     base::memcpy_ty(
1432                         bx,
1433                         scratch.llval,
1434                         scratch.align,
1435                         llval,
1436                         align,
1437                         op.layout,
1438                         MemFlags::empty(),
1439                     );
1440                     (scratch.llval, scratch.align, true)
1441                 } else {
1442                     (llval, align, true)
1443                 }
1444             }
1445         };
1446
1447         if by_ref && !arg.is_indirect() {
1448             // Have to load the argument, maybe while casting it.
1449             if let PassMode::Cast(ty, _) = &arg.mode {
1450                 let llty = bx.cast_backend_type(ty);
1451                 let addr = bx.pointercast(llval, bx.type_ptr_to(llty));
1452                 llval = bx.load(llty, addr, align.min(arg.layout.align.abi));
1453             } else {
1454                 // We can't use `PlaceRef::load` here because the argument
1455                 // may have a type we don't treat as immediate, but the ABI
1456                 // used for this call is passing it by-value. In that case,
1457                 // the load would just produce `OperandValue::Ref` instead
1458                 // of the `OperandValue::Immediate` we need for the call.
1459                 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1460                 if let abi::Abi::Scalar(scalar) = arg.layout.abi {
1461                     if scalar.is_bool() {
1462                         bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1463                     }
1464                 }
1465                 // We store bools as `i8` so we need to truncate to `i1`.
1466                 llval = bx.to_immediate(llval, arg.layout);
1467             }
1468         }
1469
1470         llargs.push(llval);
1471     }
1472
1473     fn codegen_arguments_untupled(
1474         &mut self,
1475         bx: &mut Bx,
1476         operand: &mir::Operand<'tcx>,
1477         llargs: &mut Vec<Bx::Value>,
1478         args: &[ArgAbi<'tcx, Ty<'tcx>>],
1479     ) -> usize {
1480         let tuple = self.codegen_operand(bx, operand);
1481
1482         // Handle both by-ref and immediate tuples.
1483         if let Ref(llval, None, align) = tuple.val {
1484             let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1485             for i in 0..tuple.layout.fields.count() {
1486                 let field_ptr = tuple_ptr.project_field(bx, i);
1487                 let field = bx.load_operand(field_ptr);
1488                 self.codegen_argument(bx, field, llargs, &args[i]);
1489             }
1490         } else if let Ref(_, Some(_), _) = tuple.val {
1491             bug!("closure arguments must be sized")
1492         } else {
1493             // If the tuple is immediate, the elements are as well.
1494             for i in 0..tuple.layout.fields.count() {
1495                 let op = tuple.extract_field(bx, i);
1496                 self.codegen_argument(bx, op, llargs, &args[i]);
1497             }
1498         }
1499         tuple.layout.fields.count()
1500     }
1501
1502     fn get_caller_location(
1503         &mut self,
1504         bx: &mut Bx,
1505         mut source_info: mir::SourceInfo,
1506     ) -> OperandRef<'tcx, Bx::Value> {
1507         let tcx = bx.tcx();
1508
1509         let mut span_to_caller_location = |span: Span| {
1510             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1511             let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
1512             let const_loc = tcx.const_caller_location((
1513                 Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
1514                 caller.line as u32,
1515                 caller.col_display as u32 + 1,
1516             ));
1517             OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1518         };
1519
1520         // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
1521         // If so, the starting `source_info.span` is in the innermost inlined
1522         // function, and will be replaced with outer callsite spans as long
1523         // as the inlined functions were `#[track_caller]`.
1524         loop {
1525             let scope_data = &self.mir.source_scopes[source_info.scope];
1526
1527             if let Some((callee, callsite_span)) = scope_data.inlined {
1528                 // Stop inside the most nested non-`#[track_caller]` function,
1529                 // before ever reaching its caller (which is irrelevant).
1530                 if !callee.def.requires_caller_location(tcx) {
1531                     return span_to_caller_location(source_info.span);
1532                 }
1533                 source_info.span = callsite_span;
1534             }
1535
1536             // Skip past all of the parents with `inlined: None`.
1537             match scope_data.inlined_parent_scope {
1538                 Some(parent) => source_info.scope = parent,
1539                 None => break,
1540             }
1541         }
1542
1543         // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
1544         self.caller_location.unwrap_or_else(|| span_to_caller_location(source_info.span))
1545     }
1546
1547     fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1548         let cx = bx.cx();
1549         if let Some(slot) = self.personality_slot {
1550             slot
1551         } else {
1552             let layout = cx.layout_of(
1553                 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1554             );
1555             let slot = PlaceRef::alloca(bx, layout);
1556             self.personality_slot = Some(slot);
1557             slot
1558         }
1559     }
1560
1561     /// Returns the landing/cleanup pad wrapper around the given basic block.
1562     // FIXME(eddyb) rename this to `eh_pad_for`.
1563     fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1564         if let Some(landing_pad) = self.landing_pads[bb] {
1565             return landing_pad;
1566         }
1567
1568         let landing_pad = self.landing_pad_for_uncached(bb);
1569         self.landing_pads[bb] = Some(landing_pad);
1570         landing_pad
1571     }
1572
1573     // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1574     fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1575         let llbb = self.llbb(bb);
1576         if base::wants_msvc_seh(self.cx.sess()) {
1577             let funclet;
1578             let ret_llbb;
1579             match self.mir[bb].terminator.as_ref().map(|t| &t.kind) {
1580                 // This is a basic block that we're aborting the program for,
1581                 // notably in an `extern` function. These basic blocks are inserted
1582                 // so that we assert that `extern` functions do indeed not panic,
1583                 // and if they do we abort the process.
1584                 //
1585                 // On MSVC these are tricky though (where we're doing funclets). If
1586                 // we were to do a cleanuppad (like below) the normal functions like
1587                 // `longjmp` would trigger the abort logic, terminating the
1588                 // program. Instead we insert the equivalent of `catch(...)` for C++
1589                 // which magically doesn't trigger when `longjmp` files over this
1590                 // frame.
1591                 //
1592                 // Lots more discussion can be found on #48251 but this codegen is
1593                 // modeled after clang's for:
1594                 //
1595                 //      try {
1596                 //          foo();
1597                 //      } catch (...) {
1598                 //          bar();
1599                 //      }
1600                 Some(&mir::TerminatorKind::Abort) => {
1601                     let cs_llbb =
1602                         Bx::append_block(self.cx, self.llfn, &format!("cs_funclet{:?}", bb));
1603                     let cp_llbb =
1604                         Bx::append_block(self.cx, self.llfn, &format!("cp_funclet{:?}", bb));
1605                     ret_llbb = cs_llbb;
1606
1607                     let mut cs_bx = Bx::build(self.cx, cs_llbb);
1608                     let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1609
1610                     // The "null" here is actually a RTTI type descriptor for the
1611                     // C++ personality function, but `catch (...)` has no type so
1612                     // it's null. The 64 here is actually a bitfield which
1613                     // represents that this is a catch-all block.
1614                     let mut cp_bx = Bx::build(self.cx, cp_llbb);
1615                     let null = cp_bx.const_null(
1616                         cp_bx.type_i8p_ext(cp_bx.cx().data_layout().instruction_address_space),
1617                     );
1618                     let sixty_four = cp_bx.const_i32(64);
1619                     funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
1620                     cp_bx.br(llbb);
1621                 }
1622                 _ => {
1623                     let cleanup_llbb =
1624                         Bx::append_block(self.cx, self.llfn, &format!("funclet_{:?}", bb));
1625                     ret_llbb = cleanup_llbb;
1626                     let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1627                     funclet = cleanup_bx.cleanup_pad(None, &[]);
1628                     cleanup_bx.br(llbb);
1629                 }
1630             }
1631             self.funclets[bb] = Some(funclet);
1632             ret_llbb
1633         } else {
1634             let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1635             let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1636
1637             let llpersonality = self.cx.eh_personality();
1638             let llretty = self.landing_pad_type();
1639             let lp = cleanup_bx.cleanup_landing_pad(llretty, llpersonality);
1640
1641             let slot = self.get_personality_slot(&mut cleanup_bx);
1642             slot.storage_live(&mut cleanup_bx);
1643             Pair(cleanup_bx.extract_value(lp, 0), cleanup_bx.extract_value(lp, 1))
1644                 .store(&mut cleanup_bx, slot);
1645
1646             cleanup_bx.br(llbb);
1647             cleanup_llbb
1648         }
1649     }
1650
1651     fn landing_pad_type(&self) -> Bx::Type {
1652         let cx = self.cx;
1653         cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1654     }
1655
1656     fn unreachable_block(&mut self) -> Bx::BasicBlock {
1657         self.unreachable_block.unwrap_or_else(|| {
1658             let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1659             let mut bx = Bx::build(self.cx, llbb);
1660             bx.unreachable();
1661             self.unreachable_block = Some(llbb);
1662             llbb
1663         })
1664     }
1665
1666     fn double_unwind_guard(&mut self) -> Bx::BasicBlock {
1667         self.double_unwind_guard.unwrap_or_else(|| {
1668             assert!(!base::wants_msvc_seh(self.cx.sess()));
1669
1670             let llbb = Bx::append_block(self.cx, self.llfn, "abort");
1671             let mut bx = Bx::build(self.cx, llbb);
1672             self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1673
1674             let llpersonality = self.cx.eh_personality();
1675             let llretty = self.landing_pad_type();
1676             bx.cleanup_landing_pad(llretty, llpersonality);
1677
1678             let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, LangItem::PanicNoUnwind);
1679             let fn_ty = bx.fn_decl_backend_type(&fn_abi);
1680
1681             let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &[], None);
1682             bx.do_not_inline(llret);
1683
1684             bx.unreachable();
1685
1686             self.double_unwind_guard = Some(llbb);
1687             llbb
1688         })
1689     }
1690
1691     /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
1692     /// cached in `self.cached_llbbs`, or created on demand (and cached).
1693     // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
1694     // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
1695     pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1696         self.try_llbb(bb).unwrap()
1697     }
1698
1699     /// Like `llbb`, but may fail if the basic block should be skipped.
1700     pub fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
1701         match self.cached_llbbs[bb] {
1702             CachedLlbb::None => {
1703                 // FIXME(eddyb) only name the block if `fewer_names` is `false`.
1704                 let llbb = Bx::append_block(self.cx, self.llfn, &format!("{:?}", bb));
1705                 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
1706                 Some(llbb)
1707             }
1708             CachedLlbb::Some(llbb) => Some(llbb),
1709             CachedLlbb::Skip => None,
1710         }
1711     }
1712
1713     fn make_return_dest(
1714         &mut self,
1715         bx: &mut Bx,
1716         dest: mir::Place<'tcx>,
1717         fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1718         llargs: &mut Vec<Bx::Value>,
1719         is_intrinsic: bool,
1720     ) -> ReturnDest<'tcx, Bx::Value> {
1721         // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1722         if fn_ret.is_ignore() {
1723             return ReturnDest::Nothing;
1724         }
1725         let dest = if let Some(index) = dest.as_local() {
1726             match self.locals[index] {
1727                 LocalRef::Place(dest) => dest,
1728                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1729                 LocalRef::Operand(None) => {
1730                     // Handle temporary places, specifically `Operand` ones, as
1731                     // they don't have `alloca`s.
1732                     return if fn_ret.is_indirect() {
1733                         // Odd, but possible, case, we have an operand temporary,
1734                         // but the calling convention has an indirect return.
1735                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1736                         tmp.storage_live(bx);
1737                         llargs.push(tmp.llval);
1738                         ReturnDest::IndirectOperand(tmp, index)
1739                     } else if is_intrinsic {
1740                         // Currently, intrinsics always need a location to store
1741                         // the result, so we create a temporary `alloca` for the
1742                         // result.
1743                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1744                         tmp.storage_live(bx);
1745                         ReturnDest::IndirectOperand(tmp, index)
1746                     } else {
1747                         ReturnDest::DirectOperand(index)
1748                     };
1749                 }
1750                 LocalRef::Operand(Some(_)) => {
1751                     bug!("place local already assigned to");
1752                 }
1753             }
1754         } else {
1755             self.codegen_place(
1756                 bx,
1757                 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1758             )
1759         };
1760         if fn_ret.is_indirect() {
1761             if dest.align < dest.layout.align.abi {
1762                 // Currently, MIR code generation does not create calls
1763                 // that store directly to fields of packed structs (in
1764                 // fact, the calls it creates write only to temps).
1765                 //
1766                 // If someone changes that, please update this code path
1767                 // to create a temporary.
1768                 span_bug!(self.mir.span, "can't directly store to unaligned value");
1769             }
1770             llargs.push(dest.llval);
1771             ReturnDest::Nothing
1772         } else {
1773             ReturnDest::Store(dest)
1774         }
1775     }
1776
1777     fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1778         if let Some(index) = dst.as_local() {
1779             match self.locals[index] {
1780                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1781                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1782                 LocalRef::Operand(None) => {
1783                     let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1784                     assert!(!dst_layout.ty.has_erasable_regions());
1785                     let place = PlaceRef::alloca(bx, dst_layout);
1786                     place.storage_live(bx);
1787                     self.codegen_transmute_into(bx, src, place);
1788                     let op = bx.load_operand(place);
1789                     place.storage_dead(bx);
1790                     self.locals[index] = LocalRef::Operand(Some(op));
1791                     self.debug_introduce_local(bx, index);
1792                 }
1793                 LocalRef::Operand(Some(op)) => {
1794                     assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1795                 }
1796             }
1797         } else {
1798             let dst = self.codegen_place(bx, dst.as_ref());
1799             self.codegen_transmute_into(bx, src, dst);
1800         }
1801     }
1802
1803     fn codegen_transmute_into(
1804         &mut self,
1805         bx: &mut Bx,
1806         src: &mir::Operand<'tcx>,
1807         dst: PlaceRef<'tcx, Bx::Value>,
1808     ) {
1809         let src = self.codegen_operand(bx, src);
1810
1811         // Special-case transmutes between scalars as simple bitcasts.
1812         match (src.layout.abi, dst.layout.abi) {
1813             (abi::Abi::Scalar(src_scalar), abi::Abi::Scalar(dst_scalar)) => {
1814                 // HACK(eddyb) LLVM doesn't like `bitcast`s between pointers and non-pointers.
1815                 if (src_scalar.primitive() == abi::Pointer)
1816                     == (dst_scalar.primitive() == abi::Pointer)
1817                 {
1818                     assert_eq!(src.layout.size, dst.layout.size);
1819
1820                     // NOTE(eddyb) the `from_immediate` and `to_immediate_scalar`
1821                     // conversions allow handling `bool`s the same as `u8`s.
1822                     let src = bx.from_immediate(src.immediate());
1823                     let src_as_dst = bx.bitcast(src, bx.backend_type(dst.layout));
1824                     Immediate(bx.to_immediate_scalar(src_as_dst, dst_scalar)).store(bx, dst);
1825                     return;
1826                 }
1827             }
1828             _ => {}
1829         }
1830
1831         let llty = bx.backend_type(src.layout);
1832         let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1833         let align = src.layout.align.abi.min(dst.align);
1834         src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1835     }
1836
1837     // Stores the return value of a function call into it's final location.
1838     fn store_return(
1839         &mut self,
1840         bx: &mut Bx,
1841         dest: ReturnDest<'tcx, Bx::Value>,
1842         ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1843         llval: Bx::Value,
1844     ) {
1845         use self::ReturnDest::*;
1846
1847         match dest {
1848             Nothing => (),
1849             Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1850             IndirectOperand(tmp, index) => {
1851                 let op = bx.load_operand(tmp);
1852                 tmp.storage_dead(bx);
1853                 self.locals[index] = LocalRef::Operand(Some(op));
1854                 self.debug_introduce_local(bx, index);
1855             }
1856             DirectOperand(index) => {
1857                 // If there is a cast, we have to store and reload.
1858                 let op = if let PassMode::Cast(..) = ret_abi.mode {
1859                     let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1860                     tmp.storage_live(bx);
1861                     bx.store_arg(&ret_abi, llval, tmp);
1862                     let op = bx.load_operand(tmp);
1863                     tmp.storage_dead(bx);
1864                     op
1865                 } else {
1866                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1867                 };
1868                 self.locals[index] = LocalRef::Operand(Some(op));
1869                 self.debug_introduce_local(bx, index);
1870             }
1871         }
1872     }
1873 }
1874
1875 enum ReturnDest<'tcx, V> {
1876     // Do nothing; the return value is indirect or ignored.
1877     Nothing,
1878     // Store the return value to the pointer.
1879     Store(PlaceRef<'tcx, V>),
1880     // Store an indirect return value to an operand local place.
1881     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1882     // Store a direct return value to an operand local place.
1883     DirectOperand(mir::Local),
1884 }