1use std::cmp;
2
3use rustc_abi::{Align, BackendRepr, ExternAbi, HasDataLayout, Reg, Size, WrappingRange};
4use rustc_ast as ast;
5use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
6use rustc_data_structures::packed::Pu128;
7use rustc_hir::lang_items::LangItem;
8use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
9use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
10use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
11use rustc_middle::ty::{self, Instance, Ty};
12use rustc_middle::{bug, span_bug};
13use rustc_session::config::OptLevel;
14use rustc_span::Span;
15use rustc_span::source_map::Spanned;
16use rustc_target::callconv::{ArgAbi, CastTarget, FnAbi, PassMode};
17use tracing::{debug, info};
18
19use super::operand::OperandRef;
20use super::operand::OperandValue::{Immediate, Pair, Ref, ZeroSized};
21use super::place::{PlaceRef, PlaceValue};
22use super::{CachedLlbb, FunctionCx, LocalRef};
23use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
24use crate::common::{self, IntPredicate};
25use crate::errors::CompilerBuiltinsCannotCall;
26use crate::traits::*;
27use crate::{MemFlags, meth};
28
29#[derive(Debug, PartialEq)]
33enum MergingSucc {
34 False,
35 True,
36}
37
38#[derive(Debug, PartialEq)]
41enum CallKind {
42 Normal,
43 Tail,
44}
45
46struct TerminatorCodegenHelper<'tcx> {
49 bb: mir::BasicBlock,
50 terminator: &'tcx mir::Terminator<'tcx>,
51}
52
53impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
54 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
57 &self,
58 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
59 ) -> Option<&'b Bx::Funclet> {
60 let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
61 let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
62 if fx.funclets[funclet_bb].is_none() {
71 fx.landing_pad_for(funclet_bb);
72 }
73 Some(
74 fx.funclets[funclet_bb]
75 .as_ref()
76 .expect("landing_pad_for didn't also create funclets entry"),
77 )
78 }
79
80 fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
83 &self,
84 fx: &mut FunctionCx<'a, 'tcx, Bx>,
85 target: mir::BasicBlock,
86 ) -> Bx::BasicBlock {
87 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
88 let mut lltarget = fx.llbb(target);
89 if needs_landing_pad {
90 lltarget = fx.landing_pad_for(target);
91 }
92 if is_cleanupret {
93 assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess));
95 debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
96 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
97 let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
98 let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
99 trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
100 trampoline_llbb
101 } else {
102 lltarget
103 }
104 }
105
106 fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
107 &self,
108 fx: &mut FunctionCx<'a, 'tcx, Bx>,
109 target: mir::BasicBlock,
110 ) -> (bool, bool) {
111 if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
112 let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
113 let target_funclet = cleanup_kinds[target].funclet_bb(target);
114 let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
115 (None, None) => (false, false),
116 (None, Some(_)) => (true, false),
117 (Some(f), Some(t_f)) => (f != t_f, f != t_f),
118 (Some(_), None) => {
119 let span = self.terminator.source_info.span;
120 span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
121 }
122 };
123 (needs_landing_pad, is_cleanupret)
124 } else {
125 let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
126 let is_cleanupret = false;
127 (needs_landing_pad, is_cleanupret)
128 }
129 }
130
131 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
132 &self,
133 fx: &mut FunctionCx<'a, 'tcx, Bx>,
134 bx: &mut Bx,
135 target: mir::BasicBlock,
136 mergeable_succ: bool,
137 ) -> MergingSucc {
138 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
139 if mergeable_succ && !needs_landing_pad && !is_cleanupret {
140 MergingSucc::True
142 } else {
143 let mut lltarget = fx.llbb(target);
144 if needs_landing_pad {
145 lltarget = fx.landing_pad_for(target);
146 }
147 if is_cleanupret {
148 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
151 } else {
152 bx.br(lltarget);
153 }
154 MergingSucc::False
155 }
156 }
157
158 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
161 &self,
162 fx: &mut FunctionCx<'a, 'tcx, Bx>,
163 bx: &mut Bx,
164 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
165 fn_ptr: Bx::Value,
166 llargs: &[Bx::Value],
167 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
168 mut unwind: mir::UnwindAction,
169 lifetime_ends_after_call: &[(Bx::Value, Size)],
170 instance: Option<Instance<'tcx>>,
171 kind: CallKind,
172 mergeable_succ: bool,
173 ) -> MergingSucc {
174 let tcx = bx.tcx();
175 if let Some(instance) = instance
176 && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
177 {
178 if destination.is_some() {
179 let caller_def = fx.instance.def_id();
180 let e = CompilerBuiltinsCannotCall {
181 span: tcx.def_span(caller_def),
182 caller: with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
183 callee: with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
184 };
185 tcx.dcx().emit_err(e);
186 } else {
187 info!(
188 "compiler_builtins call to diverging function {:?} replaced with abort",
189 instance.def_id()
190 );
191 bx.abort();
192 bx.unreachable();
193 return MergingSucc::False;
194 }
195 }
196
197 let fn_ty = bx.fn_decl_backend_type(fn_abi);
200
201 let fn_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
202 Some(bx.tcx().codegen_fn_attrs(fx.instance.def_id()))
203 } else {
204 None
205 };
206
207 if !fn_abi.can_unwind {
208 unwind = mir::UnwindAction::Unreachable;
209 }
210
211 let unwind_block = match unwind {
212 mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
213 mir::UnwindAction::Continue => None,
214 mir::UnwindAction::Unreachable => None,
215 mir::UnwindAction::Terminate(reason) => {
216 if fx.mir[self.bb].is_cleanup && base::wants_new_eh_instructions(fx.cx.tcx().sess) {
217 None
227 } else {
228 Some(fx.terminate_block(reason))
229 }
230 }
231 };
232
233 if kind == CallKind::Tail {
234 bx.tail_call(fn_ty, fn_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
235 return MergingSucc::False;
236 }
237
238 if let Some(unwind_block) = unwind_block {
239 let ret_llbb = if let Some((_, target)) = destination {
240 fx.llbb(target)
241 } else {
242 fx.unreachable_block()
243 };
244 let invokeret = bx.invoke(
245 fn_ty,
246 fn_attrs,
247 Some(fn_abi),
248 fn_ptr,
249 llargs,
250 ret_llbb,
251 unwind_block,
252 self.funclet(fx),
253 instance,
254 );
255 if fx.mir[self.bb].is_cleanup {
256 bx.apply_attrs_to_cleanup_callsite(invokeret);
257 }
258
259 if let Some((ret_dest, target)) = destination {
260 bx.switch_to_block(fx.llbb(target));
261 fx.set_debug_loc(bx, self.terminator.source_info);
262 for &(tmp, size) in lifetime_ends_after_call {
263 bx.lifetime_end(tmp, size);
264 }
265 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
266 }
267 MergingSucc::False
268 } else {
269 let llret =
270 bx.call(fn_ty, fn_attrs, Some(fn_abi), fn_ptr, llargs, self.funclet(fx), instance);
271 if fx.mir[self.bb].is_cleanup {
272 bx.apply_attrs_to_cleanup_callsite(llret);
273 }
274
275 if let Some((ret_dest, target)) = destination {
276 for &(tmp, size) in lifetime_ends_after_call {
277 bx.lifetime_end(tmp, size);
278 }
279 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
280 self.funclet_br(fx, bx, target, mergeable_succ)
281 } else {
282 bx.unreachable();
283 MergingSucc::False
284 }
285 }
286 }
287
288 fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
290 &self,
291 fx: &mut FunctionCx<'a, 'tcx, Bx>,
292 bx: &mut Bx,
293 template: &[InlineAsmTemplatePiece],
294 operands: &[InlineAsmOperandRef<'tcx, Bx>],
295 options: InlineAsmOptions,
296 line_spans: &[Span],
297 destination: Option<mir::BasicBlock>,
298 unwind: mir::UnwindAction,
299 instance: Instance<'_>,
300 mergeable_succ: bool,
301 ) -> MergingSucc {
302 let unwind_target = match unwind {
303 mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
304 mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason)),
305 mir::UnwindAction::Continue => None,
306 mir::UnwindAction::Unreachable => None,
307 };
308
309 if operands.iter().any(|x| matches!(x, InlineAsmOperandRef::Label { .. })) {
310 assert!(unwind_target.is_none());
311 let ret_llbb = if let Some(target) = destination {
312 fx.llbb(target)
313 } else {
314 fx.unreachable_block()
315 };
316
317 bx.codegen_inline_asm(
318 template,
319 operands,
320 options,
321 line_spans,
322 instance,
323 Some(ret_llbb),
324 None,
325 );
326 MergingSucc::False
327 } else if let Some(cleanup) = unwind_target {
328 let ret_llbb = if let Some(target) = destination {
329 fx.llbb(target)
330 } else {
331 fx.unreachable_block()
332 };
333
334 bx.codegen_inline_asm(
335 template,
336 operands,
337 options,
338 line_spans,
339 instance,
340 Some(ret_llbb),
341 Some((cleanup, self.funclet(fx))),
342 );
343 MergingSucc::False
344 } else {
345 bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
346
347 if let Some(target) = destination {
348 self.funclet_br(fx, bx, target, mergeable_succ)
349 } else {
350 bx.unreachable();
351 MergingSucc::False
352 }
353 }
354 }
355}
356
357impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
359 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
361 if let Some(funclet) = helper.funclet(self) {
362 bx.cleanup_ret(funclet, None);
363 } else {
364 let slot = self.get_personality_slot(bx);
365 let exn0 = slot.project_field(bx, 0);
366 let exn0 = bx.load_operand(exn0).immediate();
367 let exn1 = slot.project_field(bx, 1);
368 let exn1 = bx.load_operand(exn1).immediate();
369 slot.storage_dead(bx);
370
371 bx.resume(exn0, exn1);
372 }
373 }
374
375 fn codegen_switchint_terminator(
376 &mut self,
377 helper: TerminatorCodegenHelper<'tcx>,
378 bx: &mut Bx,
379 discr: &mir::Operand<'tcx>,
380 targets: &SwitchTargets,
381 ) {
382 let discr = self.codegen_operand(bx, discr);
383 let discr_value = discr.immediate();
384 let switch_ty = discr.layout.ty;
385 if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
387 let target = targets.target_for_value(const_discr);
388 bx.br(helper.llbb_with_cleanup(self, target));
389 return;
390 };
391
392 let mut target_iter = targets.iter();
393 if target_iter.len() == 1 {
394 let (test_value, target) = target_iter.next().unwrap();
397 let otherwise = targets.otherwise();
398 let lltarget = helper.llbb_with_cleanup(self, target);
399 let llotherwise = helper.llbb_with_cleanup(self, otherwise);
400 let target_cold = self.cold_blocks[target];
401 let otherwise_cold = self.cold_blocks[otherwise];
402 let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
406 if switch_ty == bx.tcx().types.bool {
407 match test_value {
409 0 => {
410 let expect = expect.map(|e| !e);
411 bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
412 }
413 1 => {
414 bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
415 }
416 _ => bug!(),
417 }
418 } else {
419 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
420 let llval = bx.const_uint_big(switch_llty, test_value);
421 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
422 bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
423 }
424 } else if target_iter.len() == 2
425 && self.mir[targets.otherwise()].is_empty_unreachable()
426 && targets.all_values().contains(&Pu128(0))
427 && targets.all_values().contains(&Pu128(1))
428 {
429 let true_bb = targets.target_for_value(1);
433 let false_bb = targets.target_for_value(0);
434 let true_ll = helper.llbb_with_cleanup(self, true_bb);
435 let false_ll = helper.llbb_with_cleanup(self, false_bb);
436
437 let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
438 None
439 } else {
440 match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
441 (true, true) | (false, false) => None,
443 (true, false) => Some(false),
445 (false, true) => Some(true),
446 }
447 };
448
449 let bool_ty = bx.tcx().types.bool;
450 let cond = if switch_ty == bool_ty {
451 discr_value
452 } else {
453 let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
454 bx.unchecked_utrunc(discr_value, bool_llty)
455 };
456 bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
457 } else if self.cx.sess().opts.optimize == OptLevel::No
458 && target_iter.len() == 2
459 && self.mir[targets.otherwise()].is_empty_unreachable()
460 {
461 let (test_value1, target1) = target_iter.next().unwrap();
474 let (_test_value2, target2) = target_iter.next().unwrap();
475 let ll1 = helper.llbb_with_cleanup(self, target1);
476 let ll2 = helper.llbb_with_cleanup(self, target2);
477 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
478 let llval = bx.const_uint_big(switch_llty, test_value1);
479 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
480 bx.cond_br(cmp, ll1, ll2);
481 } else {
482 let otherwise = targets.otherwise();
483 let otherwise_cold = self.cold_blocks[otherwise];
484 let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
485 let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
486 let none_cold = cold_count == 0;
487 let all_cold = cold_count == targets.iter().len();
488 if (none_cold && (!otherwise_cold || otherwise_unreachable))
489 || (all_cold && (otherwise_cold || otherwise_unreachable))
490 {
491 bx.switch(
494 discr_value,
495 helper.llbb_with_cleanup(self, targets.otherwise()),
496 target_iter
497 .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
498 );
499 } else {
500 bx.switch_with_weights(
502 discr_value,
503 helper.llbb_with_cleanup(self, targets.otherwise()),
504 otherwise_cold,
505 target_iter.map(|(value, target)| {
506 (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
507 }),
508 );
509 }
510 }
511 }
512
513 fn codegen_return_terminator(&mut self, bx: &mut Bx) {
514 if self.fn_abi.c_variadic {
516 let va_list_arg_idx = self.fn_abi.args.len();
518 match self.locals[mir::Local::from_usize(1 + va_list_arg_idx)] {
519 LocalRef::Place(va_list) => {
520 bx.va_end(va_list.val.llval);
521 }
522 _ => bug!("C-variadic function must have a `VaList` place"),
523 }
524 }
525 if self.fn_abi.ret.layout.is_uninhabited() {
526 bx.abort();
531 bx.unreachable();
534 return;
535 }
536 let llval = match &self.fn_abi.ret.mode {
537 PassMode::Ignore | PassMode::Indirect { .. } => {
538 bx.ret_void();
539 return;
540 }
541
542 PassMode::Direct(_) | PassMode::Pair(..) => {
543 let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
544 if let Ref(place_val) = op.val {
545 bx.load_from_place(bx.backend_type(op.layout), place_val)
546 } else {
547 op.immediate_or_packed_pair(bx)
548 }
549 }
550
551 PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
552 let op = match self.locals[mir::RETURN_PLACE] {
553 LocalRef::Operand(op) => op,
554 LocalRef::PendingOperand => bug!("use of return before def"),
555 LocalRef::Place(cg_place) => {
556 OperandRef { val: Ref(cg_place.val), layout: cg_place.layout }
557 }
558 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
559 };
560 let llslot = match op.val {
561 Immediate(_) | Pair(..) => {
562 let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
563 op.val.store(bx, scratch);
564 scratch.val.llval
565 }
566 Ref(place_val) => {
567 assert_eq!(
568 place_val.align, op.layout.align.abi,
569 "return place is unaligned!"
570 );
571 place_val.llval
572 }
573 ZeroSized => bug!("ZST return value shouldn't be in PassMode::Cast"),
574 };
575 load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
576 }
577 };
578 bx.ret(llval);
579 }
580
581 #[tracing::instrument(level = "trace", skip(self, helper, bx))]
582 fn codegen_drop_terminator(
583 &mut self,
584 helper: TerminatorCodegenHelper<'tcx>,
585 bx: &mut Bx,
586 source_info: &mir::SourceInfo,
587 location: mir::Place<'tcx>,
588 target: mir::BasicBlock,
589 unwind: mir::UnwindAction,
590 mergeable_succ: bool,
591 ) -> MergingSucc {
592 let ty = location.ty(self.mir, bx.tcx()).ty;
593 let ty = self.monomorphize(ty);
594 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
595
596 if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
597 return helper.funclet_br(self, bx, target, mergeable_succ);
599 }
600
601 let place = self.codegen_place(bx, location.as_ref());
602 let (args1, args2);
603 let mut args = if let Some(llextra) = place.val.llextra {
604 args2 = [place.val.llval, llextra];
605 &args2[..]
606 } else {
607 args1 = [place.val.llval];
608 &args1[..]
609 };
610 let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
611 ty::Dynamic(_, _, ty::Dyn) => {
614 let virtual_drop = Instance {
627 def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), args: drop_fn.args,
629 };
630 debug!("ty = {:?}", ty);
631 debug!("drop_fn = {:?}", drop_fn);
632 debug!("args = {:?}", args);
633 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
634 let vtable = args[1];
635 args = &args[..1];
637 (
638 true,
639 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
640 .get_optional_fn(bx, vtable, ty, fn_abi),
641 fn_abi,
642 virtual_drop,
643 )
644 }
645 _ => (
646 false,
647 bx.get_fn_addr(drop_fn),
648 bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
649 drop_fn,
650 ),
651 };
652
653 if maybe_null {
656 let is_not_null = bx.append_sibling_block("is_not_null");
657 let llty = bx.fn_ptr_backend_type(fn_abi);
658 let null = bx.const_null(llty);
659 let non_null =
660 bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
661 bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
662 bx.switch_to_block(is_not_null);
663 self.set_debug_loc(bx, *source_info);
664 }
665
666 helper.do_call(
667 self,
668 bx,
669 fn_abi,
670 drop_fn,
671 args,
672 Some((ReturnDest::Nothing, target)),
673 unwind,
674 &[],
675 Some(drop_instance),
676 CallKind::Normal,
677 !maybe_null && mergeable_succ,
678 )
679 }
680
681 fn codegen_assert_terminator(
682 &mut self,
683 helper: TerminatorCodegenHelper<'tcx>,
684 bx: &mut Bx,
685 terminator: &mir::Terminator<'tcx>,
686 cond: &mir::Operand<'tcx>,
687 expected: bool,
688 msg: &mir::AssertMessage<'tcx>,
689 target: mir::BasicBlock,
690 unwind: mir::UnwindAction,
691 mergeable_succ: bool,
692 ) -> MergingSucc {
693 let span = terminator.source_info.span;
694 let cond = self.codegen_operand(bx, cond).immediate();
695 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
696
697 if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
702 const_cond = Some(expected);
703 }
704
705 if const_cond == Some(expected) {
707 return helper.funclet_br(self, bx, target, mergeable_succ);
708 }
709
710 let lltarget = helper.llbb_with_cleanup(self, target);
715 let panic_block = bx.append_sibling_block("panic");
716 if expected {
717 bx.cond_br(cond, lltarget, panic_block);
718 } else {
719 bx.cond_br(cond, panic_block, lltarget);
720 }
721
722 bx.switch_to_block(panic_block);
724 self.set_debug_loc(bx, terminator.source_info);
725
726 let location = self.get_caller_location(bx, terminator.source_info).immediate();
728
729 let (lang_item, args) = match msg {
731 AssertKind::BoundsCheck { len, index } => {
732 let len = self.codegen_operand(bx, len).immediate();
733 let index = self.codegen_operand(bx, index).immediate();
734 (LangItem::PanicBoundsCheck, vec![index, len, location])
737 }
738 AssertKind::MisalignedPointerDereference { required, found } => {
739 let required = self.codegen_operand(bx, required).immediate();
740 let found = self.codegen_operand(bx, found).immediate();
741 (LangItem::PanicMisalignedPointerDereference, vec![required, found, location])
744 }
745 AssertKind::NullPointerDereference => {
746 (LangItem::PanicNullPointerDereference, vec![location])
749 }
750 AssertKind::InvalidEnumConstruction(source) => {
751 let source = self.codegen_operand(bx, source).immediate();
752 (LangItem::PanicInvalidEnumConstruction, vec![source, location])
755 }
756 _ => {
757 (msg.panic_function(), vec![location])
759 }
760 };
761
762 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
763
764 let merging_succ = helper.do_call(
766 self,
767 bx,
768 fn_abi,
769 llfn,
770 &args,
771 None,
772 unwind,
773 &[],
774 Some(instance),
775 CallKind::Normal,
776 false,
777 );
778 assert_eq!(merging_succ, MergingSucc::False);
779 MergingSucc::False
780 }
781
782 fn codegen_terminate_terminator(
783 &mut self,
784 helper: TerminatorCodegenHelper<'tcx>,
785 bx: &mut Bx,
786 terminator: &mir::Terminator<'tcx>,
787 reason: UnwindTerminateReason,
788 ) {
789 let span = terminator.source_info.span;
790 self.set_debug_loc(bx, terminator.source_info);
791
792 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
794
795 let merging_succ = helper.do_call(
797 self,
798 bx,
799 fn_abi,
800 llfn,
801 &[],
802 None,
803 mir::UnwindAction::Unreachable,
804 &[],
805 Some(instance),
806 CallKind::Normal,
807 false,
808 );
809 assert_eq!(merging_succ, MergingSucc::False);
810 }
811
812 fn codegen_panic_intrinsic(
814 &mut self,
815 helper: &TerminatorCodegenHelper<'tcx>,
816 bx: &mut Bx,
817 intrinsic: ty::IntrinsicDef,
818 instance: Instance<'tcx>,
819 source_info: mir::SourceInfo,
820 target: Option<mir::BasicBlock>,
821 unwind: mir::UnwindAction,
822 mergeable_succ: bool,
823 ) -> Option<MergingSucc> {
824 let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
828 return None;
829 };
830
831 let ty = instance.args.type_at(0);
832
833 let is_valid = bx
834 .tcx()
835 .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
836 .expect("expect to have layout during codegen");
837
838 if is_valid {
839 let target = target.unwrap();
841 return Some(helper.funclet_br(self, bx, target, mergeable_succ));
842 }
843
844 let layout = bx.layout_of(ty);
845
846 let msg_str = with_no_visible_paths!({
847 with_no_trimmed_paths!({
848 if layout.is_uninhabited() {
849 format!("attempted to instantiate uninhabited type `{ty}`")
851 } else if requirement == ValidityRequirement::Zero {
852 format!("attempted to zero-initialize type `{ty}`, which is invalid")
853 } else {
854 format!("attempted to leave type `{ty}` uninitialized, which is invalid")
855 }
856 })
857 });
858 let msg = bx.const_str(&msg_str);
859
860 let (fn_abi, llfn, instance) =
862 common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
863
864 Some(helper.do_call(
866 self,
867 bx,
868 fn_abi,
869 llfn,
870 &[msg.0, msg.1],
871 target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
872 unwind,
873 &[],
874 Some(instance),
875 CallKind::Normal,
876 mergeable_succ,
877 ))
878 }
879
880 fn codegen_call_terminator(
881 &mut self,
882 helper: TerminatorCodegenHelper<'tcx>,
883 bx: &mut Bx,
884 terminator: &mir::Terminator<'tcx>,
885 func: &mir::Operand<'tcx>,
886 args: &[Spanned<mir::Operand<'tcx>>],
887 destination: mir::Place<'tcx>,
888 target: Option<mir::BasicBlock>,
889 unwind: mir::UnwindAction,
890 fn_span: Span,
891 kind: CallKind,
892 mergeable_succ: bool,
893 ) -> MergingSucc {
894 let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
895
896 let callee = self.codegen_operand(bx, func);
898
899 let (instance, mut llfn) = match *callee.layout.ty.kind() {
900 ty::FnDef(def_id, generic_args) => {
901 let instance = ty::Instance::expect_resolve(
902 bx.tcx(),
903 bx.typing_env(),
904 def_id,
905 generic_args,
906 fn_span,
907 );
908
909 let instance = match instance.def {
910 ty::InstanceKind::DropGlue(_, None) => {
913 let target = target.unwrap();
915 return helper.funclet_br(self, bx, target, mergeable_succ);
916 }
917 ty::InstanceKind::Intrinsic(def_id) => {
918 let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
919 if let Some(merging_succ) = self.codegen_panic_intrinsic(
920 &helper,
921 bx,
922 intrinsic,
923 instance,
924 source_info,
925 target,
926 unwind,
927 mergeable_succ,
928 ) {
929 return merging_succ;
930 }
931
932 let result_layout =
933 self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
934
935 let (result, store_in_local) = if result_layout.is_zst() {
936 (
937 PlaceRef::new_sized(bx.const_undef(bx.type_ptr()), result_layout),
938 None,
939 )
940 } else if let Some(local) = destination.as_local() {
941 match self.locals[local] {
942 LocalRef::Place(dest) => (dest, None),
943 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
944 LocalRef::PendingOperand => {
945 let tmp = PlaceRef::alloca(bx, result_layout);
949 tmp.storage_live(bx);
950 (tmp, Some(local))
951 }
952 LocalRef::Operand(_) => {
953 bug!("place local already assigned to");
954 }
955 }
956 } else {
957 (self.codegen_place(bx, destination.as_ref()), None)
958 };
959
960 if result.val.align < result.layout.align.abi {
961 span_bug!(self.mir.span, "can't directly store to unaligned value");
968 }
969
970 let args: Vec<_> =
971 args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
972
973 match self.codegen_intrinsic_call(bx, instance, &args, result, source_info)
974 {
975 Ok(()) => {
976 if let Some(local) = store_in_local {
977 let op = bx.load_operand(result);
978 result.storage_dead(bx);
979 self.overwrite_local(local, LocalRef::Operand(op));
980 self.debug_introduce_local(bx, local);
981 }
982
983 return if let Some(target) = target {
984 helper.funclet_br(self, bx, target, mergeable_succ)
985 } else {
986 bx.unreachable();
987 MergingSucc::False
988 };
989 }
990 Err(instance) => {
991 if intrinsic.must_be_overridden {
992 span_bug!(
993 fn_span,
994 "intrinsic {} must be overridden by codegen backend, but isn't",
995 intrinsic.name,
996 );
997 }
998 instance
999 }
1000 }
1001 }
1002 _ => instance,
1003 };
1004
1005 (Some(instance), None)
1006 }
1007 ty::FnPtr(..) => (None, Some(callee.immediate())),
1008 _ => bug!("{} is not callable", callee.layout.ty),
1009 };
1010
1011 let sig = callee.layout.ty.fn_sig(bx.tcx());
1015
1016 let extra_args = &args[sig.inputs().skip_binder().len()..];
1017 let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1018 let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1019 self.monomorphize(op_ty)
1020 }));
1021
1022 let fn_abi = match instance {
1023 Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1024 None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1025 };
1026
1027 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1029
1030 let mut llargs = Vec::with_capacity(arg_count);
1031
1032 let destination = match kind {
1036 CallKind::Normal => {
1037 let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1038 target.map(|target| (return_dest, target))
1039 }
1040 CallKind::Tail => None,
1041 };
1042
1043 let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1045 && let Some((tup, args)) = args.split_last()
1046 {
1047 (args, Some(tup))
1048 } else {
1049 (args, None)
1050 };
1051
1052 let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1056 'make_args: for (i, arg) in first_args.iter().enumerate() {
1057 if kind == CallKind::Tail && matches!(fn_abi.args[i].mode, PassMode::Indirect { .. }) {
1058 span_bug!(
1060 fn_span,
1061 "arguments using PassMode::Indirect are currently not supported for tail calls"
1062 );
1063 }
1064
1065 let mut op = self.codegen_operand(bx, &arg.node);
1066
1067 if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1068 match op.val {
1069 Pair(data_ptr, meta) => {
1070 while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1080 let (idx, _) = op.layout.non_1zst_field(bx).expect(
1081 "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1082 );
1083 op = op.extract_field(self, bx, idx.as_usize());
1084 }
1085
1086 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1090 bx,
1091 meta,
1092 op.layout.ty,
1093 fn_abi,
1094 ));
1095 llargs.push(data_ptr);
1096 continue 'make_args;
1097 }
1098 Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1099 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1101 bx,
1102 meta,
1103 op.layout.ty,
1104 fn_abi,
1105 ));
1106 llargs.push(data_ptr);
1107 continue;
1108 }
1109 _ => {
1110 span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1111 }
1112 }
1113 }
1114
1115 match (&arg.node, op.val) {
1118 (&mir::Operand::Copy(_), Ref(PlaceValue { llextra: None, .. }))
1119 | (&mir::Operand::Constant(_), Ref(PlaceValue { llextra: None, .. })) => {
1120 let tmp = PlaceRef::alloca(bx, op.layout);
1121 bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1122 op.val.store(bx, tmp);
1123 op.val = Ref(tmp.val);
1124 lifetime_ends_after_call.push((tmp.val.llval, tmp.layout.size));
1125 }
1126 _ => {}
1127 }
1128
1129 self.codegen_argument(
1130 bx,
1131 op,
1132 &mut llargs,
1133 &fn_abi.args[i],
1134 &mut lifetime_ends_after_call,
1135 );
1136 }
1137 let num_untupled = untuple.map(|tup| {
1138 self.codegen_arguments_untupled(
1139 bx,
1140 &tup.node,
1141 &mut llargs,
1142 &fn_abi.args[first_args.len()..],
1143 &mut lifetime_ends_after_call,
1144 )
1145 });
1146
1147 let needs_location =
1148 instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1149 if needs_location {
1150 let mir_args = if let Some(num_untupled) = num_untupled {
1151 first_args.len() + num_untupled
1152 } else {
1153 args.len()
1154 };
1155 assert_eq!(
1156 fn_abi.args.len(),
1157 mir_args + 1,
1158 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1159 );
1160 let location = self.get_caller_location(bx, source_info);
1161 debug!(
1162 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1163 terminator, location, fn_span
1164 );
1165
1166 let last_arg = fn_abi.args.last().unwrap();
1167 self.codegen_argument(
1168 bx,
1169 location,
1170 &mut llargs,
1171 last_arg,
1172 &mut lifetime_ends_after_call,
1173 );
1174 }
1175
1176 let fn_ptr = match (instance, llfn) {
1177 (Some(instance), None) => bx.get_fn_addr(instance),
1178 (_, Some(llfn)) => llfn,
1179 _ => span_bug!(fn_span, "no instance or llfn for call"),
1180 };
1181 self.set_debug_loc(bx, source_info);
1182 helper.do_call(
1183 self,
1184 bx,
1185 fn_abi,
1186 fn_ptr,
1187 &llargs,
1188 destination,
1189 unwind,
1190 &lifetime_ends_after_call,
1191 instance,
1192 kind,
1193 mergeable_succ,
1194 )
1195 }
1196
1197 fn codegen_asm_terminator(
1198 &mut self,
1199 helper: TerminatorCodegenHelper<'tcx>,
1200 bx: &mut Bx,
1201 asm_macro: InlineAsmMacro,
1202 terminator: &mir::Terminator<'tcx>,
1203 template: &[ast::InlineAsmTemplatePiece],
1204 operands: &[mir::InlineAsmOperand<'tcx>],
1205 options: ast::InlineAsmOptions,
1206 line_spans: &[Span],
1207 targets: &[mir::BasicBlock],
1208 unwind: mir::UnwindAction,
1209 instance: Instance<'_>,
1210 mergeable_succ: bool,
1211 ) -> MergingSucc {
1212 let span = terminator.source_info.span;
1213
1214 let operands: Vec<_> = operands
1215 .iter()
1216 .map(|op| match *op {
1217 mir::InlineAsmOperand::In { reg, ref value } => {
1218 let value = self.codegen_operand(bx, value);
1219 InlineAsmOperandRef::In { reg, value }
1220 }
1221 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1222 let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1223 InlineAsmOperandRef::Out { reg, late, place }
1224 }
1225 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1226 let in_value = self.codegen_operand(bx, in_value);
1227 let out_place =
1228 out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1229 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1230 }
1231 mir::InlineAsmOperand::Const { ref value } => {
1232 let const_value = self.eval_mir_constant(value);
1233 let string = common::asm_const_to_str(
1234 bx.tcx(),
1235 span,
1236 const_value,
1237 bx.layout_of(value.ty()),
1238 );
1239 InlineAsmOperandRef::Const { string }
1240 }
1241 mir::InlineAsmOperand::SymFn { ref value } => {
1242 let const_ = self.monomorphize(value.const_);
1243 if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1244 let instance = ty::Instance::resolve_for_fn_ptr(
1245 bx.tcx(),
1246 bx.typing_env(),
1247 def_id,
1248 args,
1249 )
1250 .unwrap();
1251 InlineAsmOperandRef::SymFn { instance }
1252 } else {
1253 span_bug!(span, "invalid type for asm sym (fn)");
1254 }
1255 }
1256 mir::InlineAsmOperand::SymStatic { def_id } => {
1257 InlineAsmOperandRef::SymStatic { def_id }
1258 }
1259 mir::InlineAsmOperand::Label { target_index } => {
1260 InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1261 }
1262 })
1263 .collect();
1264
1265 helper.do_inlineasm(
1266 self,
1267 bx,
1268 template,
1269 &operands,
1270 options,
1271 line_spans,
1272 if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1273 unwind,
1274 instance,
1275 mergeable_succ,
1276 )
1277 }
1278
1279 pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1280 let llbb = match self.try_llbb(bb) {
1281 Some(llbb) => llbb,
1282 None => return,
1283 };
1284 let bx = &mut Bx::build(self.cx, llbb);
1285 let mir = self.mir;
1286
1287 loop {
1291 let data = &mir[bb];
1292
1293 debug!("codegen_block({:?}={:?})", bb, data);
1294
1295 for statement in &data.statements {
1296 self.codegen_statement(bx, statement);
1297 }
1298
1299 let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1300 if let MergingSucc::False = merging_succ {
1301 break;
1302 }
1303
1304 let mut successors = data.terminator().successors();
1312 let succ = successors.next().unwrap();
1313 assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1314 self.cached_llbbs[succ] = CachedLlbb::Skip;
1315 bb = succ;
1316 }
1317 }
1318
1319 pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1320 let llbb = match self.try_llbb(bb) {
1321 Some(llbb) => llbb,
1322 None => return,
1323 };
1324 let bx = &mut Bx::build(self.cx, llbb);
1325 debug!("codegen_block_as_unreachable({:?})", bb);
1326 bx.unreachable();
1327 }
1328
1329 fn codegen_terminator(
1330 &mut self,
1331 bx: &mut Bx,
1332 bb: mir::BasicBlock,
1333 terminator: &'tcx mir::Terminator<'tcx>,
1334 ) -> MergingSucc {
1335 debug!("codegen_terminator: {:?}", terminator);
1336
1337 let helper = TerminatorCodegenHelper { bb, terminator };
1338
1339 let mergeable_succ = || {
1340 let mut successors = terminator.successors();
1343 if let Some(succ) = successors.next()
1344 && successors.next().is_none()
1345 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1346 {
1347 assert_eq!(succ_pred, bb);
1350 true
1351 } else {
1352 false
1353 }
1354 };
1355
1356 self.set_debug_loc(bx, terminator.source_info);
1357 match terminator.kind {
1358 mir::TerminatorKind::UnwindResume => {
1359 self.codegen_resume_terminator(helper, bx);
1360 MergingSucc::False
1361 }
1362
1363 mir::TerminatorKind::UnwindTerminate(reason) => {
1364 self.codegen_terminate_terminator(helper, bx, terminator, reason);
1365 MergingSucc::False
1366 }
1367
1368 mir::TerminatorKind::Goto { target } => {
1369 helper.funclet_br(self, bx, target, mergeable_succ())
1370 }
1371
1372 mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1373 self.codegen_switchint_terminator(helper, bx, discr, targets);
1374 MergingSucc::False
1375 }
1376
1377 mir::TerminatorKind::Return => {
1378 self.codegen_return_terminator(bx);
1379 MergingSucc::False
1380 }
1381
1382 mir::TerminatorKind::Unreachable => {
1383 bx.unreachable();
1384 MergingSucc::False
1385 }
1386
1387 mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop, async_fut } => {
1388 assert!(
1389 async_fut.is_none() && drop.is_none(),
1390 "Async Drop must be expanded or reset to sync before codegen"
1391 );
1392 self.codegen_drop_terminator(
1393 helper,
1394 bx,
1395 &terminator.source_info,
1396 place,
1397 target,
1398 unwind,
1399 mergeable_succ(),
1400 )
1401 }
1402
1403 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1404 .codegen_assert_terminator(
1405 helper,
1406 bx,
1407 terminator,
1408 cond,
1409 expected,
1410 msg,
1411 target,
1412 unwind,
1413 mergeable_succ(),
1414 ),
1415
1416 mir::TerminatorKind::Call {
1417 ref func,
1418 ref args,
1419 destination,
1420 target,
1421 unwind,
1422 call_source: _,
1423 fn_span,
1424 } => self.codegen_call_terminator(
1425 helper,
1426 bx,
1427 terminator,
1428 func,
1429 args,
1430 destination,
1431 target,
1432 unwind,
1433 fn_span,
1434 CallKind::Normal,
1435 mergeable_succ(),
1436 ),
1437 mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1438 .codegen_call_terminator(
1439 helper,
1440 bx,
1441 terminator,
1442 func,
1443 args,
1444 mir::Place::from(mir::RETURN_PLACE),
1445 None,
1446 mir::UnwindAction::Unreachable,
1447 fn_span,
1448 CallKind::Tail,
1449 mergeable_succ(),
1450 ),
1451 mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1452 bug!("coroutine ops in codegen")
1453 }
1454 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1455 bug!("borrowck false edges in codegen")
1456 }
1457
1458 mir::TerminatorKind::InlineAsm {
1459 asm_macro,
1460 template,
1461 ref operands,
1462 options,
1463 line_spans,
1464 ref targets,
1465 unwind,
1466 } => self.codegen_asm_terminator(
1467 helper,
1468 bx,
1469 asm_macro,
1470 terminator,
1471 template,
1472 operands,
1473 options,
1474 line_spans,
1475 targets,
1476 unwind,
1477 self.instance,
1478 mergeable_succ(),
1479 ),
1480 }
1481 }
1482
1483 fn codegen_argument(
1484 &mut self,
1485 bx: &mut Bx,
1486 op: OperandRef<'tcx, Bx::Value>,
1487 llargs: &mut Vec<Bx::Value>,
1488 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1489 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1490 ) {
1491 match arg.mode {
1492 PassMode::Ignore => return,
1493 PassMode::Cast { pad_i32: true, .. } => {
1494 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1496 }
1497 PassMode::Pair(..) => match op.val {
1498 Pair(a, b) => {
1499 llargs.push(a);
1500 llargs.push(b);
1501 return;
1502 }
1503 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1504 },
1505 PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1506 Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1507 llargs.push(a);
1508 llargs.push(b);
1509 return;
1510 }
1511 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1512 },
1513 _ => {}
1514 }
1515
1516 let (mut llval, align, by_ref) = match op.val {
1518 Immediate(_) | Pair(..) => match arg.mode {
1519 PassMode::Indirect { attrs, .. } => {
1520 let required_align = match attrs.pointee_align {
1524 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1525 None => arg.layout.align.abi,
1526 };
1527 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1528 bx.lifetime_start(scratch.llval, arg.layout.size);
1529 op.val.store(bx, scratch.with_type(arg.layout));
1530 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1531 (scratch.llval, scratch.align, true)
1532 }
1533 PassMode::Cast { .. } => {
1534 let scratch = PlaceRef::alloca(bx, arg.layout);
1535 op.val.store(bx, scratch);
1536 (scratch.val.llval, scratch.val.align, true)
1537 }
1538 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1539 },
1540 Ref(op_place_val) => match arg.mode {
1541 PassMode::Indirect { attrs, .. } => {
1542 let required_align = match attrs.pointee_align {
1543 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1544 None => arg.layout.align.abi,
1545 };
1546 if op_place_val.align < required_align {
1547 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1551 bx.lifetime_start(scratch.llval, arg.layout.size);
1552 bx.typed_place_copy(scratch, op_place_val, op.layout);
1553 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1554 (scratch.llval, scratch.align, true)
1555 } else {
1556 (op_place_val.llval, op_place_val.align, true)
1557 }
1558 }
1559 _ => (op_place_val.llval, op_place_val.align, true),
1560 },
1561 ZeroSized => match arg.mode {
1562 PassMode::Indirect { on_stack, .. } => {
1563 if on_stack {
1564 bug!("ZST {op:?} passed on stack with abi {arg:?}");
1567 }
1568 let scratch = PlaceRef::alloca(bx, arg.layout);
1572 (scratch.val.llval, scratch.val.align, true)
1573 }
1574 _ => bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1575 },
1576 };
1577
1578 if by_ref && !arg.is_indirect() {
1579 if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1581 let scratch_size = cast.size(bx);
1585 let scratch_align = cast.align(bx);
1586 let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1593 let llscratch = bx.alloca(scratch_size, scratch_align);
1595 bx.lifetime_start(llscratch, scratch_size);
1596 bx.memcpy(
1598 llscratch,
1599 scratch_align,
1600 llval,
1601 align,
1602 bx.const_usize(copy_bytes),
1603 MemFlags::empty(),
1604 );
1605 llval = load_cast(bx, cast, llscratch, scratch_align);
1607 bx.lifetime_end(llscratch, scratch_size);
1608 } else {
1609 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1615 if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1616 if scalar.is_bool() {
1617 bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1618 }
1619 llval = bx.to_immediate_scalar(llval, scalar);
1621 }
1622 }
1623 }
1624
1625 llargs.push(llval);
1626 }
1627
1628 fn codegen_arguments_untupled(
1629 &mut self,
1630 bx: &mut Bx,
1631 operand: &mir::Operand<'tcx>,
1632 llargs: &mut Vec<Bx::Value>,
1633 args: &[ArgAbi<'tcx, Ty<'tcx>>],
1634 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1635 ) -> usize {
1636 let tuple = self.codegen_operand(bx, operand);
1637
1638 if let Ref(place_val) = tuple.val {
1640 if place_val.llextra.is_some() {
1641 bug!("closure arguments must be sized");
1642 }
1643 let tuple_ptr = place_val.with_type(tuple.layout);
1644 for i in 0..tuple.layout.fields.count() {
1645 let field_ptr = tuple_ptr.project_field(bx, i);
1646 let field = bx.load_operand(field_ptr);
1647 self.codegen_argument(bx, field, llargs, &args[i], lifetime_ends_after_call);
1648 }
1649 } else {
1650 for i in 0..tuple.layout.fields.count() {
1652 let op = tuple.extract_field(self, bx, i);
1653 self.codegen_argument(bx, op, llargs, &args[i], lifetime_ends_after_call);
1654 }
1655 }
1656 tuple.layout.fields.count()
1657 }
1658
1659 pub(super) fn get_caller_location(
1660 &mut self,
1661 bx: &mut Bx,
1662 source_info: mir::SourceInfo,
1663 ) -> OperandRef<'tcx, Bx::Value> {
1664 self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1665 let const_loc = bx.tcx().span_as_caller_location(span);
1666 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1667 })
1668 }
1669
1670 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1671 let cx = bx.cx();
1672 if let Some(slot) = self.personality_slot {
1673 slot
1674 } else {
1675 let layout = cx.layout_of(Ty::new_tup(
1676 cx.tcx(),
1677 &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1678 ));
1679 let slot = PlaceRef::alloca(bx, layout);
1680 self.personality_slot = Some(slot);
1681 slot
1682 }
1683 }
1684
1685 fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1688 if let Some(landing_pad) = self.landing_pads[bb] {
1689 return landing_pad;
1690 }
1691
1692 let landing_pad = self.landing_pad_for_uncached(bb);
1693 self.landing_pads[bb] = Some(landing_pad);
1694 landing_pad
1695 }
1696
1697 fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1699 let llbb = self.llbb(bb);
1700 if base::wants_new_eh_instructions(self.cx.sess()) {
1701 let cleanup_bb = Bx::append_block(self.cx, self.llfn, &format!("funclet_{bb:?}"));
1702 let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
1703 let funclet = cleanup_bx.cleanup_pad(None, &[]);
1704 cleanup_bx.br(llbb);
1705 self.funclets[bb] = Some(funclet);
1706 cleanup_bb
1707 } else {
1708 let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1709 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1710
1711 let llpersonality = self.cx.eh_personality();
1712 let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1713
1714 let slot = self.get_personality_slot(&mut cleanup_bx);
1715 slot.storage_live(&mut cleanup_bx);
1716 Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1717
1718 cleanup_bx.br(llbb);
1719 cleanup_llbb
1720 }
1721 }
1722
1723 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1724 self.unreachable_block.unwrap_or_else(|| {
1725 let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1726 let mut bx = Bx::build(self.cx, llbb);
1727 bx.unreachable();
1728 self.unreachable_block = Some(llbb);
1729 llbb
1730 })
1731 }
1732
1733 fn terminate_block(&mut self, reason: UnwindTerminateReason) -> Bx::BasicBlock {
1734 if let Some((cached_bb, cached_reason)) = self.terminate_block
1735 && reason == cached_reason
1736 {
1737 return cached_bb;
1738 }
1739
1740 let funclet;
1741 let llbb;
1742 let mut bx;
1743 if base::wants_new_eh_instructions(self.cx.sess()) {
1744 llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
1774 let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
1775
1776 let mut cs_bx = Bx::build(self.cx, llbb);
1777 let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1778
1779 bx = Bx::build(self.cx, cp_llbb);
1780 let null =
1781 bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
1782
1783 let args = if base::wants_msvc_seh(self.cx.sess()) {
1787 let adjectives = bx.const_i32(0x40);
1794 &[null, adjectives, null] as &[_]
1795 } else {
1796 &[null] as &[_]
1802 };
1803
1804 funclet = Some(bx.catch_pad(cs, args));
1805 } else {
1806 llbb = Bx::append_block(self.cx, self.llfn, "terminate");
1807 bx = Bx::build(self.cx, llbb);
1808
1809 let llpersonality = self.cx.eh_personality();
1810 bx.filter_landing_pad(llpersonality);
1811
1812 funclet = None;
1813 }
1814
1815 self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1816
1817 let (fn_abi, fn_ptr, instance) =
1818 common::build_langcall(&bx, self.mir.span, reason.lang_item());
1819 if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
1820 bx.abort();
1821 } else {
1822 let fn_ty = bx.fn_decl_backend_type(fn_abi);
1823
1824 let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
1825 bx.apply_attrs_to_cleanup_callsite(llret);
1826 }
1827
1828 bx.unreachable();
1829
1830 self.terminate_block = Some((llbb, reason));
1831 llbb
1832 }
1833
1834 pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1839 self.try_llbb(bb).unwrap()
1840 }
1841
1842 pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
1844 match self.cached_llbbs[bb] {
1845 CachedLlbb::None => {
1846 let llbb = Bx::append_block(self.cx, self.llfn, &format!("{bb:?}"));
1847 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
1848 Some(llbb)
1849 }
1850 CachedLlbb::Some(llbb) => Some(llbb),
1851 CachedLlbb::Skip => None,
1852 }
1853 }
1854
1855 fn make_return_dest(
1856 &mut self,
1857 bx: &mut Bx,
1858 dest: mir::Place<'tcx>,
1859 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1860 llargs: &mut Vec<Bx::Value>,
1861 ) -> ReturnDest<'tcx, Bx::Value> {
1862 if fn_ret.is_ignore() {
1864 return ReturnDest::Nothing;
1865 }
1866 let dest = if let Some(index) = dest.as_local() {
1867 match self.locals[index] {
1868 LocalRef::Place(dest) => dest,
1869 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1870 LocalRef::PendingOperand => {
1871 return if fn_ret.is_indirect() {
1874 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1877 tmp.storage_live(bx);
1878 llargs.push(tmp.val.llval);
1879 ReturnDest::IndirectOperand(tmp, index)
1880 } else {
1881 ReturnDest::DirectOperand(index)
1882 };
1883 }
1884 LocalRef::Operand(_) => {
1885 bug!("place local already assigned to");
1886 }
1887 }
1888 } else {
1889 self.codegen_place(bx, dest.as_ref())
1890 };
1891 if fn_ret.is_indirect() {
1892 if dest.val.align < dest.layout.align.abi {
1893 span_bug!(self.mir.span, "can't directly store to unaligned value");
1900 }
1901 llargs.push(dest.val.llval);
1902 ReturnDest::Nothing
1903 } else {
1904 ReturnDest::Store(dest)
1905 }
1906 }
1907
1908 fn store_return(
1910 &mut self,
1911 bx: &mut Bx,
1912 dest: ReturnDest<'tcx, Bx::Value>,
1913 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1914 llval: Bx::Value,
1915 ) {
1916 use self::ReturnDest::*;
1917
1918 match dest {
1919 Nothing => (),
1920 Store(dst) => bx.store_arg(ret_abi, llval, dst),
1921 IndirectOperand(tmp, index) => {
1922 let op = bx.load_operand(tmp);
1923 tmp.storage_dead(bx);
1924 self.overwrite_local(index, LocalRef::Operand(op));
1925 self.debug_introduce_local(bx, index);
1926 }
1927 DirectOperand(index) => {
1928 let op = if let PassMode::Cast { .. } = ret_abi.mode {
1930 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1931 tmp.storage_live(bx);
1932 bx.store_arg(ret_abi, llval, tmp);
1933 let op = bx.load_operand(tmp);
1934 tmp.storage_dead(bx);
1935 op
1936 } else {
1937 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1938 };
1939 self.overwrite_local(index, LocalRef::Operand(op));
1940 self.debug_introduce_local(bx, index);
1941 }
1942 }
1943 }
1944}
1945
1946enum ReturnDest<'tcx, V> {
1947 Nothing,
1949 Store(PlaceRef<'tcx, V>),
1951 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1953 DirectOperand(mir::Local),
1955}
1956
1957fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1958 bx: &mut Bx,
1959 cast: &CastTarget,
1960 ptr: Bx::Value,
1961 align: Align,
1962) -> Bx::Value {
1963 let cast_ty = bx.cast_backend_type(cast);
1964 if let Some(offset_from_start) = cast.rest_offset {
1965 assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
1966 assert_eq!(cast.rest.unit.size, cast.rest.total);
1967 let first_ty = bx.reg_backend_type(&cast.prefix[0].unwrap());
1968 let second_ty = bx.reg_backend_type(&cast.rest.unit);
1969 let first = bx.load(first_ty, ptr, align);
1970 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
1971 let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
1972 let res = bx.cx().const_poison(cast_ty);
1973 let res = bx.insert_value(res, first, 0);
1974 bx.insert_value(res, second, 1)
1975 } else {
1976 bx.load(cast_ty, ptr, align)
1977 }
1978}
1979
1980pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1981 bx: &mut Bx,
1982 cast: &CastTarget,
1983 value: Bx::Value,
1984 ptr: Bx::Value,
1985 align: Align,
1986) {
1987 if let Some(offset_from_start) = cast.rest_offset {
1988 assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
1989 assert_eq!(cast.rest.unit.size, cast.rest.total);
1990 assert!(cast.prefix[0].is_some());
1991 let first = bx.extract_value(value, 0);
1992 let second = bx.extract_value(value, 1);
1993 bx.store(first, ptr, align);
1994 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
1995 bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
1996 } else {
1997 bx.store(value, ptr, align);
1998 };
1999}