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, TypeVisitableExt};
13use rustc_middle::{bug, span_bug};
14use rustc_session::config::OptLevel;
15use rustc_span::{Span, Spanned};
16use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, PassMode};
17use tracing::{debug, info};
18
19use super::operand::OperandRef;
20use super::operand::OperandValue::{self, 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::mir::IntrinsicResult;
27use crate::traits::*;
28use crate::{MemFlags, meth};
29
30#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MergingSucc {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MergingSucc::False => "False",
MergingSucc::True => "True",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for MergingSucc {
#[inline]
fn eq(&self, other: &MergingSucc) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
34enum MergingSucc {
35 False,
36 True,
37}
38
39#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CallKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CallKind::Normal => "Normal",
CallKind::Tail => "Tail",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CallKind {
#[inline]
fn eq(&self, other: &CallKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}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 if !base::wants_new_eh_instructions(fx.cx.tcx().sess) {
::core::panicking::panic("assertion failed: base::wants_new_eh_instructions(fx.cx.tcx().sess)")
};assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess));
96 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:96",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(96u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("llbb_with_cleanup: creating cleanup trampoline for {0:?}",
target) as &dyn Value))])
});
} else { ; }
};debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
97 let name = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
self.bb, target))
})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 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("{0:?} - jump out of cleanup?", self.terminator));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: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
184 callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
185 };
186 tcx.dcx().emit_err(e);
187 } else {
188 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:188",
"rustc_codegen_ssa::mir::block", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(188u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("compiler_builtins call to diverging function {0:?} replaced with abort",
instance.def_id()) as &dyn Value))])
});
} else { ; }
};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 caller_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 caller_attrs = caller_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_wasm_eh(fx.cx.tcx().sess) {
219 Some(fx.terminate_block(reason, Some(self.bb)))
222 } else if fx.mir[self.bb].is_cleanup
223 && base::wants_new_eh_instructions(fx.cx.tcx().sess)
224 {
225 None
228 } else {
229 Some(fx.terminate_block(reason, None))
230 }
231 }
232 };
233
234 if kind == CallKind::Tail {
235 bx.tail_call(fn_ty, caller_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
236 return MergingSucc::False;
237 }
238
239 if let Some(unwind_block) = unwind_block {
240 let ret_llbb = if let Some((_, target)) = destination {
241 self.llbb_with_cleanup(fx, target)
242 } else {
243 fx.unreachable_block()
244 };
245 let invokeret = bx.invoke(
246 fn_ty,
247 caller_attrs,
248 Some(fn_abi),
249 fn_ptr,
250 llargs,
251 ret_llbb,
252 unwind_block,
253 self.funclet(fx),
254 instance,
255 );
256 if fx.mir[self.bb].is_cleanup {
257 bx.apply_attrs_to_cleanup_callsite(invokeret);
258 }
259
260 if let Some((ret_dest, target)) = destination {
261 bx.switch_to_block(fx.llbb(target));
262 fx.set_debug_loc(bx, self.terminator.source_info);
263 for &(tmp, size) in lifetime_ends_after_call {
264 bx.lifetime_end(tmp, size);
265 }
266 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
267
268 fx.cached_llbbs[target] = CachedLlbb::Some(bx.llbb());
273 }
274 MergingSucc::False
275 } else {
276 let llret = bx.call(
277 fn_ty,
278 caller_attrs,
279 Some(fn_abi),
280 fn_ptr,
281 llargs,
282 self.funclet(fx),
283 instance,
284 );
285 if fx.mir[self.bb].is_cleanup {
286 bx.apply_attrs_to_cleanup_callsite(llret);
287 }
288
289 if let Some((ret_dest, target)) = destination {
290 for &(tmp, size) in lifetime_ends_after_call {
291 bx.lifetime_end(tmp, size);
292 }
293 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
294 self.funclet_br(fx, bx, target, mergeable_succ)
295 } else {
296 bx.unreachable();
297 MergingSucc::False
298 }
299 }
300 }
301
302 fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
304 &self,
305 fx: &mut FunctionCx<'a, 'tcx, Bx>,
306 bx: &mut Bx,
307 template: &[InlineAsmTemplatePiece],
308 operands: &[InlineAsmOperandRef<'tcx, Bx>],
309 options: InlineAsmOptions,
310 line_spans: &[Span],
311 destination: Option<mir::BasicBlock>,
312 unwind: mir::UnwindAction,
313 instance: Instance<'_>,
314 mergeable_succ: bool,
315 ) -> MergingSucc {
316 let unwind_target = match unwind {
317 mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
318 mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason, None)),
319 mir::UnwindAction::Continue => None,
320 mir::UnwindAction::Unreachable => None,
321 };
322
323 if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
InlineAsmOperandRef::Label { .. } => true,
_ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
324 if !unwind_target.is_none() {
::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
325 let ret_llbb = if let Some(target) = destination {
326 self.llbb_with_cleanup(fx, target)
327 } else {
328 fx.unreachable_block()
329 };
330
331 bx.codegen_inline_asm(
332 template,
333 operands,
334 options,
335 line_spans,
336 instance,
337 Some(ret_llbb),
338 None,
339 );
340 MergingSucc::False
341 } else if let Some(cleanup) = unwind_target {
342 let ret_llbb = if let Some(target) = destination {
343 self.llbb_with_cleanup(fx, target)
344 } else {
345 fx.unreachable_block()
346 };
347
348 bx.codegen_inline_asm(
349 template,
350 operands,
351 options,
352 line_spans,
353 instance,
354 Some(ret_llbb),
355 Some((cleanup, self.funclet(fx))),
356 );
357 MergingSucc::False
358 } else {
359 bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
360
361 if let Some(target) = destination {
362 self.funclet_br(fx, bx, target, mergeable_succ)
363 } else {
364 bx.unreachable();
365 MergingSucc::False
366 }
367 }
368 }
369}
370
371impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
373 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
375 if let Some(funclet) = helper.funclet(self) {
376 bx.cleanup_ret(funclet, None);
377 } else {
378 let slot = self.get_personality_slot(bx);
379 let exn0 = slot.project_field(bx, 0);
380 let exn0 = bx.load_operand(exn0).immediate();
381 let exn1 = slot.project_field(bx, 1);
382 let exn1 = bx.load_operand(exn1).immediate();
383 slot.storage_dead(bx);
384
385 bx.resume(exn0, exn1);
386 }
387 }
388
389 fn codegen_switchint_terminator(
390 &mut self,
391 helper: TerminatorCodegenHelper<'tcx>,
392 bx: &mut Bx,
393 discr: &mir::Operand<'tcx>,
394 targets: &SwitchTargets,
395 ) {
396 let discr = self.codegen_operand(bx, discr);
397 let discr_value = discr.immediate();
398 let switch_ty = discr.layout.ty;
399 if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
401 let target = targets.target_for_value(const_discr);
402 bx.br(helper.llbb_with_cleanup(self, target));
403 return;
404 };
405
406 let mut target_iter = targets.iter();
407 if target_iter.len() == 1 {
408 let (test_value, target) = target_iter.next().unwrap();
411 let otherwise = targets.otherwise();
412 let lltarget = helper.llbb_with_cleanup(self, target);
413 let llotherwise = helper.llbb_with_cleanup(self, otherwise);
414 let target_cold = self.cold_blocks[target];
415 let otherwise_cold = self.cold_blocks[otherwise];
416 let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
420 if switch_ty == bx.tcx().types.bool {
421 match test_value {
423 0 => {
424 let expect = expect.map(|e| !e);
425 bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
426 }
427 1 => {
428 bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
429 }
430 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
431 }
432 } else {
433 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
434 let llval = bx.const_uint_big(switch_llty, test_value);
435 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
436 bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
437 }
438 } else if target_iter.len() == 2
439 && self.mir[targets.otherwise()].is_empty_unreachable()
440 && targets.all_values().contains(&Pu128(0))
441 && targets.all_values().contains(&Pu128(1))
442 {
443 let true_bb = targets.target_for_value(1);
447 let false_bb = targets.target_for_value(0);
448 let true_ll = helper.llbb_with_cleanup(self, true_bb);
449 let false_ll = helper.llbb_with_cleanup(self, false_bb);
450
451 let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
452 None
453 } else {
454 match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
455 (true, true) | (false, false) => None,
457 (true, false) => Some(false),
459 (false, true) => Some(true),
460 }
461 };
462
463 let bool_ty = bx.tcx().types.bool;
464 let cond = if switch_ty == bool_ty {
465 discr_value
466 } else {
467 let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
468 bx.unchecked_utrunc(discr_value, bool_llty)
469 };
470 bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
471 } else if self.cx.sess().opts.optimize == OptLevel::No
472 && target_iter.len() == 2
473 && self.mir[targets.otherwise()].is_empty_unreachable()
474 {
475 let (test_value1, target1) = target_iter.next().unwrap();
488 let (_test_value2, target2) = target_iter.next().unwrap();
489 let ll1 = helper.llbb_with_cleanup(self, target1);
490 let ll2 = helper.llbb_with_cleanup(self, target2);
491 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
492 let llval = bx.const_uint_big(switch_llty, test_value1);
493 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
494 bx.cond_br(cmp, ll1, ll2);
495 } else {
496 let otherwise = targets.otherwise();
497 let otherwise_cold = self.cold_blocks[otherwise];
498 let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
499 let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
500 let none_cold = cold_count == 0;
501 let all_cold = cold_count == targets.iter().len();
502 if (none_cold && (!otherwise_cold || otherwise_unreachable))
503 || (all_cold && (otherwise_cold || otherwise_unreachable))
504 {
505 bx.switch(
508 discr_value,
509 helper.llbb_with_cleanup(self, targets.otherwise()),
510 target_iter
511 .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
512 );
513 } else {
514 bx.switch_with_weights(
516 discr_value,
517 helper.llbb_with_cleanup(self, targets.otherwise()),
518 otherwise_cold,
519 target_iter.map(|(value, target)| {
520 (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
521 }),
522 );
523 }
524 }
525 }
526
527 fn codegen_return_terminator(&mut self, bx: &mut Bx) {
528 if self.fn_abi.c_variadic {
532 let va_list_arg_idx = self.fn_abi.args.len();
534 match self.locals[mir::Local::arg(va_list_arg_idx)] {
535 LocalRef::Place(va_list) => {
536 bx.lifetime_end(va_list.val.llval, va_list.layout.size);
542 }
543 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("C-variadic function must have a `VaList` place"))bug!("C-variadic function must have a `VaList` place"),
544 }
545 }
546 if self.fn_abi.ret.layout.is_uninhabited() {
547 bx.abort();
552 bx.unreachable();
555 return;
556 }
557 let llval = match &self.fn_abi.ret.mode {
558 PassMode::Ignore | PassMode::Indirect { .. } => {
559 bx.ret_void();
560 return;
561 }
562
563 PassMode::Direct(_) | PassMode::Pair(..) => {
564 let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
565 if let Ref(place_val) = op.val {
566 bx.load_from_place(bx.backend_type(op.layout), place_val)
567 } else {
568 op.immediate_or_packed_pair(bx)
569 }
570 }
571
572 PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
573 let op = match self.locals[mir::RETURN_PLACE] {
574 LocalRef::Operand(op) => op,
575 LocalRef::PendingOperand => ::rustc_middle::util::bug::bug_fmt(format_args!("use of return before def"))bug!("use of return before def"),
576 LocalRef::Place(cg_place) => OperandRef {
577 val: Ref(cg_place.val),
578 layout: cg_place.layout,
579 move_annotation: None,
580 },
581 LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
582 };
583 let llslot = match op.val {
584 Immediate(_) | Pair(..) => {
585 let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
586 op.val.store(bx, scratch);
587 scratch.val.llval
588 }
589 Ref(place_val) => {
590 match (&place_val.align, &op.layout.align.abi) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::Some(format_args!("return place is unaligned!")));
}
}
};assert_eq!(
591 place_val.align, op.layout.align.abi,
592 "return place is unaligned!"
593 );
594 place_val.llval
595 }
596 ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST return value shouldn\'t be in PassMode::Cast"))bug!("ZST return value shouldn't be in PassMode::Cast"),
597 };
598 load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
599 }
600 };
601 bx.ret(llval);
602 }
603
604 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("codegen_drop_terminator",
"rustc_codegen_ssa::mir::block", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(604u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["source_info",
"location", "target", "unwind", "mergeable_succ"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_info)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unwind)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&mergeable_succ as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: MergingSucc = loop {};
return __tracing_attr_fake_return;
}
{
let ty = location.ty(self.mir, bx.tcx()).ty;
let ty = self.monomorphize(ty);
let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
return helper.funclet_br(self, bx, target, mergeable_succ);
}
let place = self.codegen_place(bx, location.as_ref());
let (args1, args2);
let mut args =
if let Some(llextra) = place.val.llextra {
args2 = [place.val.llval, llextra];
&args2[..]
} else { args1 = [place.val.llval]; &args1[..] };
let (maybe_null, drop_fn, fn_abi, drop_instance) =
match ty.kind() {
ty::Dynamic(_, _) => {
let virtual_drop =
Instance {
def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0),
args: drop_fn.args,
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:653",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(653u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ty = {0:?}",
ty) as &dyn Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:654",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(654u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("drop_fn = {0:?}",
drop_fn) as &dyn Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:655",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(655u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("args = {0:?}",
args) as &dyn Value))])
});
} else { ; }
};
let fn_abi =
bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
let vtable = args[1];
args = &args[..1];
(true,
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE).get_optional_fn(bx,
vtable, ty, fn_abi), fn_abi, virtual_drop)
}
_ =>
(false, bx.get_fn_addr(drop_fn),
bx.fn_abi_of_instance(drop_fn, ty::List::empty()), drop_fn),
};
if maybe_null {
let is_not_null = bx.append_sibling_block("is_not_null");
let llty = bx.fn_ptr_backend_type(fn_abi);
let null = bx.const_null(llty);
let non_null =
bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne,
false), drop_fn, null);
bx.cond_br(non_null, is_not_null,
helper.llbb_with_cleanup(self, target));
bx.switch_to_block(is_not_null);
self.set_debug_loc(bx, *source_info);
}
helper.do_call(self, bx, fn_abi, drop_fn, args,
Some((ReturnDest::Nothing, target)), unwind, &[],
Some(drop_instance), CallKind::Normal,
!maybe_null && mergeable_succ)
}
}
}#[tracing::instrument(level = "trace", skip(self, helper, bx))]
605 fn codegen_drop_terminator(
606 &mut self,
607 helper: TerminatorCodegenHelper<'tcx>,
608 bx: &mut Bx,
609 source_info: &mir::SourceInfo,
610 location: mir::Place<'tcx>,
611 target: mir::BasicBlock,
612 unwind: mir::UnwindAction,
613 mergeable_succ: bool,
614 ) -> MergingSucc {
615 let ty = location.ty(self.mir, bx.tcx()).ty;
616 let ty = self.monomorphize(ty);
617 let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
618
619 if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
620 return helper.funclet_br(self, bx, target, mergeable_succ);
622 }
623
624 let place = self.codegen_place(bx, location.as_ref());
625 let (args1, args2);
626 let mut args = if let Some(llextra) = place.val.llextra {
627 args2 = [place.val.llval, llextra];
628 &args2[..]
629 } else {
630 args1 = [place.val.llval];
631 &args1[..]
632 };
633 let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
634 ty::Dynamic(_, _) => {
637 let virtual_drop = Instance {
650 def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), args: drop_fn.args,
652 };
653 debug!("ty = {:?}", ty);
654 debug!("drop_fn = {:?}", drop_fn);
655 debug!("args = {:?}", args);
656 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
657 let vtable = args[1];
658 args = &args[..1];
660 (
661 true,
662 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
663 .get_optional_fn(bx, vtable, ty, fn_abi),
664 fn_abi,
665 virtual_drop,
666 )
667 }
668 _ => (
669 false,
670 bx.get_fn_addr(drop_fn),
671 bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
672 drop_fn,
673 ),
674 };
675
676 if maybe_null {
679 let is_not_null = bx.append_sibling_block("is_not_null");
680 let llty = bx.fn_ptr_backend_type(fn_abi);
681 let null = bx.const_null(llty);
682 let non_null =
683 bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
684 bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
685 bx.switch_to_block(is_not_null);
686 self.set_debug_loc(bx, *source_info);
687 }
688
689 helper.do_call(
690 self,
691 bx,
692 fn_abi,
693 drop_fn,
694 args,
695 Some((ReturnDest::Nothing, target)),
696 unwind,
697 &[],
698 Some(drop_instance),
699 CallKind::Normal,
700 !maybe_null && mergeable_succ,
701 )
702 }
703
704 fn codegen_assert_terminator(
705 &mut self,
706 helper: TerminatorCodegenHelper<'tcx>,
707 bx: &mut Bx,
708 terminator: &mir::Terminator<'tcx>,
709 cond: &mir::Operand<'tcx>,
710 expected: bool,
711 msg: &mir::AssertMessage<'tcx>,
712 target: mir::BasicBlock,
713 unwind: mir::UnwindAction,
714 mergeable_succ: bool,
715 ) -> MergingSucc {
716 let span = terminator.source_info.span;
717 let cond = self.codegen_operand(bx, cond).immediate();
718 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
719
720 if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
725 const_cond = Some(expected);
726 }
727
728 if const_cond == Some(expected) {
730 return helper.funclet_br(self, bx, target, mergeable_succ);
731 }
732
733 let lltarget = helper.llbb_with_cleanup(self, target);
738 let panic_block = bx.append_sibling_block("panic");
739 if expected {
740 bx.cond_br(cond, lltarget, panic_block);
741 } else {
742 bx.cond_br(cond, panic_block, lltarget);
743 }
744
745 bx.switch_to_block(panic_block);
747 self.set_debug_loc(bx, terminator.source_info);
748
749 let location = self.get_caller_location(bx, terminator.source_info).immediate();
751
752 let (lang_item, args) = match msg {
754 AssertKind::BoundsCheck { len, index } => {
755 let len = self.codegen_operand(bx, len).immediate();
756 let index = self.codegen_operand(bx, index).immediate();
757 (LangItem::PanicBoundsCheck, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[index, len, location]))vec![index, len, location])
760 }
761 AssertKind::MisalignedPointerDereference { required, found } => {
762 let required = self.codegen_operand(bx, required).immediate();
763 let found = self.codegen_operand(bx, found).immediate();
764 (LangItem::PanicMisalignedPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[required, found, location]))vec![required, found, location])
767 }
768 AssertKind::NullPointerDereference => {
769 (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[location]))vec![location])
772 }
773 AssertKind::InvalidEnumConstruction(source) => {
774 let source = self.codegen_operand(bx, source).immediate();
775 (LangItem::PanicInvalidEnumConstruction, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[source, location]))vec![source, location])
778 }
779 _ => {
780 (msg.panic_function(), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[location]))vec![location])
782 }
783 };
784
785 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
786
787 let merging_succ = helper.do_call(
789 self,
790 bx,
791 fn_abi,
792 llfn,
793 &args,
794 None,
795 unwind,
796 &[],
797 Some(instance),
798 CallKind::Normal,
799 false,
800 );
801 match (&merging_succ, &MergingSucc::False) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(merging_succ, MergingSucc::False);
802 MergingSucc::False
803 }
804
805 fn codegen_terminate_terminator(
806 &mut self,
807 helper: TerminatorCodegenHelper<'tcx>,
808 bx: &mut Bx,
809 terminator: &mir::Terminator<'tcx>,
810 reason: UnwindTerminateReason,
811 ) {
812 let span = terminator.source_info.span;
813 self.set_debug_loc(bx, terminator.source_info);
814
815 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
817
818 let merging_succ = helper.do_call(
820 self,
821 bx,
822 fn_abi,
823 llfn,
824 &[],
825 None,
826 mir::UnwindAction::Unreachable,
827 &[],
828 Some(instance),
829 CallKind::Normal,
830 false,
831 );
832 match (&merging_succ, &MergingSucc::False) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(merging_succ, MergingSucc::False);
833 }
834
835 fn codegen_panic_intrinsic(
837 &mut self,
838 helper: &TerminatorCodegenHelper<'tcx>,
839 bx: &mut Bx,
840 intrinsic: ty::IntrinsicDef,
841 instance: Instance<'tcx>,
842 source_info: mir::SourceInfo,
843 target: Option<mir::BasicBlock>,
844 unwind: mir::UnwindAction,
845 mergeable_succ: bool,
846 ) -> Option<MergingSucc> {
847 let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
851 return None;
852 };
853
854 let ty = instance.args.type_at(0);
855
856 let is_valid = bx
857 .tcx()
858 .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
859 .expect("expect to have layout during codegen");
860
861 if is_valid {
862 let target = target.unwrap();
864 return Some(helper.funclet_br(self, bx, target, mergeable_succ));
865 }
866
867 let layout = bx.layout_of(ty);
868
869 let msg_str = {
let _guard = NoVisibleGuard::new();
{
{
let _guard = NoTrimmedGuard::new();
{
if layout.is_uninhabited() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to instantiate uninhabited type `{0}`",
ty))
})
} else if requirement == ValidityRequirement::Zero {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to zero-initialize type `{0}`, which is invalid",
ty))
})
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to leave type `{0}` uninitialized, which is invalid",
ty))
})
}
}
}
}
}with_no_visible_paths!({
870 with_no_trimmed_paths!({
871 if layout.is_uninhabited() {
872 format!("attempted to instantiate uninhabited type `{ty}`")
874 } else if requirement == ValidityRequirement::Zero {
875 format!("attempted to zero-initialize type `{ty}`, which is invalid")
876 } else {
877 format!("attempted to leave type `{ty}` uninitialized, which is invalid")
878 }
879 })
880 });
881 let msg = bx.const_str(&msg_str);
882
883 let (fn_abi, llfn, instance) =
885 common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
886
887 Some(helper.do_call(
889 self,
890 bx,
891 fn_abi,
892 llfn,
893 &[msg.0, msg.1],
894 target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
895 unwind,
896 &[],
897 Some(instance),
898 CallKind::Normal,
899 mergeable_succ,
900 ))
901 }
902
903 fn codegen_call_terminator(
904 &mut self,
905 helper: TerminatorCodegenHelper<'tcx>,
906 bx: &mut Bx,
907 terminator: &mir::Terminator<'tcx>,
908 func: &mir::Operand<'tcx>,
909 args: &[Spanned<mir::Operand<'tcx>>],
910 destination: mir::Place<'tcx>,
911 target: Option<mir::BasicBlock>,
912 unwind: mir::UnwindAction,
913 fn_span: Span,
914 kind: CallKind,
915 mergeable_succ: bool,
916 ) -> MergingSucc {
917 let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
918
919 let callee = self.codegen_operand(bx, func);
921
922 let (instance, mut llfn) = match *callee.layout.ty.kind() {
923 ty::FnDef(def_id, generic_args) => {
924 let instance = ty::Instance::expect_resolve(
925 bx.tcx(),
926 bx.typing_env(),
927 def_id,
928 generic_args,
929 fn_span,
930 );
931
932 match instance.def {
933 ty::InstanceKind::DropGlue(_, None) => {
936 let target = target.unwrap();
938 return helper.funclet_br(self, bx, target, mergeable_succ);
939 }
940 ty::InstanceKind::Intrinsic(def_id) => {
941 let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
942 if let Some(merging_succ) = self.codegen_panic_intrinsic(
943 &helper,
944 bx,
945 intrinsic,
946 instance,
947 source_info,
948 target,
949 unwind,
950 mergeable_succ,
951 ) {
952 return merging_succ;
953 }
954
955 let result_layout =
956 self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
957
958 let (result_place, store_in_local) =
959 if let Some(local) = destination.as_local() {
960 match self.locals[local] {
961 LocalRef::Place(dest) => (Some(dest.val), None),
962 LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
963 LocalRef::PendingOperand => (None, Some(local)),
964 LocalRef::Operand(_) => {
965 if result_layout.is_zst() {
966 let place = PlaceRef::new_sized(
967 bx.const_undef(bx.type_ptr()),
968 result_layout,
969 );
970 (Some(place.val), None)
971 } else {
972 ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
973 }
974 }
975 }
976 } else {
977 (Some(self.codegen_place(bx, destination.as_ref()).val), None)
978 };
979
980 if let Some(place) = result_place
981 && place.align < result_layout.align.abi
982 {
983 ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
990 }
991
992 let args: Vec<_> =
993 args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
994
995 let intrinsic_result = self.codegen_intrinsic_call(
996 bx,
997 instance,
998 &args,
999 result_layout,
1000 result_place,
1001 source_info,
1002 );
1003
1004 if let IntrinsicResult::Operand(op_val) = intrinsic_result {
1005 match (result_place, store_in_local) {
1006 (None, Some(local)) => {
1007 let op = OperandRef {
1008 val: op_val,
1009 layout: result_layout,
1010 move_annotation: None,
1011 };
1012 self.overwrite_local(local, LocalRef::Operand(op));
1013 self.debug_introduce_local(bx, local);
1014 }
1015 (Some(place_val), None) => {
1016 let dest = PlaceRef { val: place_val, layout: result_layout };
1017 op_val.store(bx, dest);
1018 }
1019 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1020 }
1021 }
1022
1023 match intrinsic_result {
1024 IntrinsicResult::Operand(_) | IntrinsicResult::WroteIntoPlace => {
1025 return if let Some(target) = target {
1026 helper.funclet_br(self, bx, target, mergeable_succ)
1027 } else {
1028 bx.unreachable();
1029 MergingSucc::False
1030 };
1031 }
1032 IntrinsicResult::Err(_) => {
1033 if let Some(local) = store_in_local {
1037 let op = OperandRef {
1038 val: OperandValue::poison(bx, result_layout),
1039 layout: result_layout,
1040 move_annotation: None,
1041 };
1042 self.overwrite_local(local, LocalRef::Operand(op));
1043 }
1044 bx.abort();
1047 return MergingSucc::False;
1048 }
1049 IntrinsicResult::Fallback(instance) => {
1050 if intrinsic.must_be_overridden {
1051 ::rustc_middle::util::bug::span_bug_fmt(fn_span,
format_args!("intrinsic {0} must be overridden by codegen backend, but isn\'t",
intrinsic.name));span_bug!(
1052 fn_span,
1053 "intrinsic {} must be overridden by codegen backend, but isn't",
1054 intrinsic.name,
1055 );
1056 }
1057 (Some(instance), None)
1058 }
1059 }
1060 }
1061
1062 _ if kind == CallKind::Tail
1063 && instance.def.requires_caller_location(bx.tcx()) =>
1064 {
1065 if let Some(hir_id) =
1066 terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1067 {
1068 bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1069 _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1070 }));
1071 }
1072
1073 let instance = ty::Instance::resolve_for_fn_ptr(
1074 bx.tcx(),
1075 bx.typing_env(),
1076 def_id,
1077 generic_args,
1078 )
1079 .unwrap();
1080
1081 (None, Some(bx.get_fn_addr(instance)))
1082 }
1083 _ => (Some(instance), None),
1084 }
1085 }
1086 ty::FnPtr(..) => (None, Some(callee.immediate())),
1087 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} is not callable",
callee.layout.ty))bug!("{} is not callable", callee.layout.ty),
1088 };
1089
1090 if let Some(instance) = instance
1091 && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1092 && name.as_str().starts_with("llvm.")
1093 && name.as_str() != "llvm.wasm.throw"
1097 {
1098 if !!instance.args.has_infer() {
::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1099 if !!instance.args.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !instance.args.has_escaping_bound_vars()")
};assert!(!instance.args.has_escaping_bound_vars());
1100
1101 let result_layout =
1102 self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1103
1104 let return_dest = if result_layout.is_zst() {
1105 ReturnDest::Nothing
1106 } else if let Some(index) = destination.as_local() {
1107 match self.locals[index] {
1108 LocalRef::Place(dest) => ReturnDest::Store(dest),
1109 LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
1110 LocalRef::PendingOperand => {
1111 ReturnDest::DirectOperand(index)
1114 }
1115 LocalRef::Operand(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"))bug!("place local already assigned to"),
1116 }
1117 } else {
1118 ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1119 };
1120
1121 let args =
1122 args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1123
1124 self.set_debug_loc(bx, source_info);
1125
1126 let llret =
1127 bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1128
1129 if let Some(target) = target {
1130 self.store_return(
1131 bx,
1132 return_dest,
1133 &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1134 llret,
1135 );
1136 return helper.funclet_br(self, bx, target, mergeable_succ);
1137 } else {
1138 bx.unreachable();
1139 return MergingSucc::False;
1140 }
1141 }
1142
1143 let sig = callee.layout.ty.fn_sig(bx.tcx());
1147
1148 let extra_args = &args[sig.inputs().skip_binder().len()..];
1149 let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1150 let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1151 self.monomorphize(op_ty)
1152 }));
1153
1154 let fn_abi = match instance {
1155 Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1156 None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1157 };
1158
1159 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1161
1162 let mut llargs = Vec::with_capacity(arg_count);
1163
1164 let destination = match kind {
1168 CallKind::Normal => {
1169 let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1170 target.map(|target| (return_dest, target))
1171 }
1172 CallKind::Tail => {
1173 if fn_abi.ret.is_indirect() {
1174 match self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs) {
1175 ReturnDest::Nothing => {}
1176 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("tail calls to functions with indirect returns cannot store into a destination"))bug!(
1177 "tail calls to functions with indirect returns cannot store into a destination"
1178 ),
1179 }
1180 }
1181 None
1182 }
1183 };
1184
1185 let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1187 && let Some((tup, args)) = args.split_last()
1188 {
1189 (args, Some(tup))
1190 } else {
1191 (args, None)
1192 };
1193
1194 let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1217 if kind == CallKind::Tail {
1218 tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1219 for (i, arg) in first_args.iter().enumerate() {
1222 if !#[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
PassMode::Indirect { on_stack: false, .. } => true,
_ => false,
}matches!(fn_abi.args[i].mode, PassMode::Indirect { on_stack: false, .. }) {
1223 continue;
1224 }
1225
1226 let op = self.codegen_operand(bx, &arg.node);
1227 let tmp = PlaceRef::alloca(bx, op.layout);
1228 bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1229 op.store_with_annotation(bx, tmp);
1230
1231 tail_call_temporaries[i] = Some(tmp);
1232 }
1233 }
1234
1235 let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1239 'make_args: for (i, arg) in first_args.iter().enumerate() {
1240 let mut op = self.codegen_operand(bx, &arg.node);
1241
1242 if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1243 match op.val {
1244 Pair(data_ptr, meta) => {
1245 while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1255 let (idx, _) = op.layout.non_1zst_field(bx).expect(
1256 "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1257 );
1258 op = op.extract_field(self, bx, idx.as_usize());
1259 }
1260
1261 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1265 bx,
1266 meta,
1267 op.layout.ty,
1268 fn_abi,
1269 ));
1270 llargs.push(data_ptr);
1271 continue 'make_args;
1272 }
1273 Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1274 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1276 bx,
1277 meta,
1278 op.layout.ty,
1279 fn_abi,
1280 ));
1281 llargs.push(data_ptr);
1282 continue;
1283 }
1284 _ => {
1285 ::rustc_middle::util::bug::span_bug_fmt(fn_span,
format_args!("can\'t codegen a virtual call on {0:#?}", op));span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1286 }
1287 }
1288 }
1289
1290 let by_move = if let PassMode::Indirect { on_stack: false, .. } = fn_abi.args[i].mode
1291 && kind == CallKind::Tail
1292 {
1293 let Some(tmp) = tail_call_temporaries[i].take() else {
1306 ::rustc_middle::util::bug::span_bug_fmt(fn_span,
format_args!("missing temporary for indirect tail call argument #{0}", i))span_bug!(fn_span, "missing temporary for indirect tail call argument #{i}")
1307 };
1308
1309 let local = self.mir.args_iter().nth(i).unwrap();
1310
1311 match &self.locals[local] {
1312 LocalRef::Place(arg) => {
1313 bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1314 op.val = Ref(arg.val);
1315 }
1316 LocalRef::Operand(arg) => {
1317 let Ref(place_value) = arg.val else {
1318 ::rustc_middle::util::bug::bug_fmt(format_args!("only `Ref` should use `PassMode::Indirect`"));bug!("only `Ref` should use `PassMode::Indirect`");
1319 };
1320 bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1321 op.val = arg.val;
1322 }
1323 LocalRef::UnsizedPlace(_) => {
1324 ::rustc_middle::util::bug::span_bug_fmt(fn_span,
format_args!("unsized types are not supported"))span_bug!(fn_span, "unsized types are not supported")
1325 }
1326 LocalRef::PendingOperand => {
1327 ::rustc_middle::util::bug::span_bug_fmt(fn_span,
format_args!("argument local should not be pending"))span_bug!(fn_span, "argument local should not be pending")
1328 }
1329 };
1330
1331 bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1332 true
1333 } else {
1334 #[allow(non_exhaustive_omitted_patterns)] match arg.node {
mir::Operand::Move(_) => true,
_ => false,
}matches!(arg.node, mir::Operand::Move(_))
1335 };
1336
1337 self.codegen_argument(
1338 bx,
1339 op,
1340 by_move,
1341 &mut llargs,
1342 &fn_abi.args[i],
1343 &mut lifetime_ends_after_call,
1344 );
1345 }
1346 let num_untupled = untuple.map(|tup| {
1347 self.codegen_arguments_untupled(
1348 bx,
1349 &tup.node,
1350 &mut llargs,
1351 &fn_abi.args[first_args.len()..],
1352 &mut lifetime_ends_after_call,
1353 )
1354 });
1355
1356 let needs_location =
1357 instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1358 if needs_location {
1359 let mir_args = if let Some(num_untupled) = num_untupled {
1360 first_args.len() + num_untupled
1361 } else {
1362 args.len()
1363 };
1364 match (&fn_abi.args.len(), &(mir_args + 1)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::Some(format_args!("#[track_caller] fn\'s must have 1 more argument in their ABI than in their MIR: {0:?} {1:?} {2:?}",
instance, fn_span, fn_abi)));
}
}
};assert_eq!(
1365 fn_abi.args.len(),
1366 mir_args + 1,
1367 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1368 );
1369 let location = self.get_caller_location(bx, source_info);
1370 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1370",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1370u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("codegen_call_terminator({0:?}): location={1:?} (fn_span {2:?})",
terminator, location, fn_span) as &dyn Value))])
});
} else { ; }
};debug!(
1371 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1372 terminator, location, fn_span
1373 );
1374
1375 let last_arg = fn_abi.args.last().unwrap();
1376 self.codegen_argument(
1377 bx,
1378 location,
1379 false,
1380 &mut llargs,
1381 last_arg,
1382 &mut lifetime_ends_after_call,
1383 );
1384 }
1385
1386 let fn_ptr = match (instance, llfn) {
1387 (Some(instance), None) => bx.get_fn_addr(instance),
1388 (_, Some(llfn)) => llfn,
1389 _ => ::rustc_middle::util::bug::span_bug_fmt(fn_span,
format_args!("no instance or llfn for call"))span_bug!(fn_span, "no instance or llfn for call"),
1390 };
1391 self.set_debug_loc(bx, source_info);
1392 helper.do_call(
1393 self,
1394 bx,
1395 fn_abi,
1396 fn_ptr,
1397 &llargs,
1398 destination,
1399 unwind,
1400 &lifetime_ends_after_call,
1401 instance,
1402 kind,
1403 mergeable_succ,
1404 )
1405 }
1406
1407 fn codegen_asm_terminator(
1408 &mut self,
1409 helper: TerminatorCodegenHelper<'tcx>,
1410 bx: &mut Bx,
1411 asm_macro: InlineAsmMacro,
1412 terminator: &mir::Terminator<'tcx>,
1413 template: &[ast::InlineAsmTemplatePiece],
1414 operands: &[mir::InlineAsmOperand<'tcx>],
1415 options: ast::InlineAsmOptions,
1416 line_spans: &[Span],
1417 targets: &[mir::BasicBlock],
1418 unwind: mir::UnwindAction,
1419 instance: Instance<'_>,
1420 mergeable_succ: bool,
1421 ) -> MergingSucc {
1422 let span = terminator.source_info.span;
1423
1424 let operands: Vec<_> = operands
1425 .iter()
1426 .map(|op| match *op {
1427 mir::InlineAsmOperand::In { reg, ref value } => {
1428 let value = self.codegen_operand(bx, value);
1429 InlineAsmOperandRef::In { reg, value }
1430 }
1431 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1432 let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1433 InlineAsmOperandRef::Out { reg, late, place }
1434 }
1435 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1436 let in_value = self.codegen_operand(bx, in_value);
1437 let out_place =
1438 out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1439 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1440 }
1441 mir::InlineAsmOperand::Const { ref value } => {
1442 let const_value = self.eval_mir_constant(value);
1443 let string = common::asm_const_to_str(
1444 bx.tcx(),
1445 span,
1446 const_value,
1447 bx.layout_of(value.ty()),
1448 );
1449 InlineAsmOperandRef::Const { string }
1450 }
1451 mir::InlineAsmOperand::SymFn { ref value } => {
1452 let const_ = self.monomorphize(value.const_);
1453 if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1454 let instance = ty::Instance::resolve_for_fn_ptr(
1455 bx.tcx(),
1456 bx.typing_env(),
1457 def_id,
1458 args,
1459 )
1460 .unwrap();
1461 InlineAsmOperandRef::SymFn { instance }
1462 } else {
1463 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("invalid type for asm sym (fn)"));span_bug!(span, "invalid type for asm sym (fn)");
1464 }
1465 }
1466 mir::InlineAsmOperand::SymStatic { def_id } => {
1467 InlineAsmOperandRef::SymStatic { def_id }
1468 }
1469 mir::InlineAsmOperand::Label { target_index } => {
1470 InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1471 }
1472 })
1473 .collect();
1474
1475 helper.do_inlineasm(
1476 self,
1477 bx,
1478 template,
1479 &operands,
1480 options,
1481 line_spans,
1482 if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1483 unwind,
1484 instance,
1485 mergeable_succ,
1486 )
1487 }
1488
1489 pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1490 let llbb = match self.try_llbb(bb) {
1491 Some(llbb) => llbb,
1492 None => return,
1493 };
1494 let bx = &mut Bx::build(self.cx, llbb);
1495 let mir = self.mir;
1496
1497 loop {
1501 let data = &mir[bb];
1502
1503 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1503",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1503u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("codegen_block({0:?}={1:?})",
bb, data) as &dyn Value))])
});
} else { ; }
};debug!("codegen_block({:?}={:?})", bb, data);
1504
1505 for statement in &data.statements {
1506 self.codegen_statement(bx, statement);
1507 }
1508 self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1509
1510 let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1511 if let MergingSucc::False = merging_succ {
1512 break;
1513 }
1514
1515 let mut successors = data.terminator().successors();
1523 let succ = successors.next().unwrap();
1524 if !#[allow(non_exhaustive_omitted_patterns)] match self.cached_llbbs[succ] {
CachedLlbb::None => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(self.cached_llbbs[succ], CachedLlbb::None)")
};assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1525 self.cached_llbbs[succ] = CachedLlbb::Skip;
1526 bb = succ;
1527 }
1528 }
1529
1530 pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1531 let llbb = match self.try_llbb(bb) {
1532 Some(llbb) => llbb,
1533 None => return,
1534 };
1535 let bx = &mut Bx::build(self.cx, llbb);
1536 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1536",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1536u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("codegen_block_as_unreachable({0:?})",
bb) as &dyn Value))])
});
} else { ; }
};debug!("codegen_block_as_unreachable({:?})", bb);
1537 bx.unreachable();
1538 }
1539
1540 fn codegen_terminator(
1541 &mut self,
1542 bx: &mut Bx,
1543 bb: mir::BasicBlock,
1544 terminator: &'tcx mir::Terminator<'tcx>,
1545 ) -> MergingSucc {
1546 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1546",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1546u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("codegen_terminator: {0:?}",
terminator) as &dyn Value))])
});
} else { ; }
};debug!("codegen_terminator: {:?}", terminator);
1547
1548 let helper = TerminatorCodegenHelper { bb, terminator };
1549
1550 let mergeable_succ = || {
1551 let mut successors = terminator.successors();
1554 if let Some(succ) = successors.next()
1555 && successors.next().is_none()
1556 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1557 {
1558 match (&succ_pred, &bb) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(succ_pred, bb);
1561 true
1562 } else {
1563 false
1564 }
1565 };
1566
1567 self.set_debug_loc(bx, terminator.source_info);
1568 match terminator.kind {
1569 mir::TerminatorKind::UnwindResume => {
1570 self.codegen_resume_terminator(helper, bx);
1571 MergingSucc::False
1572 }
1573
1574 mir::TerminatorKind::UnwindTerminate(reason) => {
1575 self.codegen_terminate_terminator(helper, bx, terminator, reason);
1576 MergingSucc::False
1577 }
1578
1579 mir::TerminatorKind::Goto { target } => {
1580 helper.funclet_br(self, bx, target, mergeable_succ())
1581 }
1582
1583 mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1584 self.codegen_switchint_terminator(helper, bx, discr, targets);
1585 MergingSucc::False
1586 }
1587
1588 mir::TerminatorKind::Return => {
1589 self.codegen_return_terminator(bx);
1590 MergingSucc::False
1591 }
1592
1593 mir::TerminatorKind::Unreachable => {
1594 bx.unreachable();
1595 MergingSucc::False
1596 }
1597
1598 mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop } => {
1599 if !drop.is_none() {
{
::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
}
};assert!(
1600 drop.is_none(),
1601 "Async Drop must be expanded or reset to sync before codegen"
1602 );
1603 self.codegen_drop_terminator(
1604 helper,
1605 bx,
1606 &terminator.source_info,
1607 place,
1608 target,
1609 unwind,
1610 mergeable_succ(),
1611 )
1612 }
1613
1614 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1615 .codegen_assert_terminator(
1616 helper,
1617 bx,
1618 terminator,
1619 cond,
1620 expected,
1621 msg,
1622 target,
1623 unwind,
1624 mergeable_succ(),
1625 ),
1626
1627 mir::TerminatorKind::Call {
1628 ref func,
1629 ref args,
1630 destination,
1631 target,
1632 unwind,
1633 call_source: _,
1634 fn_span,
1635 } => self.codegen_call_terminator(
1636 helper,
1637 bx,
1638 terminator,
1639 func,
1640 args,
1641 destination,
1642 target,
1643 unwind,
1644 fn_span,
1645 CallKind::Normal,
1646 mergeable_succ(),
1647 ),
1648 mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1649 .codegen_call_terminator(
1650 helper,
1651 bx,
1652 terminator,
1653 func,
1654 args,
1655 mir::Place::from(mir::RETURN_PLACE),
1656 None,
1657 mir::UnwindAction::Unreachable,
1658 fn_span,
1659 CallKind::Tail,
1660 mergeable_succ(),
1661 ),
1662 mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1663 ::rustc_middle::util::bug::bug_fmt(format_args!("coroutine ops in codegen"))bug!("coroutine ops in codegen")
1664 }
1665 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1666 ::rustc_middle::util::bug::bug_fmt(format_args!("borrowck false edges in codegen"))bug!("borrowck false edges in codegen")
1667 }
1668
1669 mir::TerminatorKind::InlineAsm {
1670 asm_macro,
1671 template,
1672 ref operands,
1673 options,
1674 line_spans,
1675 ref targets,
1676 unwind,
1677 } => self.codegen_asm_terminator(
1678 helper,
1679 bx,
1680 asm_macro,
1681 terminator,
1682 template,
1683 operands,
1684 options,
1685 line_spans,
1686 targets,
1687 unwind,
1688 self.instance,
1689 mergeable_succ(),
1690 ),
1691 }
1692 }
1693
1694 fn codegen_argument(
1695 &mut self,
1696 bx: &mut Bx,
1697 op: OperandRef<'tcx, Bx::Value>,
1698 by_move: bool,
1699 llargs: &mut Vec<Bx::Value>,
1700 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1701 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1702 ) {
1703 match arg.mode {
1704 PassMode::Ignore => return,
1705 PassMode::Cast { pad_i32: true, .. } => {
1706 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1708 }
1709 PassMode::Pair(..) => match op.val {
1710 Pair(a, b) => {
1711 llargs.push(a);
1712 llargs.push(b);
1713 return;
1714 }
1715 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for pair argument",
op))bug!("codegen_argument: {:?} invalid for pair argument", op),
1716 },
1717 PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1718 Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1719 llargs.push(a);
1720 llargs.push(b);
1721 return;
1722 }
1723 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for unsized indirect argument",
op))bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1724 },
1725 _ => {}
1726 }
1727
1728 let (mut llval, align, by_ref) = match op.val {
1730 Immediate(_) | Pair(..) => match arg.mode {
1731 PassMode::Indirect { attrs, .. } => {
1732 let required_align = match attrs.pointee_align {
1736 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1737 None => arg.layout.align.abi,
1738 };
1739 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1740 bx.lifetime_start(scratch.llval, arg.layout.size);
1741 op.store_with_annotation(bx, scratch.with_type(arg.layout));
1742 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1743 (scratch.llval, scratch.align, true)
1744 }
1745 PassMode::Cast { .. } => {
1746 let scratch = PlaceRef::alloca(bx, arg.layout);
1747 op.store_with_annotation(bx, scratch);
1748 (scratch.val.llval, scratch.val.align, true)
1749 }
1750 PassMode::Direct(_) => (op.immediate(), arg.layout.align.abi, false),
1751 PassMode::Ignore | PassMode::Pair(..) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("handled above")));
}unreachable!("handled above"),
1752 },
1753 Ref(op_place_val) => match arg.mode {
1754 PassMode::Indirect { attrs, on_stack, .. } => {
1755 let required_align = match attrs.pointee_align {
1759 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1760 None => arg.layout.align.abi,
1761 };
1762 if op_place_val.align < required_align || (!on_stack && !by_move) {
1764 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1765 bx.lifetime_start(scratch.llval, arg.layout.size);
1766 op.store_with_annotation(bx, scratch.with_type(arg.layout));
1767 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1768 (scratch.llval, scratch.align, true)
1769 } else {
1770 (op_place_val.llval, op_place_val.align, true)
1771 }
1772 }
1773 _ => (op_place_val.llval, op_place_val.align, true),
1774 },
1775 ZeroSized => match arg.mode {
1776 PassMode::Indirect { on_stack, .. } => {
1777 if on_stack {
1778 ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} passed on stack with abi {1:?}",
op, arg));bug!("ZST {op:?} passed on stack with abi {arg:?}");
1781 }
1782 let scratch = PlaceRef::alloca(bx, arg.layout);
1786 (scratch.val.llval, scratch.val.align, true)
1787 }
1788 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} wasn\'t ignored, but was passed with abi {1:?}",
op, arg))bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1789 },
1790 };
1791
1792 if by_ref && !arg.is_indirect() {
1793 if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1795 let scratch_size = cast.size(bx);
1799 let scratch_align = cast.align(bx);
1800 let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1807 let llscratch = bx.alloca(scratch_size, scratch_align);
1809 bx.lifetime_start(llscratch, scratch_size);
1810 bx.memcpy(
1812 llscratch,
1813 scratch_align,
1814 llval,
1815 align,
1816 bx.const_usize(copy_bytes),
1817 MemFlags::empty(),
1818 None,
1819 );
1820 llval = load_cast(bx, cast, llscratch, scratch_align);
1822 bx.lifetime_end(llscratch, scratch_size);
1823 } else {
1824 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1830 if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1831 if scalar.is_bool() {
1832 bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1833 }
1834 llval = bx.to_immediate_scalar(llval, scalar);
1836 }
1837 }
1838 }
1839
1840 llargs.push(llval);
1841 }
1842
1843 fn codegen_arguments_untupled(
1844 &mut self,
1845 bx: &mut Bx,
1846 operand: &mir::Operand<'tcx>,
1847 llargs: &mut Vec<Bx::Value>,
1848 args: &[ArgAbi<'tcx, Ty<'tcx>>],
1849 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1850 ) -> usize {
1851 let tuple = self.codegen_operand(bx, operand);
1852 let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
mir::Operand::Move(_) => true,
_ => false,
}matches!(operand, mir::Operand::Move(_));
1853
1854 if let Ref(place_val) = tuple.val {
1856 if place_val.llextra.is_some() {
1857 ::rustc_middle::util::bug::bug_fmt(format_args!("closure arguments must be sized"));bug!("closure arguments must be sized");
1858 }
1859 let tuple_ptr = place_val.with_type(tuple.layout);
1860 for i in 0..tuple.layout.fields.count() {
1861 let field_ptr = tuple_ptr.project_field(bx, i);
1862 let field = bx.load_operand(field_ptr);
1863 self.codegen_argument(
1864 bx,
1865 field,
1866 by_move,
1867 llargs,
1868 &args[i],
1869 lifetime_ends_after_call,
1870 );
1871 }
1872 } else {
1873 for i in 0..tuple.layout.fields.count() {
1875 let op = tuple.extract_field(self, bx, i);
1876 self.codegen_argument(bx, op, by_move, llargs, &args[i], lifetime_ends_after_call);
1877 }
1878 }
1879 tuple.layout.fields.count()
1880 }
1881
1882 pub(super) fn get_caller_location(
1883 &mut self,
1884 bx: &mut Bx,
1885 source_info: mir::SourceInfo,
1886 ) -> OperandRef<'tcx, Bx::Value> {
1887 self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1888 let const_loc = bx.tcx().span_as_caller_location(span);
1889 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1890 })
1891 }
1892
1893 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1894 let cx = bx.cx();
1895 if let Some(slot) = self.personality_slot {
1896 slot
1897 } else {
1898 let layout = cx.layout_of(Ty::new_tup(
1899 cx.tcx(),
1900 &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1901 ));
1902 let slot = PlaceRef::alloca(bx, layout);
1903 self.personality_slot = Some(slot);
1904 slot
1905 }
1906 }
1907
1908 fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1911 if let Some(landing_pad) = self.landing_pads[bb] {
1912 return landing_pad;
1913 }
1914
1915 let landing_pad = self.landing_pad_for_uncached(bb);
1916 self.landing_pads[bb] = Some(landing_pad);
1917 landing_pad
1918 }
1919
1920 fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1922 let llbb = self.llbb(bb);
1923 if base::wants_new_eh_instructions(self.cx.sess()) {
1924 let cleanup_bb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("funclet_{0:?}", bb))
})format!("funclet_{bb:?}"));
1925 let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
1926 let funclet = cleanup_bx.cleanup_pad(None, &[]);
1927 cleanup_bx.br(llbb);
1928 self.funclets[bb] = Some(funclet);
1929 cleanup_bb
1930 } else {
1931 let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1932 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1933
1934 let llpersonality = self.cx.eh_personality();
1935 let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1936
1937 let slot = self.get_personality_slot(&mut cleanup_bx);
1938 slot.storage_live(&mut cleanup_bx);
1939 Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1940
1941 cleanup_bx.br(llbb);
1942 cleanup_llbb
1943 }
1944 }
1945
1946 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1947 self.unreachable_block.unwrap_or_else(|| {
1948 let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1949 let mut bx = Bx::build(self.cx, llbb);
1950 bx.unreachable();
1951 self.unreachable_block = Some(llbb);
1952 llbb
1953 })
1954 }
1955
1956 fn terminate_block(
1957 &mut self,
1958 reason: UnwindTerminateReason,
1959 outer_catchpad_bb: Option<mir::BasicBlock>,
1960 ) -> Bx::BasicBlock {
1961 if true {
if !(outer_catchpad_bb.is_some() ==
(base::wants_wasm_eh(self.cx.tcx().sess) &&
reason == UnwindTerminateReason::InCleanup)) {
::core::panicking::panic("assertion failed: outer_catchpad_bb.is_some() ==\n (base::wants_wasm_eh(self.cx.tcx().sess) &&\n reason == UnwindTerminateReason::InCleanup)")
};
};debug_assert!(
1966 outer_catchpad_bb.is_some()
1967 == (base::wants_wasm_eh(self.cx.tcx().sess)
1968 && reason == UnwindTerminateReason::InCleanup)
1969 );
1970
1971 let mut cache_bb = mir::START_BLOCK;
1974 if let Some(outer_bb) = outer_catchpad_bb {
1977 let cleanup_kinds =
1978 self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
1979 cache_bb = cleanup_kinds[outer_bb]
1980 .funclet_bb(outer_bb)
1981 .expect("funclet_bb should be in a funclet");
1982
1983 if self.funclets[cache_bb].is_none() {
1985 self.landing_pad_for(cache_bb);
1986 }
1987 }
1988 if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
1989 && reason == cached_reason
1990 {
1991 return cached_bb;
1992 }
1993
1994 let funclet;
1995 let llbb;
1996 let mut bx;
1997 if base::wants_new_eh_instructions(self.cx.sess()) {
1998 llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
2038
2039 let mut cs_bx = Bx::build(self.cx, llbb);
2040
2041 let mut outer_cleanuppad = None;
2045 if outer_catchpad_bb.is_some() {
2046 let outer_funclet = self.funclets[cache_bb]
2048 .as_ref()
2049 .expect("landing_pad_for didn't create funclet");
2050 outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2051 }
2052 let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2053 let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2054 drop(cs_bx);
2055
2056 bx = Bx::build(self.cx, cp_llbb);
2057 let null =
2058 bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2059
2060 let args = if base::wants_msvc_seh(self.cx.sess()) {
2064 let adjectives = bx.const_i32(0x40);
2071 &[null, adjectives, null] as &[_]
2072 } else {
2073 &[null] as &[_]
2079 };
2080
2081 funclet = Some(bx.catch_pad(cs, args));
2082 } else {
2088 llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2089 bx = Bx::build(self.cx, llbb);
2090
2091 let llpersonality = self.cx.eh_personality();
2092 bx.filter_landing_pad(llpersonality);
2093
2094 funclet = None;
2095 }
2096
2097 self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2098
2099 let (fn_abi, fn_ptr, instance) =
2100 common::build_langcall(&bx, self.mir.span, reason.lang_item());
2101 if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2102 bx.abort();
2103 } else {
2104 let fn_ty = bx.fn_decl_backend_type(fn_abi);
2105
2106 let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
2107 bx.apply_attrs_to_cleanup_callsite(llret);
2108 }
2109
2110 bx.unreachable();
2111
2112 self.terminate_blocks[cache_bb] = Some((llbb, reason));
2113 llbb
2114 }
2115
2116 pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2121 self.try_llbb(bb).unwrap()
2122 }
2123
2124 pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2126 match self.cached_llbbs[bb] {
2127 CachedLlbb::None => {
2128 let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", bb))
})format!("{bb:?}"));
2129 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2130 Some(llbb)
2131 }
2132 CachedLlbb::Some(llbb) => Some(llbb),
2133 CachedLlbb::Skip => None,
2134 }
2135 }
2136
2137 fn make_return_dest(
2138 &mut self,
2139 bx: &mut Bx,
2140 dest: mir::Place<'tcx>,
2141 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2142 llargs: &mut Vec<Bx::Value>,
2143 ) -> ReturnDest<'tcx, Bx::Value> {
2144 if fn_ret.is_ignore() {
2146 return ReturnDest::Nothing;
2147 }
2148 let dest = if let Some(index) = dest.as_local() {
2149 match self.locals[index] {
2150 LocalRef::Place(dest) => dest,
2151 LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
2152 LocalRef::PendingOperand => {
2153 return if fn_ret.is_indirect() {
2156 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2159 tmp.storage_live(bx);
2160 llargs.push(tmp.val.llval);
2161 ReturnDest::IndirectOperand(tmp, index)
2162 } else {
2163 ReturnDest::DirectOperand(index)
2164 };
2165 }
2166 LocalRef::Operand(_) => {
2167 ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
2168 }
2169 }
2170 } else {
2171 self.codegen_place(bx, dest.as_ref())
2172 };
2173 if fn_ret.is_indirect() {
2174 if dest.val.align < dest.layout.align.abi {
2175 ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
2182 }
2183 llargs.push(dest.val.llval);
2184 ReturnDest::Nothing
2185 } else {
2186 ReturnDest::Store(dest)
2187 }
2188 }
2189
2190 fn store_return(
2192 &mut self,
2193 bx: &mut Bx,
2194 dest: ReturnDest<'tcx, Bx::Value>,
2195 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2196 llval: Bx::Value,
2197 ) {
2198 use self::ReturnDest::*;
2199 let retags_enabled = bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some();
2200 match dest {
2201 Nothing => (),
2202 Store(dst) => {
2203 bx.store_arg(ret_abi, llval, dst);
2204 if retags_enabled {
2205 self.codegen_retag_place(bx, dst, false);
2206 }
2207 }
2208 IndirectOperand(tmp, index) => {
2209 let mut op = bx.load_operand(tmp);
2210 tmp.storage_dead(bx);
2211 if retags_enabled {
2212 op = self.codegen_retag_operand(bx, op, false);
2213 }
2214 self.overwrite_local(index, LocalRef::Operand(op));
2215 self.debug_introduce_local(bx, index);
2216 }
2217 DirectOperand(index) => {
2218 let mut op = if let PassMode::Cast { .. } = ret_abi.mode {
2220 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2221 tmp.storage_live(bx);
2222 bx.store_arg(ret_abi, llval, tmp);
2223 let op = bx.load_operand(tmp);
2224 tmp.storage_dead(bx);
2225 op
2226 } else {
2227 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2228 };
2229 if retags_enabled {
2230 op = self.codegen_retag_operand(bx, op, false);
2231 }
2232 self.overwrite_local(index, LocalRef::Operand(op));
2233 self.debug_introduce_local(bx, index);
2234 }
2235 }
2236 }
2237}
2238
2239enum ReturnDest<'tcx, V> {
2240 Nothing,
2242 Store(PlaceRef<'tcx, V>),
2244 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2246 DirectOperand(mir::Local),
2248}
2249
2250fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2251 bx: &mut Bx,
2252 cast: &CastTarget,
2253 ptr: Bx::Value,
2254 align: Align,
2255) -> Bx::Value {
2256 let cast_ty = bx.cast_backend_type(cast);
2257 if let Some(offset_from_start) = cast.rest_offset {
2258 match (&cast.prefix.len(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(cast.prefix.len(), 1);
2259 match (&cast.rest.unit.size, &cast.rest.total) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(cast.rest.unit.size, cast.rest.total);
2260 let first_ty = bx.reg_backend_type(&cast.prefix[0]);
2261 let second_ty = bx.reg_backend_type(&cast.rest.unit);
2262 let first = bx.load(first_ty, ptr, align);
2263 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2264 let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2265 let res = bx.cx().const_poison(cast_ty);
2266 let res = bx.insert_value(res, first, 0);
2267 bx.insert_value(res, second, 1)
2268 } else {
2269 bx.load(cast_ty, ptr, align)
2270 }
2271}
2272
2273pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2274 bx: &mut Bx,
2275 cast: &CastTarget,
2276 value: Bx::Value,
2277 ptr: Bx::Value,
2278 align: Align,
2279) {
2280 if let Some(offset_from_start) = cast.rest_offset {
2281 match (&cast.prefix.len(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(cast.prefix.len(), 1);
2282 match (&cast.rest.unit.size, &cast.rest.total) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(cast.rest.unit.size, cast.rest.total);
2283 let first = bx.extract_value(value, 0);
2284 let second = bx.extract_value(value, 1);
2285 bx.store(first, ptr, align);
2286 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2287 bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2288 } else {
2289 bx.store(value, ptr, align);
2290 };
2291}