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