1use std::iter;
23use rustc_index::IndexVec;
4use rustc_index::bit_set::DenseBitSet;
5use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
6use rustc_middle::mir::{Body, Local, UnwindTerminateReason, traversal};
7use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, TyAndLayout};
8use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable, TypeVisitableExt};
9use rustc_middle::{bug, mir, span_bug};
10use rustc_span::ErrorGuaranteed;
11use rustc_target::callconv::{FnAbi, PassMode};
12use tracing::{debug, instrument};
1314use crate::base;
15use crate::traits::*;
1617mod analyze;
18mod block;
19mod constant;
20mod coverageinfo;
21pub mod debuginfo;
22mod intrinsic;
23mod locals;
24pub mod naked_asm;
25pub mod operand;
26pub mod place;
27mod retag;
28mod rvalue;
29mod statement;
3031pub use self::block::store_cast;
32use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
33use self::operand::{OperandRef, OperandValue};
34use self::place::PlaceRef;
3536// Used for tracking the state of generated basic blocks.
37enum CachedLlbb<T> {
38/// Nothing created yet.
39None,
4041/// Has been created.
42Some(T),
4344/// Nothing created yet, and nothing should be.
45Skip,
46}
4748type PerLocalVarDebugInfoIndexVec<'tcx, V> =
49IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, V>>>;
5051/// Master context for codegenning from MIR.
52pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
53 instance: Instance<'tcx>,
5455 mir: &'tcx mir::Body<'tcx>,
5657 debug_context: Option<FunctionDebugContext<'tcx, Bx::DIScope, Bx::DILocation>>,
5859 llfn: Bx::Function,
6061 cx: &'a Bx::CodegenCx,
6263 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
6465/// When unwinding is initiated, we have to store this personality
66 /// value somewhere so that we can load it and re-use it in the
67 /// resume instruction. The personality is (afaik) some kind of
68 /// value used for C++ unwinding, which must filter by type: we
69 /// don't really care about it very much. Anyway, this value
70 /// contains an alloca into which the personality is stored and
71 /// then later loaded when generating the DIVERGE_BLOCK.
72personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
7374/// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
75 /// as-needed (e.g. RPO reaching it or another block branching to it).
76// FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
77 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
78cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>>,
7980/// The funclet status of each basic block
81cleanup_kinds: Option<IndexVec<mir::BasicBlock, analyze::CleanupKind>>,
8283/// When targeting MSVC, this stores the cleanup info for each funclet BB.
84 /// This is initialized at the same time as the `landing_pads` entry for the
85 /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
86funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
8788/// This stores the cached landing/cleanup pad block for a given BB.
89// FIXME(eddyb) rename this to `eh_pads`.
90landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
9192/// Cached unreachable block
93unreachable_block: Option<Bx::BasicBlock>,
9495/// Cached terminate upon unwinding block and its reason. For non-wasm
96 /// targets, there is at most one such block per function, stored at index
97 /// `START_BLOCK`. For wasm targets, each funclet needs its own terminate
98 /// block, indexed by the cleanup block that is the funclet's head.
99terminate_blocks: IndexVec<mir::BasicBlock, Option<(Bx::BasicBlock, UnwindTerminateReason)>>,
100101/// A bool flag for each basic block indicating whether it is a cold block.
102 /// A cold block is a block that is unlikely to be executed at runtime.
103cold_blocks: IndexVec<mir::BasicBlock, bool>,
104105/// The location where each MIR arg/var/tmp/ret is stored. This is
106 /// usually an `PlaceRef` representing an alloca, but not always:
107 /// sometimes we can skip the alloca and just store the value
108 /// directly using an `OperandRef`, which makes for tighter LLVM
109 /// IR. The conditions for using an `OperandRef` are as follows:
110 ///
111 /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
112 /// - the operand must never be referenced indirectly
113 /// - we should not take its address using the `&` operator
114 /// - nor should it appear in a place path like `tmp.a`
115 /// - the operand must be defined by an rvalue that can generate immediate
116 /// values
117 ///
118 /// Avoiding allocs can also be important for certain intrinsics,
119 /// notably `expect`.
120locals: locals::Locals<'tcx, Bx::Value>,
121122/// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
123 /// This is `None` if no variable debuginfo/names are needed.
124per_local_var_debug_info: Option<PerLocalVarDebugInfoIndexVec<'tcx, Bx::DIVariable>>,
125126/// Caller location propagated if this function has `#[track_caller]`.
127caller_location: Option<OperandRef<'tcx, Bx::Value>>,
128}
129130impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
131pub fn monomorphize<T>(&self, value: T) -> T
132where
133T: Copy + TypeFoldable<TyCtxt<'tcx>>,
134 {
135{
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/mod.rs:135",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(135u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::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!("monomorphize: self.instance={0:?}",
self.instance) as &dyn Value))])
});
} else { ; }
};debug!("monomorphize: self.instance={:?}", self.instance);
136self.instance.instantiate_mir_and_normalize_erasing_regions(
137self.cx.tcx(),
138self.cx.typing_env(),
139 ty::EarlyBinder::bind(value),
140 )
141 }
142}
143144enum LocalRef<'tcx, V> {
145 Place(PlaceRef<'tcx, V>),
146/// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
147 /// `*p` is the wide pointer that references the actual unsized place.
148 ///
149 /// MIR only supports unsized args, not dynamically-sized locals, so
150 /// new unsized temps don't exist and we must reuse the referred-to place.
151 ///
152 /// FIXME: Since the removal of unsized locals in <https://github.com/rust-lang/rust/pull/142911>,
153 /// can we maybe use `Place` here? Or refactor it in another way? There are quite a few
154 /// `UnsizedPlace => bug` branches now.
155UnsizedPlace(PlaceRef<'tcx, V>),
156/// The backend [`OperandValue`] has already been generated.
157Operand(OperandRef<'tcx, V>),
158/// Will be a `Self::Operand` once we get to its definition.
159PendingOperand,
160}
161162pub enum IntrinsicResult<'tcx, V> {
163/// This intrinsic created an operand without using the `result_place` argument.
164 ///
165 /// `codegen_call_terminator` will handle writing the result into the place,
166 /// if doing so is needed.
167 ///
168 /// The vast majority of intrinsics can do this, see MCP#970
169Operand(OperandValue<V>),
170171/// The intrinsic wrote its result into the `result_place` argument.
172 ///
173 /// Most things don't need to do this, but there are some: `volatile_load`
174 /// of a non-scalar type, for example, has to.
175WroteIntoPlace,
176177/// Another instance should be called instead. This is used to invoke intrinsic
178 /// default bodies in case an intrinsic is not implemented by the backend.
179Fallback(ty::Instance<'tcx>),
180181/// Arguably this shouldn't exist, per MCP#620, but a bunch do it.
182Err(ErrorGuaranteed),
183}
184185impl<'tcx, V: CodegenObject> LocalRef<'tcx, V> {
186fn new_operand(layout: TyAndLayout<'tcx>) -> LocalRef<'tcx, V> {
187if layout.is_zst() {
188// Zero-size temporaries aren't always initialized, which
189 // doesn't matter because they don't contain data, but
190 // we need something sufficiently aligned in the operand.
191LocalRef::Operand(OperandRef::zero_sized(layout))
192 } else {
193 LocalRef::PendingOperand194 }
195 }
196}
197198///////////////////////////////////////////////////////////////////////////
199200#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::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_mir",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(200u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["instance"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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(&instance)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
if !!instance.args.has_infer() {
::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};
let tcx = cx.tcx();
let llfn = cx.get_fn(instance);
let mut mir = tcx.instance_mir(instance.def);
let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
{
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/mod.rs:216",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(216u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::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!("fn_abi: {0:?}",
fn_abi) as &dyn Value))])
});
} else { ; }
};
if tcx.features().ergonomic_clones() {
let monomorphized_mir =
instance.instantiate_mir_and_normalize_erasing_regions(tcx,
ty::TypingEnv::fully_monomorphized(),
ty::EarlyBinder::bind(mir.clone()));
mir =
tcx.arena.alloc(optimize_use_clone::<Bx>(cx,
monomorphized_mir));
}
let start_llbb = Bx::append_block(cx, llfn, "start");
let mut start_bx = Bx::build(cx, start_llbb);
if mir.basic_blocks.iter().any(|bb|
{
bb.is_cleanup ||
#[allow(non_exhaustive_omitted_patterns)] match bb.terminator().unwind()
{
Some(mir::UnwindAction::Terminate(_)) => true,
_ => false,
}
}) {
start_bx.set_personality_fn(cx.eh_personality());
}
let cleanup_kinds =
base::wants_new_eh_instructions(tcx.sess).then(||
analyze::cleanup_kinds(&mir));
let cached_llbbs:
IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
mir.basic_blocks.indices().map(|bb|
{
if bb == mir::START_BLOCK {
CachedLlbb::Some(start_llbb)
} else { CachedLlbb::None }
}).collect();
let mut fx =
FunctionCx {
instance,
mir,
llfn,
fn_abi,
cx,
personality_slot: None,
cached_llbbs,
unreachable_block: None,
terminate_blocks: IndexVec::from_elem(None,
&mir.basic_blocks),
cleanup_kinds,
landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
funclets: IndexVec::from_fn_n(|_| None,
mir.basic_blocks.len()),
cold_blocks: find_cold_blocks(tcx, mir),
locals: locals::Locals::empty(),
debug_context: None,
per_local_var_debug_info: None,
caller_location: None,
};
fx.fill_function_debug_context();
let (per_local_var_debug_info, consts_debug_info) =
fx.compute_per_local_var_debug_info(&mut start_bx).unzip();
fx.per_local_var_debug_info = per_local_var_debug_info;
let traversal_order =
traversal::mono_reachable_reverse_postorder(mir, tcx,
instance);
let memory_locals =
analyze::non_ssa_locals(&fx, &traversal_order);
let local_values =
{
let args =
arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
let mut allocate_local =
|local: Local|
{
let decl = &mir.local_decls[local];
let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
if !!layout.ty.has_erasable_regions() {
::core::panicking::panic("assertion failed: !layout.ty.has_erasable_regions()")
};
if local == mir::RETURN_PLACE {
match fx.fn_abi.ret.mode {
PassMode::Indirect { .. } => {
{
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/mod.rs:293",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(293u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::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!("alloc: {0:?} (return place) -> place",
local) as &dyn Value))])
});
} else { ; }
};
let llretptr = start_bx.get_param(0);
return LocalRef::Place(PlaceRef::new_sized(llretptr,
layout));
}
PassMode::Cast { ref cast, .. } => {
{
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/mod.rs:298",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(298u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::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!("alloc: {0:?} (return place) -> place",
local) as &dyn Value))])
});
} else { ; }
};
let size = cast.size(&start_bx).max(layout.size);
return LocalRef::Place(PlaceRef::alloca_size(&mut start_bx,
size, layout));
}
_ => {}
};
}
if memory_locals.contains(local) {
{
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/mod.rs:307",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(307u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::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!("alloc: {0:?} -> place",
local) as &dyn Value))])
});
} else { ; }
};
if layout.is_unsized() {
LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx,
layout))
} else {
LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
}
} 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/mod.rs:314",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(314u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::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!("alloc: {0:?} -> operand",
local) as &dyn Value))])
});
} else { ; }
};
LocalRef::new_operand(layout)
}
};
let retptr = allocate_local(mir::RETURN_PLACE);
iter::once(retptr).chain(args.into_iter()).chain(mir.vars_and_temps_iter().map(allocate_local)).collect()
};
fx.initialize_locals(local_values);
fx.debug_introduce_locals(&mut start_bx,
consts_debug_info.unwrap_or_default());
drop(start_bx);
let mut unreached_blocks =
DenseBitSet::new_filled(mir.basic_blocks.len());
for bb in traversal_order {
fx.codegen_block(bb);
unreached_blocks.remove(bb);
}
for bb in unreached_blocks.iter() {
fx.codegen_block_as_unreachable(bb);
}
}
}
}#[instrument(level = "debug", skip(cx))]201pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
202 cx: &'a Bx::CodegenCx,
203 instance: Instance<'tcx>,
204) {
205assert!(!instance.args.has_infer());
206207let tcx = cx.tcx();
208let llfn = cx.get_fn(instance);
209210let mut mir = tcx.instance_mir(instance.def);
211// Note that the ABI logic has deduced facts about the functions' parameters based on the MIR we
212 // got here (`deduce_param_attrs`). That means we can *not* apply arbitrary further MIR
213 // transforms as that may invalidate those deduced facts!
214215let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
216debug!("fn_abi: {:?}", fn_abi);
217218if tcx.features().ergonomic_clones() {
219let monomorphized_mir = instance.instantiate_mir_and_normalize_erasing_regions(
220 tcx,
221 ty::TypingEnv::fully_monomorphized(),
222 ty::EarlyBinder::bind(mir.clone()),
223 );
224 mir = tcx.arena.alloc(optimize_use_clone::<Bx>(cx, monomorphized_mir));
225 }
226227let start_llbb = Bx::append_block(cx, llfn, "start");
228let mut start_bx = Bx::build(cx, start_llbb);
229230if mir.basic_blocks.iter().any(|bb| {
231 bb.is_cleanup || matches!(bb.terminator().unwind(), Some(mir::UnwindAction::Terminate(_)))
232 }) {
233 start_bx.set_personality_fn(cx.eh_personality());
234 }
235236let cleanup_kinds =
237 base::wants_new_eh_instructions(tcx.sess).then(|| analyze::cleanup_kinds(&mir));
238239let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
240 mir.basic_blocks
241 .indices()
242 .map(|bb| {
243if bb == mir::START_BLOCK { CachedLlbb::Some(start_llbb) } else { CachedLlbb::None }
244 })
245 .collect();
246247let mut fx = FunctionCx {
248 instance,
249 mir,
250 llfn,
251 fn_abi,
252 cx,
253 personality_slot: None,
254 cached_llbbs,
255 unreachable_block: None,
256 terminate_blocks: IndexVec::from_elem(None, &mir.basic_blocks),
257 cleanup_kinds,
258 landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
259 funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
260 cold_blocks: find_cold_blocks(tcx, mir),
261 locals: locals::Locals::empty(),
262 debug_context: None,
263 per_local_var_debug_info: None,
264 caller_location: None,
265 };
266267// It may seem like we should iterate over `required_consts` to ensure they all successfully
268 // evaluate; however, the `MirUsedCollector` already did that during the collection phase of
269 // monomorphization, and if there is an error during collection then codegen never starts -- so
270 // we don't have to do it again.
271272fx.fill_function_debug_context();
273274let (per_local_var_debug_info, consts_debug_info) =
275 fx.compute_per_local_var_debug_info(&mut start_bx).unzip();
276 fx.per_local_var_debug_info = per_local_var_debug_info;
277278let traversal_order = traversal::mono_reachable_reverse_postorder(mir, tcx, instance);
279let memory_locals = analyze::non_ssa_locals(&fx, &traversal_order);
280281// Allocate variable and temp allocas
282let local_values = {
283let args = arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
284285let mut allocate_local = |local: Local| {
286let decl = &mir.local_decls[local];
287let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
288assert!(!layout.ty.has_erasable_regions());
289290if local == mir::RETURN_PLACE {
291match fx.fn_abi.ret.mode {
292 PassMode::Indirect { .. } => {
293debug!("alloc: {:?} (return place) -> place", local);
294let llretptr = start_bx.get_param(0);
295return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
296 }
297 PassMode::Cast { ref cast, .. } => {
298debug!("alloc: {:?} (return place) -> place", local);
299let size = cast.size(&start_bx).max(layout.size);
300return LocalRef::Place(PlaceRef::alloca_size(&mut start_bx, size, layout));
301 }
302_ => {}
303 };
304 }
305306if memory_locals.contains(local) {
307debug!("alloc: {:?} -> place", local);
308if layout.is_unsized() {
309 LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx, layout))
310 } else {
311 LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
312 }
313 } else {
314debug!("alloc: {:?} -> operand", local);
315 LocalRef::new_operand(layout)
316 }
317 };
318319let retptr = allocate_local(mir::RETURN_PLACE);
320 iter::once(retptr)
321 .chain(args.into_iter())
322 .chain(mir.vars_and_temps_iter().map(allocate_local))
323 .collect()
324 };
325 fx.initialize_locals(local_values);
326327// Apply debuginfo to the newly allocated locals.
328fx.debug_introduce_locals(&mut start_bx, consts_debug_info.unwrap_or_default());
329330// The builders will be created separately for each basic block at `codegen_block`.
331 // So drop the builder of `start_llbb` to avoid having two at the same time.
332drop(start_bx);
333334let mut unreached_blocks = DenseBitSet::new_filled(mir.basic_blocks.len());
335// Codegen the body of each reachable block using our reverse postorder list.
336for bb in traversal_order {
337 fx.codegen_block(bb);
338 unreached_blocks.remove(bb);
339 }
340341// FIXME: These empty unreachable blocks are *mostly* a waste. They are occasionally
342 // targets for a SwitchInt terminator, but the reimplementation of the mono-reachable
343 // simplification in SwitchInt lowering sometimes misses cases that
344 // mono_reachable_reverse_postorder manages to figure out.
345 // The solution is to do something like post-mono GVN. But for now we have this hack.
346for bb in unreached_blocks.iter() {
347 fx.codegen_block_as_unreachable(bb);
348 }
349}
350351/// Replace `clone` calls that come from `use` statements with direct copies if possible.
352// FIXME: Move this function to mir::transform when post-mono MIR passes land.
353fn optimize_use_clone<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
354 cx: &'a Bx::CodegenCx,
355mut mir: Body<'tcx>,
356) -> Body<'tcx> {
357let tcx = cx.tcx();
358359if tcx.features().ergonomic_clones() {
360for bb in mir.basic_blocks.as_mut() {
361let mir::TerminatorKind::Call {
362 args,
363 destination,
364 target,
365 call_source: mir::CallSource::Use,
366 ..
367 } = &bb.terminator().kind
368else {
369continue;
370 };
371372// CallSource::Use calls always use 1 argument.
373match (&args.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!(args.len(), 1);
374let arg = &args[0];
375376// These types are easily available from locals, so check that before
377 // doing DefId lookups to figure out what we're actually calling.
378let arg_ty = arg.node.ty(&mir.local_decls, tcx);
379380let ty::Ref(_region, inner_ty, mir::Mutability::Not) = *arg_ty.kind() else { continue };
381382if !tcx.type_is_copy_modulo_regions(cx.typing_env(), inner_ty) {
383continue;
384 }
385386let Some(arg_place) = arg.node.place() else { continue };
387388let destination_block = target.unwrap();
389390 bb.statements.push(mir::Statement::new(
391 bb.terminator().source_info,
392 mir::StatementKind::Assign(Box::new((
393*destination,
394 mir::Rvalue::Use(
395 mir::Operand::Copy(
396 arg_place.project_deeper(&[mir::ProjectionElem::Deref], tcx),
397 ),
398 mir::WithRetag::Yes,
399 ),
400 ))),
401 ));
402403 bb.terminator_mut().kind = mir::TerminatorKind::Goto { target: destination_block };
404 }
405 }
406407mir408}
409410/// Produces, for each argument, a `Value` pointing at the
411/// argument's value. As arguments are places, these are always
412/// indirect.
413fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
414 bx: &mut Bx,
415 fx: &mut FunctionCx<'a, 'tcx, Bx>,
416 memory_locals: &DenseBitSet<mir::Local>,
417) -> Vec<LocalRef<'tcx, Bx::Value>> {
418let mir = fx.mir;
419let mut idx = 0;
420let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
421422let mut num_untupled = None;
423424let codegen_fn_attrs = bx.tcx().codegen_instance_attrs(fx.instance.def);
425if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
426return ::alloc::vec::Vec::new()vec![];
427 }
428429let mut args = mir430 .args_iter()
431 .enumerate()
432 .map(|(arg_index, local)| {
433let arg_decl = &mir.local_decls[local];
434let arg_ty = fx.monomorphize(arg_decl.ty);
435436if Some(local) == mir.spread_arg {
437// This argument (e.g., the last argument in the "rust-call" ABI)
438 // is a tuple that was spread at the ABI level and now we have
439 // to reconstruct it into a tuple local variable, from multiple
440 // individual LLVM function arguments.
441let ty::Tuple(tupled_arg_tys) = arg_ty.kind() else {
442::rustc_middle::util::bug::bug_fmt(format_args!("spread argument isn\'t a tuple?!"));bug!("spread argument isn't a tuple?!");
443 };
444445let layout = bx.layout_of(arg_ty);
446447// FIXME: support unsized params in "rust-call" ABI
448if layout.is_unsized() {
449::rustc_middle::util::bug::span_bug_fmt(arg_decl.source_info.span,
format_args!("\"rust-call\" ABI does not support unsized params"));span_bug!(
450 arg_decl.source_info.span,
451"\"rust-call\" ABI does not support unsized params",
452 );
453 }
454455let place = PlaceRef::alloca(bx, layout);
456for i in 0..tupled_arg_tys.len() {
457let arg = &fx.fn_abi.args[idx];
458 idx += 1;
459if let PassMode::Cast { pad_i32: true, .. } = arg.mode {
460 llarg_idx += 1;
461 }
462let pr_field = place.project_field(bx, i);
463 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
464 }
465match (&None, &num_untupled.replace(tupled_arg_tys.len())) {
(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!("Replaced existing num_untupled")));
}
}
};assert_eq!(
466None,
467 num_untupled.replace(tupled_arg_tys.len()),
468"Replaced existing num_untupled"
469);
470471return LocalRef::Place(place);
472 }
473474if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
475let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
476477// Explicitly start the lifetime of the `va_list`, improves LLVM codegen.
478bx.lifetime_start(va_list.val.llval, va_list.layout.size);
479480bx.va_start(va_list.val.llval);
481482return LocalRef::Place(va_list);
483 }
484485let arg = &fx.fn_abi.args[idx];
486idx += 1;
487if let PassMode::Cast { pad_i32: true, .. } = arg.mode {
488llarg_idx += 1;
489 }
490491if !memory_locals.contains(local) {
492// We don't have to cast or keep the argument in the alloca.
493 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
494 // of putting everything in allocas just so we can use llvm.dbg.declare.
495let local = |op| LocalRef::Operand(op);
496match arg.mode {
497 PassMode::Ignore => {
498return local(OperandRef::zero_sized(arg.layout));
499 }
500 PassMode::Direct(_) => {
501let llarg = bx.get_param(llarg_idx);
502llarg_idx += 1;
503if true {
if !bx.is_backend_immediate(arg.layout) {
::core::panicking::panic("assertion failed: bx.is_backend_immediate(arg.layout)")
};
};debug_assert!(bx.is_backend_immediate(arg.layout));
504return local(OperandRef {
505 val: OperandValue::Immediate(llarg),
506 layout: arg.layout,
507 move_annotation: None,
508 });
509 }
510 PassMode::Pair(..) => {
511let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
512llarg_idx += 2;
513514return local(OperandRef {
515 val: OperandValue::Pair(a, b),
516 layout: arg.layout,
517 move_annotation: None,
518 });
519 }
520_ => {}
521 }
522 }
523524match arg.mode {
525// Sized indirect arguments
526PassMode::Indirect { attrs, meta_attrs: None, on_stack: _ } => {
527// Don't copy an indirect argument to an alloca, the caller already put it
528 // in a temporary alloca and gave it up.
529 // FIXME: lifetimes
530if let Some(pointee_align) = attrs.pointee_align
531 && pointee_align < arg.layout.align.abi
532 {
533// ...unless the argument is underaligned, then we need to copy it to
534 // a higher-aligned alloca.
535let tmp = PlaceRef::alloca(bx, arg.layout);
536bx.store_fn_arg(arg, &mut llarg_idx, tmp);
537 LocalRef::Place(tmp)
538 } else {
539let llarg = bx.get_param(llarg_idx);
540llarg_idx += 1;
541 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
542 }
543 }
544// Unsized indirect arguments
545PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
546// As the storage for the indirect argument lives during
547 // the whole function call, we just copy the wide pointer.
548let llarg = bx.get_param(llarg_idx);
549llarg_idx += 1;
550let llextra = bx.get_param(llarg_idx);
551llarg_idx += 1;
552let indirect_operand = OperandValue::Pair(llarg, llextra);
553554let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
555indirect_operand.store(bx, tmp);
556 LocalRef::UnsizedPlace(tmp)
557 }
558_ => {
559let tmp = PlaceRef::alloca(bx, arg.layout);
560bx.store_fn_arg(arg, &mut llarg_idx, tmp);
561 LocalRef::Place(tmp)
562 }
563 }
564 })
565 .collect::<Vec<_>>();
566if bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
567args = args568 .iter()
569 .map(|arg| match arg {
570&LocalRef::Place(place_ref) => {
571fx.codegen_retag_place(bx, place_ref, true);
572 LocalRef::Place(place_ref)
573 }
574&LocalRef::UnsizedPlace(place_ref) => {
575let operand = bx.load_operand(place_ref);
576let retagged = fx.codegen_retag_operand(bx, operand, true);
577if !#[allow(non_exhaustive_omitted_patterns)] match retagged.val {
OperandValue::Pair(_, _) => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(retagged.val, OperandValue::Pair(_, _))")
};assert!(matches!(retagged.val, OperandValue::Pair(_, _)));
578retagged.val.store(bx, place_ref);
579 LocalRef::UnsizedPlace(place_ref)
580 }
581&LocalRef::Operand(operand_ref) => {
582let retagged = fx.codegen_retag_operand(bx, operand_ref, true);
583 LocalRef::Operand(retagged)
584 }
585 LocalRef::PendingOperand => LocalRef::PendingOperand,
586 })
587 .collect::<Vec<_>>();
588// If we branched during retagging, then we need to update the
589 // start block to the new location.
590fx.cached_llbbs[mir::START_BLOCK] = CachedLlbb::Some(bx.llbb());
591 }
592593if fx.instance.def.requires_caller_location(bx.tcx()) {
594let mir_args = if let Some(num_untupled) = num_untupled {
595// Subtract off the tupled argument that gets 'expanded'
596args.len() - 1 + num_untupled597 } else {
598args.len()
599 };
600match (&fx.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] instance {0:?} must have 1 more argument in their ABI than in their MIR",
fx.instance)));
}
}
};assert_eq!(
601 fx.fn_abi.args.len(),
602 mir_args + 1,
603"#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
604 fx.instance
605 );
606607let arg = fx.fn_abi.args.last().unwrap();
608match arg.mode {
609 PassMode::Direct(_) => (),
610_ => ::rustc_middle::util::bug::bug_fmt(format_args!("caller location must be PassMode::Direct, found {0:?}",
arg.mode))bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
611 }
612613fx.caller_location = Some(OperandRef {
614 val: OperandValue::Immediate(bx.get_param(llarg_idx)),
615 layout: arg.layout,
616 move_annotation: None,
617 });
618 }
619620args621}
622623fn find_cold_blocks<'tcx>(
624 tcx: TyCtxt<'tcx>,
625 mir: &mir::Body<'tcx>,
626) -> IndexVec<mir::BasicBlock, bool> {
627let local_decls = &mir.local_decls;
628629let mut cold_blocks: IndexVec<mir::BasicBlock, bool> =
630IndexVec::from_elem(false, &mir.basic_blocks);
631632// Traverse all basic blocks from end of the function to the start.
633for (bb, bb_data) in traversal::postorder(mir) {
634let terminator = bb_data.terminator();
635636match terminator.kind {
637// If a BB ends with a call to a cold function, mark it as cold.
638mir::TerminatorKind::Call { ref func, .. }
639 | mir::TerminatorKind::TailCall { ref func, .. }
640if let ty::FnDef(def_id, ..) = *func.ty(local_decls, tcx).kind()
641 && let attrs = tcx.codegen_fn_attrs(def_id)
642 && attrs.flags.contains(CodegenFnAttrFlags::COLD) =>
643 {
644 cold_blocks[bb] = true;
645continue;
646 }
647648// If a BB ends with an `unreachable`, also mark it as cold.
649mir::TerminatorKind::Unreachable => {
650 cold_blocks[bb] = true;
651continue;
652 }
653654_ => {}
655 }
656657// If all successors of a BB are cold and there's at least one of them, mark this BB as cold
658let mut succ = terminator.successors();
659if let Some(first) = succ.next()
660 && cold_blocks[first]
661 && succ.all(|s| cold_blocks[s])
662 {
663 cold_blocks[bb] = true;
664 }
665 }
666667cold_blocks668}