2 use rustc_errors::ErrorReported;
4 use rustc_middle::mir::interpret::ErrorHandled;
5 use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout};
6 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
7 use rustc_target::abi::call::{FnAbi, PassMode};
11 use rustc_index::bit_set::BitSet;
12 use rustc_index::vec::IndexVec;
14 use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
15 use self::place::PlaceRef;
16 use rustc_middle::mir::traversal;
18 use self::operand::{OperandRef, OperandValue};
20 /// Master context for codegenning from MIR.
21 pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
22 instance: Instance<'tcx>,
24 mir: &'tcx mir::Body<'tcx>,
26 debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>,
30 cx: &'a Bx::CodegenCx,
32 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
34 /// When unwinding is initiated, we have to store this personality
35 /// value somewhere so that we can load it and re-use it in the
36 /// resume instruction. The personality is (afaik) some kind of
37 /// value used for C++ unwinding, which must filter by type: we
38 /// don't really care about it very much. Anyway, this value
39 /// contains an alloca into which the personality is stored and
40 /// then later loaded when generating the DIVERGE_BLOCK.
41 personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
43 /// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
44 /// as-needed (e.g. RPO reaching it or another block branching to it).
45 // FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
46 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
47 cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
49 /// The funclet status of each basic block
50 cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
52 /// When targeting MSVC, this stores the cleanup info for each funclet BB.
53 /// This is initialized at the same time as the `landing_pads` entry for the
54 /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
55 funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
57 /// This stores the cached landing/cleanup pad block for a given BB.
58 // FIXME(eddyb) rename this to `eh_pads`.
59 landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
61 /// Cached unreachable block
62 unreachable_block: Option<Bx::BasicBlock>,
64 /// The location where each MIR arg/var/tmp/ret is stored. This is
65 /// usually an `PlaceRef` representing an alloca, but not always:
66 /// sometimes we can skip the alloca and just store the value
67 /// directly using an `OperandRef`, which makes for tighter LLVM
68 /// IR. The conditions for using an `OperandRef` are as follows:
70 /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
71 /// - the operand must never be referenced indirectly
72 /// - we should not take its address using the `&` operator
73 /// - nor should it appear in a place path like `tmp.a`
74 /// - the operand must be defined by an rvalue that can generate immediate
77 /// Avoiding allocs can also be important for certain intrinsics,
79 locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
81 /// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
82 /// This is `None` if no var`#[non_exhaustive]`iable debuginfo/names are needed.
83 per_local_var_debug_info:
84 Option<IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, Bx::DIVariable>>>>,
86 /// Caller location propagated if this function has `#[track_caller]`.
87 caller_location: Option<OperandRef<'tcx, Bx::Value>>,
90 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
91 pub fn monomorphize<T>(&self, value: T) -> T
93 T: Copy + TypeFoldable<'tcx>,
95 debug!("monomorphize: self.instance={:?}", self.instance);
96 self.instance.subst_mir_and_normalize_erasing_regions(
98 ty::ParamEnv::reveal_all(),
104 enum LocalRef<'tcx, V> {
105 Place(PlaceRef<'tcx, V>),
106 /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
107 /// `*p` is the fat pointer that references the actual unsized place.
108 /// Every time it is initialized, we have to reallocate the place
109 /// and update the fat pointer. That's the reason why it is indirect.
110 UnsizedPlace(PlaceRef<'tcx, V>),
111 Operand(Option<OperandRef<'tcx, V>>),
114 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
115 fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
117 layout: TyAndLayout<'tcx>,
118 ) -> LocalRef<'tcx, V> {
120 // Zero-size temporaries aren't always initialized, which
121 // doesn't matter because they don't contain data, but
122 // we need something in the operand.
123 LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
125 LocalRef::Operand(None)
130 ///////////////////////////////////////////////////////////////////////////
132 #[instrument(level = "debug", skip(cx))]
133 pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
134 cx: &'a Bx::CodegenCx,
135 instance: Instance<'tcx>,
137 assert!(!instance.substs.needs_infer());
139 let llfn = cx.get_fn(instance);
141 let mir = cx.tcx().instance_mir(instance.def);
143 let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
144 debug!("fn_abi: {:?}", fn_abi);
146 let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
148 let start_llbb = Bx::append_block(cx, llfn, "start");
149 let mut bx = Bx::build(cx, start_llbb);
151 if mir.basic_blocks().iter().any(|bb| bb.is_cleanup) {
152 bx.set_personality_fn(cx.eh_personality());
155 let cleanup_kinds = analyze::cleanup_kinds(&mir);
156 let cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>> = mir
159 .map(|bb| if bb == mir::START_BLOCK { Some(start_llbb) } else { None })
162 let mut fx = FunctionCx {
168 personality_slot: None,
170 unreachable_block: None,
172 landing_pads: IndexVec::from_elem(None, mir.basic_blocks()),
173 funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks().len()),
174 locals: IndexVec::new(),
176 per_local_var_debug_info: None,
177 caller_location: None,
180 fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut bx);
182 // Evaluate all required consts; codegen later assumes that CTFE will never fail.
183 let mut all_consts_ok = true;
184 for const_ in &mir.required_consts {
185 if let Err(err) = fx.eval_mir_constant(const_) {
186 all_consts_ok = false;
188 // errored or at least linted
189 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {}
190 ErrorHandled::TooGeneric => {
191 span_bug!(const_.span, "codgen encountered polymorphic constant: {:?}", err)
197 // We leave the IR in some half-built state here, and rely on this code not even being
198 // submitted to LLVM once an error was raised.
202 let memory_locals = analyze::non_ssa_locals(&fx);
204 // Allocate variable and temp allocas
206 let args = arg_local_refs(&mut bx, &mut fx, &memory_locals);
208 let mut allocate_local = |local| {
209 let decl = &mir.local_decls[local];
210 let layout = bx.layout_of(fx.monomorphize(decl.ty));
211 assert!(!layout.ty.has_erasable_regions(cx.tcx()));
213 if local == mir::RETURN_PLACE && fx.fn_abi.ret.is_indirect() {
214 debug!("alloc: {:?} (return place) -> place", local);
215 let llretptr = bx.get_param(0);
216 return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
219 if memory_locals.contains(local) {
220 debug!("alloc: {:?} -> place", local);
221 if layout.is_unsized() {
222 LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut bx, layout))
224 LocalRef::Place(PlaceRef::alloca(&mut bx, layout))
227 debug!("alloc: {:?} -> operand", local);
228 LocalRef::new_operand(&mut bx, layout)
232 let retptr = allocate_local(mir::RETURN_PLACE);
234 .chain(args.into_iter())
235 .chain(mir.vars_and_temps_iter().map(allocate_local))
239 // Apply debuginfo to the newly allocated locals.
240 fx.debug_introduce_locals(&mut bx);
242 // Codegen the body of each block using reverse postorder
243 // FIXME(eddyb) reuse RPO iterator between `analysis` and this.
244 for (bb, _) in traversal::reverse_postorder(&mir) {
245 fx.codegen_block(bb);
249 /// Produces, for each argument, a `Value` pointing at the
250 /// argument's value. As arguments are places, these are always
252 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
254 fx: &mut FunctionCx<'a, 'tcx, Bx>,
255 memory_locals: &BitSet<mir::Local>,
256 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
259 let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
261 let mut num_untupled = None;
266 .map(|(arg_index, local)| {
267 let arg_decl = &mir.local_decls[local];
269 if Some(local) == mir.spread_arg {
270 // This argument (e.g., the last argument in the "rust-call" ABI)
271 // is a tuple that was spread at the ABI level and now we have
272 // to reconstruct it into a tuple local variable, from multiple
273 // individual LLVM function arguments.
275 let arg_ty = fx.monomorphize(arg_decl.ty);
276 let tupled_arg_tys = match arg_ty.kind() {
277 ty::Tuple(tys) => tys,
278 _ => bug!("spread argument isn't a tuple?!"),
281 let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
282 for i in 0..tupled_arg_tys.len() {
283 let arg = &fx.fn_abi.args[idx];
285 if arg.pad.is_some() {
288 let pr_field = place.project_field(bx, i);
289 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
293 num_untupled.replace(tupled_arg_tys.len()),
294 "Replaced existing num_tupled"
297 return LocalRef::Place(place);
300 if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
301 let arg_ty = fx.monomorphize(arg_decl.ty);
303 let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
304 bx.va_start(va_list.llval);
306 return LocalRef::Place(va_list);
309 let arg = &fx.fn_abi.args[idx];
311 if arg.pad.is_some() {
315 if !memory_locals.contains(local) {
316 // We don't have to cast or keep the argument in the alloca.
317 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
318 // of putting everything in allocas just so we can use llvm.dbg.declare.
319 let local = |op| LocalRef::Operand(Some(op));
321 PassMode::Ignore => {
322 return local(OperandRef::new_zst(bx, arg.layout));
324 PassMode::Direct(_) => {
325 let llarg = bx.get_param(llarg_idx);
327 return local(OperandRef::from_immediate_or_packed_pair(
328 bx, llarg, arg.layout,
331 PassMode::Pair(..) => {
332 let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
335 return local(OperandRef {
336 val: OperandValue::Pair(a, b),
344 if arg.is_sized_indirect() {
345 // Don't copy an indirect argument to an alloca, the caller
346 // already put it in a temporary alloca and gave it up.
348 let llarg = bx.get_param(llarg_idx);
350 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
351 } else if arg.is_unsized_indirect() {
352 // As the storage for the indirect argument lives during
353 // the whole function call, we just copy the fat pointer.
354 let llarg = bx.get_param(llarg_idx);
356 let llextra = bx.get_param(llarg_idx);
358 let indirect_operand = OperandValue::Pair(llarg, llextra);
360 let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
361 indirect_operand.store(bx, tmp);
362 LocalRef::UnsizedPlace(tmp)
364 let tmp = PlaceRef::alloca(bx, arg.layout);
365 bx.store_fn_arg(arg, &mut llarg_idx, tmp);
369 .collect::<Vec<_>>();
371 if fx.instance.def.requires_caller_location(bx.tcx()) {
372 let mir_args = if let Some(num_untupled) = num_untupled {
373 // Subtract off the tupled argument that gets 'expanded'
374 args.len() - 1 + num_untupled
379 fx.fn_abi.args.len(),
381 "#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
385 let arg = fx.fn_abi.args.last().unwrap();
387 PassMode::Direct(_) => (),
388 _ => bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
391 fx.caller_location = Some(OperandRef {
392 val: OperandValue::Immediate(bx.get_param(llarg_idx)),
403 pub mod coverageinfo;