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