1 use super::operand::OperandRef;
2 use super::operand::OperandValue::{Immediate, Pair, Ref};
3 use super::place::PlaceRef;
4 use super::{FunctionCx, LocalRef};
7 use crate::common::{self, IntPredicate};
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;
28 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
29 /// e.g., creating a basic block, calling a function, etc.
30 struct TerminatorCodegenHelper<'tcx> {
32 terminator: &'tcx mir::Terminator<'tcx>,
33 funclet_bb: Option<mir::BasicBlock>,
36 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
37 /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
38 /// either already previously cached, or newly created, by `landing_pad_for`.
39 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
41 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
42 ) -> Option<&'b Bx::Funclet> {
43 let funclet_bb = self.funclet_bb?;
44 if base::wants_msvc_seh(fx.cx.tcx().sess) {
45 // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
46 // it has to be now. This may not seem necessary, as RPO should lead
47 // to all the unwind edges being visited (and so to `landing_pad_for`
48 // getting called for them), before building any of the blocks inside
49 // the funclet itself - however, if MIR contains edges that end up not
50 // being needed in the LLVM IR after monomorphization, the funclet may
51 // be unreachable, and we don't have yet a way to skip building it in
52 // such an eventuality (which may be a better solution than this).
53 if fx.funclets[funclet_bb].is_none() {
54 fx.landing_pad_for(funclet_bb);
58 fx.funclets[funclet_bb]
60 .expect("landing_pad_for didn't also create funclets entry"),
67 /// Get a basic block (creating it if necessary), possibly with a landing
69 fn llbb_with_landing_pad<Bx: BuilderMethods<'a, 'tcx>>(
71 fx: &mut FunctionCx<'a, 'tcx, Bx>,
72 target: mir::BasicBlock,
73 ) -> (Bx::BasicBlock, bool) {
74 let span = self.terminator.source_info.span;
75 let lltarget = fx.llbb(target);
76 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
77 match (self.funclet_bb, target_funclet) {
78 (None, None) => (lltarget, false),
79 // jump *into* cleanup - need a landing pad if GNU, cleanup pad if MSVC
80 (None, Some(_)) => (fx.landing_pad_for(target), false),
81 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
82 (Some(f), Some(t_f)) => {
83 if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) {
86 (fx.landing_pad_for(target), true)
92 /// Get a basic block (creating it if necessary), possibly with cleanup
93 /// stuff in it or next to it.
94 fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
96 fx: &mut FunctionCx<'a, 'tcx, Bx>,
97 target: mir::BasicBlock,
99 let (lltarget, is_cleanupret) = self.llbb_with_landing_pad(fx, target);
101 // MSVC cross-funclet jump - need a trampoline
102 debug_assert!(base::wants_msvc_seh(fx.cx.tcx().sess));
103 debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
104 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
105 let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
106 let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
107 trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
114 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
116 fx: &mut FunctionCx<'a, 'tcx, Bx>,
118 target: mir::BasicBlock,
120 let (lltarget, is_cleanupret) = self.llbb_with_landing_pad(fx, target);
122 // MSVC micro-optimization: generate a `ret` rather than a jump
124 debug_assert!(base::wants_msvc_seh(fx.cx.tcx().sess));
125 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
131 /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
132 /// return destination `destination` and the cleanup function `cleanup`.
133 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
135 fx: &mut FunctionCx<'a, 'tcx, Bx>,
137 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
139 llargs: &[Bx::Value],
140 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
141 cleanup: Option<mir::BasicBlock>,
142 copied_constant_arguments: &[PlaceRef<'tcx, <Bx as BackendTypes>::Value>],
144 // If there is a cleanup block and the function we're calling can unwind, then
145 // do an invoke, otherwise do a call.
146 let fn_ty = bx.fn_decl_backend_type(&fn_abi);
148 let unwind_block = if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
149 Some(self.llbb_with_cleanup(fx, cleanup))
150 } else if fx.mir[self.bb].is_cleanup
152 && !base::wants_msvc_seh(fx.cx.tcx().sess)
154 // Exception must not propagate out of the execution of a cleanup (doing so
155 // can cause undefined behaviour). We insert a double unwind guard for
156 // functions that can potentially unwind to protect against this.
158 // This is not necessary for SEH which does not use successive unwinding
159 // like Itanium EH. EH frames in SEH are different from normal function
160 // frames and SEH will abort automatically if an exception tries to
161 // propagate out from cleanup.
162 Some(fx.double_unwind_guard())
167 if let Some(unwind_block) = unwind_block {
168 let ret_llbb = if let Some((_, target)) = destination {
171 fx.unreachable_block()
173 let invokeret = bx.invoke(
182 if fx.mir[self.bb].is_cleanup {
183 bx.do_not_inline(invokeret);
186 if let Some((ret_dest, target)) = destination {
187 bx.switch_to_block(fx.llbb(target));
188 fx.set_debug_loc(bx, self.terminator.source_info);
189 for tmp in copied_constant_arguments {
190 bx.lifetime_end(tmp.llval, tmp.layout.size);
192 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
195 let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &llargs, self.funclet(fx));
196 if fx.mir[self.bb].is_cleanup {
197 // Cleanup is always the cold path. Don't inline
198 // drop glue. Also, when there is a deeply-nested
199 // struct, there are "symmetry" issues that cause
200 // exponential inlining - see issue #41696.
201 bx.do_not_inline(llret);
204 if let Some((ret_dest, target)) = destination {
205 for tmp in copied_constant_arguments {
206 bx.lifetime_end(tmp.llval, tmp.layout.size);
208 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
209 self.funclet_br(fx, bx, target);
216 /// Generates inline assembly with optional `destination` and `cleanup`.
217 fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
219 fx: &mut FunctionCx<'a, 'tcx, Bx>,
221 template: &[InlineAsmTemplatePiece],
222 operands: &[InlineAsmOperandRef<'tcx, Bx>],
223 options: InlineAsmOptions,
225 destination: Option<mir::BasicBlock>,
226 cleanup: Option<mir::BasicBlock>,
227 instance: Instance<'_>,
229 if let Some(cleanup) = cleanup {
230 let ret_llbb = if let Some(target) = destination {
233 fx.unreachable_block()
236 bx.codegen_inline_asm(
242 Some((ret_llbb, self.llbb_with_cleanup(fx, cleanup), self.funclet(fx))),
245 bx.codegen_inline_asm(template, &operands, options, line_spans, instance, None);
247 if let Some(target) = destination {
248 self.funclet_br(fx, bx, target);
256 /// Codegen implementations for some terminator variants.
257 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
258 /// Generates code for a `Resume` terminator.
259 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
260 if let Some(funclet) = helper.funclet(self) {
261 bx.cleanup_ret(funclet, None);
263 let slot = self.get_personality_slot(&mut bx);
264 let lp0 = slot.project_field(&mut bx, 0);
265 let lp0 = bx.load_operand(lp0).immediate();
266 let lp1 = slot.project_field(&mut bx, 1);
267 let lp1 = bx.load_operand(lp1).immediate();
268 slot.storage_dead(&mut bx);
270 let mut lp = bx.const_undef(self.landing_pad_type());
271 lp = bx.insert_value(lp, lp0, 0);
272 lp = bx.insert_value(lp, lp1, 1);
277 fn codegen_switchint_terminator(
279 helper: TerminatorCodegenHelper<'tcx>,
281 discr: &mir::Operand<'tcx>,
283 targets: &SwitchTargets,
285 let discr = self.codegen_operand(&mut bx, &discr);
286 // `switch_ty` is redundant, sanity-check that.
287 assert_eq!(discr.layout.ty, switch_ty);
288 let mut target_iter = targets.iter();
289 if target_iter.len() == 1 {
290 // If there are two targets (one conditional, one fallback), emit `br` instead of
292 let (test_value, target) = target_iter.next().unwrap();
293 let lltrue = helper.llbb_with_cleanup(self, target);
294 let llfalse = helper.llbb_with_cleanup(self, targets.otherwise());
295 if switch_ty == bx.tcx().types.bool {
296 // Don't generate trivial icmps when switching on bool.
298 0 => bx.cond_br(discr.immediate(), llfalse, lltrue),
299 1 => bx.cond_br(discr.immediate(), lltrue, llfalse),
303 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
304 let llval = bx.const_uint_big(switch_llty, test_value);
305 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
306 bx.cond_br(cmp, lltrue, llfalse);
308 } else if self.cx.sess().opts.optimize == OptLevel::No
309 && target_iter.len() == 2
310 && self.mir[targets.otherwise()].is_empty_unreachable()
312 // In unoptimized builds, if there are two normal targets and the `otherwise` target is
313 // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
314 // BB, which will usually (but not always) be dead code.
316 // Why only in unoptimized builds?
317 // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
318 // must fall back to the to the slower SelectionDAG isel. Therefore, using `br` gives
319 // significant compile time speedups for unoptimized builds.
320 // - In optimized builds the above doesn't hold, and using `br` sometimes results in
321 // worse generated code because LLVM can no longer tell that the value being switched
322 // on can only have two values, e.g. 0 and 1.
324 let (test_value1, target1) = target_iter.next().unwrap();
325 let (_test_value2, target2) = target_iter.next().unwrap();
326 let ll1 = helper.llbb_with_cleanup(self, target1);
327 let ll2 = helper.llbb_with_cleanup(self, target2);
328 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
329 let llval = bx.const_uint_big(switch_llty, test_value1);
330 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
331 bx.cond_br(cmp, ll1, ll2);
335 helper.llbb_with_cleanup(self, targets.otherwise()),
336 target_iter.map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
341 fn codegen_return_terminator(&mut self, mut bx: Bx) {
342 // Call `va_end` if this is the definition of a C-variadic function.
343 if self.fn_abi.c_variadic {
344 // The `VaList` "spoofed" argument is just after all the real arguments.
345 let va_list_arg_idx = self.fn_abi.args.len();
346 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
347 LocalRef::Place(va_list) => {
348 bx.va_end(va_list.llval);
350 _ => bug!("C-variadic function must have a `VaList` place"),
353 if self.fn_abi.ret.layout.abi.is_uninhabited() {
354 // Functions with uninhabited return values are marked `noreturn`,
355 // so we should make sure that we never actually do.
356 // We play it safe by using a well-defined `abort`, but we could go for immediate UB
357 // if that turns out to be helpful.
359 // `abort` does not terminate the block, so we still need to generate
360 // an `unreachable` terminator after it.
364 let llval = match &self.fn_abi.ret.mode {
365 PassMode::Ignore | PassMode::Indirect { .. } => {
370 PassMode::Direct(_) | PassMode::Pair(..) => {
371 let op = self.codegen_consume(&mut bx, mir::Place::return_place().as_ref());
372 if let Ref(llval, _, align) = op.val {
373 bx.load(bx.backend_type(op.layout), llval, align)
375 op.immediate_or_packed_pair(&mut bx)
379 PassMode::Cast(cast_ty, _) => {
380 let op = match self.locals[mir::RETURN_PLACE] {
381 LocalRef::Operand(Some(op)) => op,
382 LocalRef::Operand(None) => bug!("use of return before def"),
383 LocalRef::Place(cg_place) => OperandRef {
384 val: Ref(cg_place.llval, None, cg_place.align),
385 layout: cg_place.layout,
387 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
389 let llslot = match op.val {
390 Immediate(_) | Pair(..) => {
391 let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
392 op.val.store(&mut bx, scratch);
395 Ref(llval, _, align) => {
396 assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
400 let ty = bx.cast_backend_type(cast_ty);
401 let addr = bx.pointercast(llslot, bx.type_ptr_to(ty));
402 bx.load(ty, addr, self.fn_abi.ret.layout.align.abi)
408 #[tracing::instrument(level = "trace", skip(self, helper, bx))]
409 fn codegen_drop_terminator(
411 helper: TerminatorCodegenHelper<'tcx>,
413 location: mir::Place<'tcx>,
414 target: mir::BasicBlock,
415 unwind: Option<mir::BasicBlock>,
417 let ty = location.ty(self.mir, bx.tcx()).ty;
418 let ty = self.monomorphize(ty);
419 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
421 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
422 // we don't actually need to drop anything.
423 helper.funclet_br(self, &mut bx, target);
427 let place = self.codegen_place(&mut bx, location.as_ref());
429 let mut args = if let Some(llextra) = place.llextra {
430 args2 = [place.llval, llextra];
433 args1 = [place.llval];
436 let (drop_fn, fn_abi) = match ty.kind() {
437 // FIXME(eddyb) perhaps move some of this logic into
438 // `Instance::resolve_drop_in_place`?
439 ty::Dynamic(_, _, ty::Dyn) => {
440 // IN THIS ARM, WE HAVE:
441 // ty = *mut (dyn Trait)
442 // which is: exists<T> ( *mut T, Vtable<T: Trait> )
445 // args = ( Data, Vtable )
452 let virtual_drop = Instance {
453 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
454 substs: drop_fn.substs,
456 debug!("ty = {:?}", ty);
457 debug!("drop_fn = {:?}", drop_fn);
458 debug!("args = {:?}", args);
459 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
460 let vtable = args[1];
461 // Truncate vtable off of args list
464 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
465 .get_fn(&mut bx, vtable, ty, &fn_abi),
469 ty::Dynamic(_, _, ty::DynStar) => {
470 // IN THIS ARM, WE HAVE:
471 // ty = *mut (dyn* Trait)
472 // which is: *mut exists<T: sizeof(T) == sizeof(usize)> (T, Vtable<T: Trait>)
485 // WE CAN CONVERT THIS INTO THE ABOVE LOGIC BY DOING
487 // data = &(*args[0]).0 // gives a pointer to Data above (really the same pointer)
488 // vtable = (*args[0]).1 // loads the vtable out
489 // (data, vtable) // an equivalent Rust `*mut dyn Trait`
491 // SO THEN WE CAN USE THE ABOVE CODE.
492 let virtual_drop = Instance {
493 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
494 substs: drop_fn.substs,
496 debug!("ty = {:?}", ty);
497 debug!("drop_fn = {:?}", drop_fn);
498 debug!("args = {:?}", args);
499 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
501 let data_ty = bx.cx().backend_type(place.layout);
503 bx.gep(data_ty, data, &[bx.cx().const_i32(0), bx.cx().const_i32(1)]);
504 let vtable = bx.load(bx.type_i8p(), vtable_ptr, abi::Align::ONE);
505 // Truncate vtable off of args list
507 debug!("args' = {:?}", args);
509 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
510 .get_fn(&mut bx, vtable, ty, &fn_abi),
514 _ => (bx.get_fn_addr(drop_fn), bx.fn_abi_of_instance(drop_fn, ty::List::empty())),
522 Some((ReturnDest::Nothing, target)),
528 fn codegen_assert_terminator(
530 helper: TerminatorCodegenHelper<'tcx>,
532 terminator: &mir::Terminator<'tcx>,
533 cond: &mir::Operand<'tcx>,
535 msg: &mir::AssertMessage<'tcx>,
536 target: mir::BasicBlock,
537 cleanup: Option<mir::BasicBlock>,
539 let span = terminator.source_info.span;
540 let cond = self.codegen_operand(&mut bx, cond).immediate();
541 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
543 // This case can currently arise only from functions marked
544 // with #[rustc_inherit_overflow_checks] and inlined from
545 // another crate (mostly core::num generic/#[inline] fns),
546 // while the current crate doesn't use overflow checks.
547 // NOTE: Unlike binops, negation doesn't have its own
548 // checked operation, just a comparison with the minimum
549 // value, so we have to check for the assert message.
550 if !bx.check_overflow() {
551 if let AssertKind::OverflowNeg(_) = *msg {
552 const_cond = Some(expected);
556 // Don't codegen the panic block if success if known.
557 if const_cond == Some(expected) {
558 helper.funclet_br(self, &mut bx, target);
562 // Pass the condition through llvm.expect for branch hinting.
563 let cond = bx.expect(cond, expected);
565 // Create the failure block and the conditional branch to it.
566 let lltarget = helper.llbb_with_cleanup(self, target);
567 let panic_block = bx.append_sibling_block("panic");
569 bx.cond_br(cond, lltarget, panic_block);
571 bx.cond_br(cond, panic_block, lltarget);
574 // After this point, bx is the block for the call to panic.
575 bx.switch_to_block(panic_block);
576 self.set_debug_loc(&mut bx, terminator.source_info);
578 // Get the location information.
579 let location = self.get_caller_location(&mut bx, terminator.source_info).immediate();
581 // Put together the arguments to the panic entry point.
582 let (lang_item, args) = match msg {
583 AssertKind::BoundsCheck { ref len, ref index } => {
584 let len = self.codegen_operand(&mut bx, len).immediate();
585 let index = self.codegen_operand(&mut bx, index).immediate();
586 // It's `fn panic_bounds_check(index: usize, len: usize)`,
587 // and `#[track_caller]` adds an implicit third argument.
588 (LangItem::PanicBoundsCheck, vec![index, len, location])
591 let msg = bx.const_str(msg.description());
592 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
593 // as two arguments, and `#[track_caller]` adds an implicit third argument.
594 (LangItem::Panic, vec![msg.0, msg.1, location])
598 let (fn_abi, llfn) = common::build_langcall(&bx, Some(span), lang_item);
600 // Codegen the actual panic invoke/call.
601 helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup, &[]);
604 fn codegen_abort_terminator(
606 helper: TerminatorCodegenHelper<'tcx>,
608 terminator: &mir::Terminator<'tcx>,
610 let span = terminator.source_info.span;
611 self.set_debug_loc(&mut bx, terminator.source_info);
613 // Obtain the panic entry point.
614 let (fn_abi, llfn) = common::build_langcall(&bx, Some(span), LangItem::PanicNoUnwind);
616 // Codegen the actual panic invoke/call.
617 helper.do_call(self, &mut bx, fn_abi, llfn, &[], None, None, &[]);
620 /// Returns `true` if this is indeed a panic intrinsic and codegen is done.
621 fn codegen_panic_intrinsic(
623 helper: &TerminatorCodegenHelper<'tcx>,
625 intrinsic: Option<Symbol>,
626 instance: Option<Instance<'tcx>>,
627 source_info: mir::SourceInfo,
628 target: Option<mir::BasicBlock>,
629 cleanup: Option<mir::BasicBlock>,
631 // Emit a panic or a no-op for `assert_*` intrinsics.
632 // These are intrinsics that compile to panics so that we can get a message
633 // which mentions the offending type, even from a const context.
634 #[derive(Debug, PartialEq)]
635 enum AssertIntrinsic {
640 let panic_intrinsic = intrinsic.and_then(|i| match i {
641 sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
642 sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
643 sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
646 if let Some(intrinsic) = panic_intrinsic {
647 use AssertIntrinsic::*;
649 let ty = instance.unwrap().substs.type_at(0);
650 let layout = bx.layout_of(ty);
651 let do_panic = match intrinsic {
652 Inhabited => layout.abi.is_uninhabited(),
653 ZeroValid => !bx.tcx().permits_zero_init(layout),
654 UninitValid => !bx.tcx().permits_uninit_init(layout),
657 let msg_str = with_no_visible_paths!({
658 with_no_trimmed_paths!({
659 if layout.abi.is_uninhabited() {
660 // Use this error even for the other intrinsics as it is more precise.
661 format!("attempted to instantiate uninhabited type `{}`", ty)
662 } else if intrinsic == ZeroValid {
663 format!("attempted to zero-initialize type `{}`, which is invalid", ty)
666 "attempted to leave type `{}` uninitialized, which is invalid",
672 let msg = bx.const_str(&msg_str);
673 let location = self.get_caller_location(bx, source_info).immediate();
675 // Obtain the panic entry point.
677 common::build_langcall(bx, Some(source_info.span), LangItem::Panic);
679 // Codegen the actual panic invoke/call.
685 &[msg.0, msg.1, location],
686 target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
692 let target = target.unwrap();
693 helper.funclet_br(self, bx, target)
701 fn codegen_call_terminator(
703 helper: TerminatorCodegenHelper<'tcx>,
705 terminator: &mir::Terminator<'tcx>,
706 func: &mir::Operand<'tcx>,
707 args: &[mir::Operand<'tcx>],
708 destination: mir::Place<'tcx>,
709 target: Option<mir::BasicBlock>,
710 cleanup: Option<mir::BasicBlock>,
713 let source_info = terminator.source_info;
714 let span = source_info.span;
716 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
717 let callee = self.codegen_operand(&mut bx, func);
719 let (instance, mut llfn) = match *callee.layout.ty.kind() {
720 ty::FnDef(def_id, substs) => (
722 ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
725 .polymorphize(bx.tcx()),
729 ty::FnPtr(_) => (None, Some(callee.immediate())),
730 _ => bug!("{} is not callable", callee.layout.ty),
732 let def = instance.map(|i| i.def);
734 if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
735 // Empty drop glue; a no-op.
736 let target = target.unwrap();
737 helper.funclet_br(self, &mut bx, target);
741 // FIXME(eddyb) avoid computing this if possible, when `instance` is
742 // available - right now `sig` is only needed for getting the `abi`
743 // and figuring out how many extra args were passed to a C-variadic `fn`.
744 let sig = callee.layout.ty.fn_sig(bx.tcx());
747 // Handle intrinsics old codegen wants Expr's for, ourselves.
748 let intrinsic = match def {
749 Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
753 let extra_args = &args[sig.inputs().skip_binder().len()..];
754 let extra_args = bx.tcx().mk_type_list(extra_args.iter().map(|op_arg| {
755 let op_ty = op_arg.ty(self.mir, bx.tcx());
756 self.monomorphize(op_ty)
759 let fn_abi = match instance {
760 Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
761 None => bx.fn_abi_of_fn_ptr(sig, extra_args),
764 if intrinsic == Some(sym::transmute) {
765 if let Some(target) = target {
766 self.codegen_transmute(&mut bx, &args[0], destination);
767 helper.funclet_br(self, &mut bx, target);
769 // If we are trying to transmute to an uninhabited type,
770 // it is likely there is no allotted destination. In fact,
771 // transmuting to an uninhabited type is UB, which means
772 // we can do what we like. Here, we declare that transmuting
773 // into an uninhabited type is impossible, so anything following
774 // it must be unreachable.
775 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
781 if self.codegen_panic_intrinsic(
793 // The arguments we'll be passing. Plus one to account for outptr, if used.
794 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
795 let mut llargs = Vec::with_capacity(arg_count);
797 // Prepare the return value destination
798 let ret_dest = if target.is_some() {
799 let is_intrinsic = intrinsic.is_some();
800 self.make_return_dest(&mut bx, destination, &fn_abi.ret, &mut llargs, is_intrinsic)
805 if intrinsic == Some(sym::caller_location) {
806 if let Some(target) = target {
808 .get_caller_location(&mut bx, mir::SourceInfo { span: fn_span, ..source_info });
810 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
811 location.val.store(&mut bx, tmp);
813 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
814 helper.funclet_br(self, &mut bx, target);
820 None | Some(sym::drop_in_place) => {}
821 Some(sym::copy_nonoverlapping) => unreachable!(),
823 let dest = match ret_dest {
824 _ if fn_abi.ret.is_indirect() => llargs[0],
825 ReturnDest::Nothing => {
826 bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
828 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
829 ReturnDest::DirectOperand(_) => {
830 bug!("Cannot use direct operand with an intrinsic call")
834 let args: Vec<_> = args
838 // The indices passed to simd_shuffle* in the
839 // third argument must be constant. This is
840 // checked by const-qualification, which also
841 // promotes any complex rvalues to constants.
842 if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
843 if let mir::Operand::Constant(constant) = arg {
844 let c = self.eval_mir_constant(constant);
845 let (llval, ty) = self.simd_shuffle_indices(
848 self.monomorphize(constant.ty()),
852 val: Immediate(llval),
853 layout: bx.layout_of(ty),
856 span_bug!(span, "shuffle indices must be constant");
860 self.codegen_operand(&mut bx, arg)
864 Self::codegen_intrinsic_call(
866 *instance.as_ref().unwrap(),
873 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
874 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
877 if let Some(target) = target {
878 helper.funclet_br(self, &mut bx, target);
887 // Split the rust-call tupled arguments off.
888 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
889 let (tup, args) = args.split_last().unwrap();
895 let mut copied_constant_arguments = vec![];
896 'make_args: for (i, arg) in first_args.iter().enumerate() {
897 let mut op = self.codegen_operand(&mut bx, arg);
899 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
901 Pair(data_ptr, meta) => {
902 // In the case of Rc<Self>, we need to explicitly pass a
903 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
904 // that is understood elsewhere in the compiler as a method on
906 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
907 // we get a value of a built-in pointer type
908 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
909 && !op.layout.ty.is_region_ptr()
911 for i in 0..op.layout.fields.count() {
912 let field = op.extract_field(&mut bx, i);
913 if !field.layout.is_zst() {
914 // we found the one non-zero-sized field that is allowed
915 // now find *its* non-zero-sized field, or stop if it's a
918 continue 'descend_newtypes;
922 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
925 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
926 // data pointer and vtable. Look up the method in the vtable, and pass
927 // the data pointer as the first argument
928 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
934 llargs.push(data_ptr);
937 Ref(data_ptr, Some(meta), _) => {
938 // by-value dynamic dispatch
939 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
945 llargs.push(data_ptr);
949 let ty::Ref(_, ty, _) = op.layout.ty.kind() else {
950 span_bug!(span, "can't codegen a virtual call on {:#?}", op);
952 if !ty.is_dyn_star() {
953 span_bug!(span, "can't codegen a virtual call on {:#?}", op);
955 // FIXME(dyn-star): Make sure this is done on a &dyn* receiver
956 let place = op.deref(bx.cx());
957 let data_ptr = place.project_field(&mut bx, 0);
958 let meta_ptr = place.project_field(&mut bx, 1);
959 let meta = bx.load_operand(meta_ptr);
960 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
966 llargs.push(data_ptr.llval);
970 span_bug!(span, "can't codegen a virtual call on {:#?}", op);
975 // The callee needs to own the argument memory if we pass it
976 // by-ref, so make a local copy of non-immediate constants.
977 match (arg, op.val) {
978 (&mir::Operand::Copy(_), Ref(_, None, _))
979 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
980 let tmp = PlaceRef::alloca(&mut bx, op.layout);
981 bx.lifetime_start(tmp.llval, tmp.layout.size);
982 op.val.store(&mut bx, tmp);
983 op.val = Ref(tmp.llval, None, tmp.align);
984 copied_constant_arguments.push(tmp);
989 self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
991 let num_untupled = untuple.map(|tup| {
992 self.codegen_arguments_untupled(
996 &fn_abi.args[first_args.len()..],
1000 let needs_location =
1001 instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
1003 let mir_args = if let Some(num_untupled) = num_untupled {
1004 first_args.len() + num_untupled
1011 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {:?} {:?} {:?}",
1017 self.get_caller_location(&mut bx, mir::SourceInfo { span: fn_span, ..source_info });
1019 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1020 terminator, location, fn_span
1023 let last_arg = fn_abi.args.last().unwrap();
1024 self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
1027 let (is_indirect_call, fn_ptr) = match (llfn, instance) {
1028 (Some(llfn), _) => (true, llfn),
1029 (None, Some(instance)) => (false, bx.get_fn_addr(instance)),
1030 _ => span_bug!(span, "no llfn for call"),
1033 // For backends that support CFI using type membership (i.e., testing whether a given
1034 // pointer is associated with a type identifier).
1035 if bx.tcx().sess.is_sanitizer_cfi_enabled() && is_indirect_call {
1036 // Emit type metadata and checks.
1037 // FIXME(rcvalle): Add support for generalized identifiers.
1038 // FIXME(rcvalle): Create distinct unnamed MDNodes for internal identifiers.
1039 let typeid = typeid_for_fnabi(bx.tcx(), fn_abi);
1040 let typeid_metadata = self.cx.typeid_metadata(typeid);
1042 // Test whether the function pointer is associated with the type identifier.
1043 let cond = bx.type_test(fn_ptr, typeid_metadata);
1044 let bb_pass = bx.append_sibling_block("type_test.pass");
1045 let bb_fail = bx.append_sibling_block("type_test.fail");
1046 bx.cond_br(cond, bb_pass, bb_fail);
1048 bx.switch_to_block(bb_pass);
1055 target.as_ref().map(|&target| (ret_dest, target)),
1057 &copied_constant_arguments,
1060 bx.switch_to_block(bb_fail);
1073 target.as_ref().map(|&target| (ret_dest, target)),
1075 &copied_constant_arguments,
1079 fn codegen_asm_terminator(
1081 helper: TerminatorCodegenHelper<'tcx>,
1083 terminator: &mir::Terminator<'tcx>,
1084 template: &[ast::InlineAsmTemplatePiece],
1085 operands: &[mir::InlineAsmOperand<'tcx>],
1086 options: ast::InlineAsmOptions,
1087 line_spans: &[Span],
1088 destination: Option<mir::BasicBlock>,
1089 cleanup: Option<mir::BasicBlock>,
1090 instance: Instance<'_>,
1092 let span = terminator.source_info.span;
1094 let operands: Vec<_> = operands
1096 .map(|op| match *op {
1097 mir::InlineAsmOperand::In { reg, ref value } => {
1098 let value = self.codegen_operand(&mut bx, value);
1099 InlineAsmOperandRef::In { reg, value }
1101 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1102 let place = place.map(|place| self.codegen_place(&mut bx, place.as_ref()));
1103 InlineAsmOperandRef::Out { reg, late, place }
1105 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1106 let in_value = self.codegen_operand(&mut bx, in_value);
1108 out_place.map(|out_place| self.codegen_place(&mut bx, out_place.as_ref()));
1109 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1111 mir::InlineAsmOperand::Const { ref value } => {
1112 let const_value = self
1113 .eval_mir_constant(value)
1114 .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
1115 let string = common::asm_const_to_str(
1119 bx.layout_of(value.ty()),
1121 InlineAsmOperandRef::Const { string }
1123 mir::InlineAsmOperand::SymFn { ref value } => {
1124 let literal = self.monomorphize(value.literal);
1125 if let ty::FnDef(def_id, substs) = *literal.ty().kind() {
1126 let instance = ty::Instance::resolve_for_fn_ptr(
1128 ty::ParamEnv::reveal_all(),
1133 InlineAsmOperandRef::SymFn { instance }
1135 span_bug!(span, "invalid type for asm sym (fn)");
1138 mir::InlineAsmOperand::SymStatic { def_id } => {
1139 InlineAsmOperandRef::SymStatic { def_id }
1144 helper.do_inlineasm(
1158 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1159 pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
1160 let llbb = self.llbb(bb);
1161 let mut bx = Bx::build(self.cx, llbb);
1163 let data = &mir[bb];
1165 debug!("codegen_block({:?}={:?})", bb, data);
1167 for statement in &data.statements {
1168 bx = self.codegen_statement(bx, statement);
1171 self.codegen_terminator(bx, bb, data.terminator());
1174 fn codegen_terminator(
1177 bb: mir::BasicBlock,
1178 terminator: &'tcx mir::Terminator<'tcx>,
1180 debug!("codegen_terminator: {:?}", terminator);
1182 // Create the cleanup bundle, if needed.
1183 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
1184 let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
1186 self.set_debug_loc(&mut bx, terminator.source_info);
1187 match terminator.kind {
1188 mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
1190 mir::TerminatorKind::Abort => {
1191 self.codegen_abort_terminator(helper, bx, terminator);
1194 mir::TerminatorKind::Goto { target } => {
1195 helper.funclet_br(self, &mut bx, target);
1198 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref targets } => {
1199 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, targets);
1202 mir::TerminatorKind::Return => {
1203 self.codegen_return_terminator(bx);
1206 mir::TerminatorKind::Unreachable => {
1210 mir::TerminatorKind::Drop { place, target, unwind } => {
1211 self.codegen_drop_terminator(helper, bx, place, target, unwind);
1214 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
1215 self.codegen_assert_terminator(
1216 helper, bx, terminator, cond, expected, msg, target, cleanup,
1220 mir::TerminatorKind::DropAndReplace { .. } => {
1221 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1224 mir::TerminatorKind::Call {
1233 self.codegen_call_terminator(
1245 mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1246 bug!("generator ops in codegen")
1248 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1249 bug!("borrowck false edges in codegen")
1252 mir::TerminatorKind::InlineAsm {
1260 self.codegen_asm_terminator(
1276 fn codegen_argument(
1279 op: OperandRef<'tcx, Bx::Value>,
1280 llargs: &mut Vec<Bx::Value>,
1281 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1284 PassMode::Ignore => return,
1285 PassMode::Cast(_, true) => {
1286 // Fill padding with undef value, where applicable.
1287 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1289 PassMode::Pair(..) => match op.val {
1295 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1297 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => match op.val {
1298 Ref(a, Some(b), _) => {
1303 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1308 // Force by-ref if we have to load through a cast pointer.
1309 let (mut llval, align, by_ref) = match op.val {
1310 Immediate(_) | Pair(..) => match arg.mode {
1311 PassMode::Indirect { .. } | PassMode::Cast(..) => {
1312 let scratch = PlaceRef::alloca(bx, arg.layout);
1313 op.val.store(bx, scratch);
1314 (scratch.llval, scratch.align, true)
1316 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1318 Ref(llval, _, align) => {
1319 if arg.is_indirect() && align < arg.layout.align.abi {
1320 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1321 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1322 // have scary latent bugs around.
1324 let scratch = PlaceRef::alloca(bx, arg.layout);
1334 (scratch.llval, scratch.align, true)
1336 (llval, align, true)
1341 if by_ref && !arg.is_indirect() {
1342 // Have to load the argument, maybe while casting it.
1343 if let PassMode::Cast(ty, _) = &arg.mode {
1344 let llty = bx.cast_backend_type(ty);
1345 let addr = bx.pointercast(llval, bx.type_ptr_to(llty));
1346 llval = bx.load(llty, addr, align.min(arg.layout.align.abi));
1348 // We can't use `PlaceRef::load` here because the argument
1349 // may have a type we don't treat as immediate, but the ABI
1350 // used for this call is passing it by-value. In that case,
1351 // the load would just produce `OperandValue::Ref` instead
1352 // of the `OperandValue::Immediate` we need for the call.
1353 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1354 if let abi::Abi::Scalar(scalar) = arg.layout.abi {
1355 if scalar.is_bool() {
1356 bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1359 // We store bools as `i8` so we need to truncate to `i1`.
1360 llval = bx.to_immediate(llval, arg.layout);
1367 fn codegen_arguments_untupled(
1370 operand: &mir::Operand<'tcx>,
1371 llargs: &mut Vec<Bx::Value>,
1372 args: &[ArgAbi<'tcx, Ty<'tcx>>],
1374 let tuple = self.codegen_operand(bx, operand);
1376 // Handle both by-ref and immediate tuples.
1377 if let Ref(llval, None, align) = tuple.val {
1378 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1379 for i in 0..tuple.layout.fields.count() {
1380 let field_ptr = tuple_ptr.project_field(bx, i);
1381 let field = bx.load_operand(field_ptr);
1382 self.codegen_argument(bx, field, llargs, &args[i]);
1384 } else if let Ref(_, Some(_), _) = tuple.val {
1385 bug!("closure arguments must be sized")
1387 // If the tuple is immediate, the elements are as well.
1388 for i in 0..tuple.layout.fields.count() {
1389 let op = tuple.extract_field(bx, i);
1390 self.codegen_argument(bx, op, llargs, &args[i]);
1393 tuple.layout.fields.count()
1396 fn get_caller_location(
1399 mut source_info: mir::SourceInfo,
1400 ) -> OperandRef<'tcx, Bx::Value> {
1403 let mut span_to_caller_location = |span: Span| {
1404 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1405 let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
1406 let const_loc = tcx.const_caller_location((
1407 Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
1409 caller.col_display as u32 + 1,
1411 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1414 // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
1415 // If so, the starting `source_info.span` is in the innermost inlined
1416 // function, and will be replaced with outer callsite spans as long
1417 // as the inlined functions were `#[track_caller]`.
1419 let scope_data = &self.mir.source_scopes[source_info.scope];
1421 if let Some((callee, callsite_span)) = scope_data.inlined {
1422 // Stop inside the most nested non-`#[track_caller]` function,
1423 // before ever reaching its caller (which is irrelevant).
1424 if !callee.def.requires_caller_location(tcx) {
1425 return span_to_caller_location(source_info.span);
1427 source_info.span = callsite_span;
1430 // Skip past all of the parents with `inlined: None`.
1431 match scope_data.inlined_parent_scope {
1432 Some(parent) => source_info.scope = parent,
1437 // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
1438 self.caller_location.unwrap_or_else(|| span_to_caller_location(source_info.span))
1441 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1443 if let Some(slot) = self.personality_slot {
1446 let layout = cx.layout_of(
1447 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1449 let slot = PlaceRef::alloca(bx, layout);
1450 self.personality_slot = Some(slot);
1455 /// Returns the landing/cleanup pad wrapper around the given basic block.
1456 // FIXME(eddyb) rename this to `eh_pad_for`.
1457 fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1458 if let Some(landing_pad) = self.landing_pads[bb] {
1462 let landing_pad = self.landing_pad_for_uncached(bb);
1463 self.landing_pads[bb] = Some(landing_pad);
1467 // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1468 fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1469 let llbb = self.llbb(bb);
1470 if base::wants_msvc_seh(self.cx.sess()) {
1473 match self.mir[bb].terminator.as_ref().map(|t| &t.kind) {
1474 // This is a basic block that we're aborting the program for,
1475 // notably in an `extern` function. These basic blocks are inserted
1476 // so that we assert that `extern` functions do indeed not panic,
1477 // and if they do we abort the process.
1479 // On MSVC these are tricky though (where we're doing funclets). If
1480 // we were to do a cleanuppad (like below) the normal functions like
1481 // `longjmp` would trigger the abort logic, terminating the
1482 // program. Instead we insert the equivalent of `catch(...)` for C++
1483 // which magically doesn't trigger when `longjmp` files over this
1486 // Lots more discussion can be found on #48251 but this codegen is
1487 // modeled after clang's for:
1494 Some(&mir::TerminatorKind::Abort) => {
1496 Bx::append_block(self.cx, self.llfn, &format!("cs_funclet{:?}", bb));
1498 Bx::append_block(self.cx, self.llfn, &format!("cp_funclet{:?}", bb));
1501 let mut cs_bx = Bx::build(self.cx, cs_llbb);
1502 let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1504 // The "null" here is actually a RTTI type descriptor for the
1505 // C++ personality function, but `catch (...)` has no type so
1506 // it's null. The 64 here is actually a bitfield which
1507 // represents that this is a catch-all block.
1508 let mut cp_bx = Bx::build(self.cx, cp_llbb);
1509 let null = cp_bx.const_null(
1510 cp_bx.type_i8p_ext(cp_bx.cx().data_layout().instruction_address_space),
1512 let sixty_four = cp_bx.const_i32(64);
1513 funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
1518 Bx::append_block(self.cx, self.llfn, &format!("funclet_{:?}", bb));
1519 ret_llbb = cleanup_llbb;
1520 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1521 funclet = cleanup_bx.cleanup_pad(None, &[]);
1522 cleanup_bx.br(llbb);
1525 self.funclets[bb] = Some(funclet);
1528 let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1529 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1531 let llpersonality = self.cx.eh_personality();
1532 let llretty = self.landing_pad_type();
1533 let lp = cleanup_bx.cleanup_landing_pad(llretty, llpersonality);
1535 let slot = self.get_personality_slot(&mut cleanup_bx);
1536 slot.storage_live(&mut cleanup_bx);
1537 Pair(cleanup_bx.extract_value(lp, 0), cleanup_bx.extract_value(lp, 1))
1538 .store(&mut cleanup_bx, slot);
1540 cleanup_bx.br(llbb);
1545 fn landing_pad_type(&self) -> Bx::Type {
1547 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1550 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1551 self.unreachable_block.unwrap_or_else(|| {
1552 let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1553 let mut bx = Bx::build(self.cx, llbb);
1555 self.unreachable_block = Some(llbb);
1560 fn double_unwind_guard(&mut self) -> Bx::BasicBlock {
1561 self.double_unwind_guard.unwrap_or_else(|| {
1562 assert!(!base::wants_msvc_seh(self.cx.sess()));
1564 let llbb = Bx::append_block(self.cx, self.llfn, "abort");
1565 let mut bx = Bx::build(self.cx, llbb);
1566 self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1568 let llpersonality = self.cx.eh_personality();
1569 let llretty = self.landing_pad_type();
1570 bx.cleanup_landing_pad(llretty, llpersonality);
1572 let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, LangItem::PanicNoUnwind);
1573 let fn_ty = bx.fn_decl_backend_type(&fn_abi);
1575 let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &[], None);
1576 bx.do_not_inline(llret);
1580 self.double_unwind_guard = Some(llbb);
1585 /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
1586 /// cached in `self.cached_llbbs`, or created on demand (and cached).
1587 // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
1588 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
1589 pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1590 self.cached_llbbs[bb].unwrap_or_else(|| {
1591 // FIXME(eddyb) only name the block if `fewer_names` is `false`.
1592 let llbb = Bx::append_block(self.cx, self.llfn, &format!("{:?}", bb));
1593 self.cached_llbbs[bb] = Some(llbb);
1598 fn make_return_dest(
1601 dest: mir::Place<'tcx>,
1602 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1603 llargs: &mut Vec<Bx::Value>,
1605 ) -> ReturnDest<'tcx, Bx::Value> {
1606 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1607 if fn_ret.is_ignore() {
1608 return ReturnDest::Nothing;
1610 let dest = if let Some(index) = dest.as_local() {
1611 match self.locals[index] {
1612 LocalRef::Place(dest) => dest,
1613 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1614 LocalRef::Operand(None) => {
1615 // Handle temporary places, specifically `Operand` ones, as
1616 // they don't have `alloca`s.
1617 return if fn_ret.is_indirect() {
1618 // Odd, but possible, case, we have an operand temporary,
1619 // but the calling convention has an indirect return.
1620 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1621 tmp.storage_live(bx);
1622 llargs.push(tmp.llval);
1623 ReturnDest::IndirectOperand(tmp, index)
1624 } else if is_intrinsic {
1625 // Currently, intrinsics always need a location to store
1626 // the result, so we create a temporary `alloca` for the
1628 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1629 tmp.storage_live(bx);
1630 ReturnDest::IndirectOperand(tmp, index)
1632 ReturnDest::DirectOperand(index)
1635 LocalRef::Operand(Some(_)) => {
1636 bug!("place local already assigned to");
1642 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1645 if fn_ret.is_indirect() {
1646 if dest.align < dest.layout.align.abi {
1647 // Currently, MIR code generation does not create calls
1648 // that store directly to fields of packed structs (in
1649 // fact, the calls it creates write only to temps).
1651 // If someone changes that, please update this code path
1652 // to create a temporary.
1653 span_bug!(self.mir.span, "can't directly store to unaligned value");
1655 llargs.push(dest.llval);
1658 ReturnDest::Store(dest)
1662 fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1663 if let Some(index) = dst.as_local() {
1664 match self.locals[index] {
1665 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1666 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1667 LocalRef::Operand(None) => {
1668 let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1669 assert!(!dst_layout.ty.has_erasable_regions());
1670 let place = PlaceRef::alloca(bx, dst_layout);
1671 place.storage_live(bx);
1672 self.codegen_transmute_into(bx, src, place);
1673 let op = bx.load_operand(place);
1674 place.storage_dead(bx);
1675 self.locals[index] = LocalRef::Operand(Some(op));
1676 self.debug_introduce_local(bx, index);
1678 LocalRef::Operand(Some(op)) => {
1679 assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1683 let dst = self.codegen_place(bx, dst.as_ref());
1684 self.codegen_transmute_into(bx, src, dst);
1688 fn codegen_transmute_into(
1691 src: &mir::Operand<'tcx>,
1692 dst: PlaceRef<'tcx, Bx::Value>,
1694 let src = self.codegen_operand(bx, src);
1696 // Special-case transmutes between scalars as simple bitcasts.
1697 match (src.layout.abi, dst.layout.abi) {
1698 (abi::Abi::Scalar(src_scalar), abi::Abi::Scalar(dst_scalar)) => {
1699 // HACK(eddyb) LLVM doesn't like `bitcast`s between pointers and non-pointers.
1700 if (src_scalar.primitive() == abi::Pointer)
1701 == (dst_scalar.primitive() == abi::Pointer)
1703 assert_eq!(src.layout.size, dst.layout.size);
1705 // NOTE(eddyb) the `from_immediate` and `to_immediate_scalar`
1706 // conversions allow handling `bool`s the same as `u8`s.
1707 let src = bx.from_immediate(src.immediate());
1708 let src_as_dst = bx.bitcast(src, bx.backend_type(dst.layout));
1709 Immediate(bx.to_immediate_scalar(src_as_dst, dst_scalar)).store(bx, dst);
1716 let llty = bx.backend_type(src.layout);
1717 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1718 let align = src.layout.align.abi.min(dst.align);
1719 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1722 // Stores the return value of a function call into it's final location.
1726 dest: ReturnDest<'tcx, Bx::Value>,
1727 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1730 use self::ReturnDest::*;
1734 Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1735 IndirectOperand(tmp, index) => {
1736 let op = bx.load_operand(tmp);
1737 tmp.storage_dead(bx);
1738 self.locals[index] = LocalRef::Operand(Some(op));
1739 self.debug_introduce_local(bx, index);
1741 DirectOperand(index) => {
1742 // If there is a cast, we have to store and reload.
1743 let op = if let PassMode::Cast(..) = ret_abi.mode {
1744 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1745 tmp.storage_live(bx);
1746 bx.store_arg(&ret_abi, llval, tmp);
1747 let op = bx.load_operand(tmp);
1748 tmp.storage_dead(bx);
1751 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1753 self.locals[index] = LocalRef::Operand(Some(op));
1754 self.debug_introduce_local(bx, index);
1760 enum ReturnDest<'tcx, V> {
1761 // Do nothing; the return value is indirect or ignored.
1763 // Store the return value to the pointer.
1764 Store(PlaceRef<'tcx, V>),
1765 // Store an indirect return value to an operand local place.
1766 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1767 // Store a direct return value to an operand local place.
1768 DirectOperand(mir::Local),