]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/mod.rs
Auto merge of #101173 - jyn514:simplify-macro-arguments, r=cjgillot
[rust.git] / compiler / rustc_codegen_ssa / src / mir / mod.rs
1 use crate::traits::*;
2 use rustc_middle::mir;
3 use rustc_middle::mir::interpret::ErrorHandled;
4 use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout};
5 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable, TypeVisitable};
6 use rustc_target::abi::call::{FnAbi, PassMode};
7
8 use std::iter;
9
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
12
13 use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
14 use self::place::PlaceRef;
15 use rustc_middle::mir::traversal;
16
17 use self::operand::{OperandRef, OperandValue};
18
19 /// Master context for codegenning from MIR.
20 pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
21     instance: Instance<'tcx>,
22
23     mir: &'tcx mir::Body<'tcx>,
24
25     debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>,
26
27     llfn: Bx::Function,
28
29     cx: &'a Bx::CodegenCx,
30
31     fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
32
33     /// When unwinding is initiated, we have to store this personality
34     /// value somewhere so that we can load it and re-use it in the
35     /// resume instruction. The personality is (afaik) some kind of
36     /// value used for C++ unwinding, which must filter by type: we
37     /// don't really care about it very much. Anyway, this value
38     /// contains an alloca into which the personality is stored and
39     /// then later loaded when generating the DIVERGE_BLOCK.
40     personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
41
42     /// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
43     /// as-needed (e.g. RPO reaching it or another block branching to it).
44     // FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
45     // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
46     cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
47
48     /// The funclet status of each basic block
49     cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
50
51     /// When targeting MSVC, this stores the cleanup info for each funclet BB.
52     /// This is initialized at the same time as the `landing_pads` entry for the
53     /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
54     funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
55
56     /// This stores the cached landing/cleanup pad block for a given BB.
57     // FIXME(eddyb) rename this to `eh_pads`.
58     landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
59
60     /// Cached unreachable block
61     unreachable_block: Option<Bx::BasicBlock>,
62
63     /// Cached double unwind guarding block
64     double_unwind_guard: Option<Bx::BasicBlock>,
65
66     /// The location where each MIR arg/var/tmp/ret is stored. This is
67     /// usually an `PlaceRef` representing an alloca, but not always:
68     /// sometimes we can skip the alloca and just store the value
69     /// directly using an `OperandRef`, which makes for tighter LLVM
70     /// IR. The conditions for using an `OperandRef` are as follows:
71     ///
72     /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
73     /// - the operand must never be referenced indirectly
74     ///     - we should not take its address using the `&` operator
75     ///     - nor should it appear in a place path like `tmp.a`
76     /// - the operand must be defined by an rvalue that can generate immediate
77     ///   values
78     ///
79     /// Avoiding allocs can also be important for certain intrinsics,
80     /// notably `expect`.
81     locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
82
83     /// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
84     /// This is `None` if no var`#[non_exhaustive]`iable debuginfo/names are needed.
85     per_local_var_debug_info:
86         Option<IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, Bx::DIVariable>>>>,
87
88     /// Caller location propagated if this function has `#[track_caller]`.
89     caller_location: Option<OperandRef<'tcx, Bx::Value>>,
90 }
91
92 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
93     pub fn monomorphize<T>(&self, value: T) -> T
94     where
95         T: Copy + TypeFoldable<'tcx>,
96     {
97         debug!("monomorphize: self.instance={:?}", self.instance);
98         self.instance.subst_mir_and_normalize_erasing_regions(
99             self.cx.tcx(),
100             ty::ParamEnv::reveal_all(),
101             value,
102         )
103     }
104 }
105
106 enum LocalRef<'tcx, V> {
107     Place(PlaceRef<'tcx, V>),
108     /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
109     /// `*p` is the fat pointer that references the actual unsized place.
110     /// Every time it is initialized, we have to reallocate the place
111     /// and update the fat pointer. That's the reason why it is indirect.
112     UnsizedPlace(PlaceRef<'tcx, V>),
113     Operand(Option<OperandRef<'tcx, V>>),
114 }
115
116 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
117     fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
118         bx: &mut Bx,
119         layout: TyAndLayout<'tcx>,
120     ) -> LocalRef<'tcx, V> {
121         if layout.is_zst() {
122             // Zero-size temporaries aren't always initialized, which
123             // doesn't matter because they don't contain data, but
124             // we need something in the operand.
125             LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
126         } else {
127             LocalRef::Operand(None)
128         }
129     }
130 }
131
132 ///////////////////////////////////////////////////////////////////////////
133
134 #[instrument(level = "debug", skip(cx))]
135 pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
136     cx: &'a Bx::CodegenCx,
137     instance: Instance<'tcx>,
138 ) {
139     assert!(!instance.substs.needs_infer());
140
141     let llfn = cx.get_fn(instance);
142
143     let mir = cx.tcx().instance_mir(instance.def);
144
145     let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
146     debug!("fn_abi: {:?}", fn_abi);
147
148     let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
149
150     let start_llbb = Bx::append_block(cx, llfn, "start");
151     let mut bx = Bx::build(cx, start_llbb);
152
153     if mir.basic_blocks.iter().any(|bb| bb.is_cleanup) {
154         bx.set_personality_fn(cx.eh_personality());
155     }
156
157     let cleanup_kinds = analyze::cleanup_kinds(&mir);
158     let cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>> = mir
159         .basic_blocks
160         .indices()
161         .map(|bb| if bb == mir::START_BLOCK { Some(start_llbb) } else { None })
162         .collect();
163
164     let mut fx = FunctionCx {
165         instance,
166         mir,
167         llfn,
168         fn_abi,
169         cx,
170         personality_slot: None,
171         cached_llbbs,
172         unreachable_block: None,
173         double_unwind_guard: None,
174         cleanup_kinds,
175         landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
176         funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
177         locals: IndexVec::new(),
178         debug_context,
179         per_local_var_debug_info: None,
180         caller_location: None,
181     };
182
183     fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut bx);
184
185     // Evaluate all required consts; codegen later assumes that CTFE will never fail.
186     let mut all_consts_ok = true;
187     for const_ in &mir.required_consts {
188         if let Err(err) = fx.eval_mir_constant(const_) {
189             all_consts_ok = false;
190             match err {
191                 // errored or at least linted
192                 ErrorHandled::Reported(_) | ErrorHandled::Linted => {}
193                 ErrorHandled::TooGeneric => {
194                     span_bug!(const_.span, "codegen encountered polymorphic constant: {:?}", err)
195                 }
196             }
197         }
198     }
199     if !all_consts_ok {
200         // We leave the IR in some half-built state here, and rely on this code not even being
201         // submitted to LLVM once an error was raised.
202         return;
203     }
204
205     let memory_locals = analyze::non_ssa_locals(&fx);
206
207     // Allocate variable and temp allocas
208     fx.locals = {
209         let args = arg_local_refs(&mut bx, &mut fx, &memory_locals);
210
211         let mut allocate_local = |local| {
212             let decl = &mir.local_decls[local];
213             let layout = bx.layout_of(fx.monomorphize(decl.ty));
214             assert!(!layout.ty.has_erasable_regions());
215
216             if local == mir::RETURN_PLACE && fx.fn_abi.ret.is_indirect() {
217                 debug!("alloc: {:?} (return place) -> place", local);
218                 let llretptr = bx.get_param(0);
219                 return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
220             }
221
222             if memory_locals.contains(local) {
223                 debug!("alloc: {:?} -> place", local);
224                 if layout.is_unsized() {
225                     LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut bx, layout))
226                 } else {
227                     LocalRef::Place(PlaceRef::alloca(&mut bx, layout))
228                 }
229             } else {
230                 debug!("alloc: {:?} -> operand", local);
231                 LocalRef::new_operand(&mut bx, layout)
232             }
233         };
234
235         let retptr = allocate_local(mir::RETURN_PLACE);
236         iter::once(retptr)
237             .chain(args.into_iter())
238             .chain(mir.vars_and_temps_iter().map(allocate_local))
239             .collect()
240     };
241
242     // Apply debuginfo to the newly allocated locals.
243     fx.debug_introduce_locals(&mut bx);
244
245     // Codegen the body of each block using reverse postorder
246     for (bb, _) in traversal::reverse_postorder(&mir) {
247         fx.codegen_block(bb);
248     }
249 }
250
251 /// Produces, for each argument, a `Value` pointing at the
252 /// argument's value. As arguments are places, these are always
253 /// indirect.
254 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
255     bx: &mut Bx,
256     fx: &mut FunctionCx<'a, 'tcx, Bx>,
257     memory_locals: &BitSet<mir::Local>,
258 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
259     let mir = fx.mir;
260     let mut idx = 0;
261     let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
262
263     let mut num_untupled = None;
264
265     let args = mir
266         .args_iter()
267         .enumerate()
268         .map(|(arg_index, local)| {
269             let arg_decl = &mir.local_decls[local];
270
271             if Some(local) == mir.spread_arg {
272                 // This argument (e.g., the last argument in the "rust-call" ABI)
273                 // is a tuple that was spread at the ABI level and now we have
274                 // to reconstruct it into a tuple local variable, from multiple
275                 // individual LLVM function arguments.
276
277                 let arg_ty = fx.monomorphize(arg_decl.ty);
278                 let ty::Tuple(tupled_arg_tys) = arg_ty.kind() else {
279                     bug!("spread argument isn't a tuple?!");
280                 };
281
282                 let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
283                 for i in 0..tupled_arg_tys.len() {
284                     let arg = &fx.fn_abi.args[idx];
285                     idx += 1;
286                     if let PassMode::Cast(_, true) = arg.mode {
287                         llarg_idx += 1;
288                     }
289                     let pr_field = place.project_field(bx, i);
290                     bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
291                 }
292                 assert_eq!(
293                     None,
294                     num_untupled.replace(tupled_arg_tys.len()),
295                     "Replaced existing num_tupled"
296                 );
297
298                 return LocalRef::Place(place);
299             }
300
301             if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
302                 let arg_ty = fx.monomorphize(arg_decl.ty);
303
304                 let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
305                 bx.va_start(va_list.llval);
306
307                 return LocalRef::Place(va_list);
308             }
309
310             let arg = &fx.fn_abi.args[idx];
311             idx += 1;
312             if let PassMode::Cast(_, true) = arg.mode {
313                 llarg_idx += 1;
314             }
315
316             if !memory_locals.contains(local) {
317                 // We don't have to cast or keep the argument in the alloca.
318                 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
319                 // of putting everything in allocas just so we can use llvm.dbg.declare.
320                 let local = |op| LocalRef::Operand(Some(op));
321                 match arg.mode {
322                     PassMode::Ignore => {
323                         return local(OperandRef::new_zst(bx, arg.layout));
324                     }
325                     PassMode::Direct(_) => {
326                         let llarg = bx.get_param(llarg_idx);
327                         llarg_idx += 1;
328                         return local(OperandRef::from_immediate_or_packed_pair(
329                             bx, llarg, arg.layout,
330                         ));
331                     }
332                     PassMode::Pair(..) => {
333                         let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
334                         llarg_idx += 2;
335
336                         return local(OperandRef {
337                             val: OperandValue::Pair(a, b),
338                             layout: arg.layout,
339                         });
340                     }
341                     _ => {}
342                 }
343             }
344
345             if arg.is_sized_indirect() {
346                 // Don't copy an indirect argument to an alloca, the caller
347                 // already put it in a temporary alloca and gave it up.
348                 // FIXME: lifetimes
349                 let llarg = bx.get_param(llarg_idx);
350                 llarg_idx += 1;
351                 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
352             } else if arg.is_unsized_indirect() {
353                 // As the storage for the indirect argument lives during
354                 // the whole function call, we just copy the fat pointer.
355                 let llarg = bx.get_param(llarg_idx);
356                 llarg_idx += 1;
357                 let llextra = bx.get_param(llarg_idx);
358                 llarg_idx += 1;
359                 let indirect_operand = OperandValue::Pair(llarg, llextra);
360
361                 let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
362                 indirect_operand.store(bx, tmp);
363                 LocalRef::UnsizedPlace(tmp)
364             } else {
365                 let tmp = PlaceRef::alloca(bx, arg.layout);
366                 bx.store_fn_arg(arg, &mut llarg_idx, tmp);
367                 LocalRef::Place(tmp)
368             }
369         })
370         .collect::<Vec<_>>();
371
372     if fx.instance.def.requires_caller_location(bx.tcx()) {
373         let mir_args = if let Some(num_untupled) = num_untupled {
374             // Subtract off the tupled argument that gets 'expanded'
375             args.len() - 1 + num_untupled
376         } else {
377             args.len()
378         };
379         assert_eq!(
380             fx.fn_abi.args.len(),
381             mir_args + 1,
382             "#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
383             fx.instance
384         );
385
386         let arg = fx.fn_abi.args.last().unwrap();
387         match arg.mode {
388             PassMode::Direct(_) => (),
389             _ => bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
390         }
391
392         fx.caller_location = Some(OperandRef {
393             val: OperandValue::Immediate(bx.get_param(llarg_idx)),
394             layout: arg.layout,
395         });
396     }
397
398     args
399 }
400
401 mod analyze;
402 mod block;
403 pub mod constant;
404 pub mod coverageinfo;
405 pub mod debuginfo;
406 mod intrinsic;
407 pub mod operand;
408 pub mod place;
409 mod rvalue;
410 mod statement;