]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/mod.rs
Rollup merge of #66941 - CAD97:nord, r=Dylan-DPC
[rust.git] / src / librustc_codegen_ssa / mir / mod.rs
1 use rustc::ty::{self, Ty, TypeFoldable, Instance};
2 use rustc::ty::layout::{TyLayout, HasTyCtxt, FnAbiExt};
3 use rustc::mir::{self, Body, ReadOnlyBodyCache};
4 use rustc_target::abi::call::{FnAbi, PassMode};
5 use crate::base;
6 use crate::traits::*;
7
8 use std::iter;
9
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
12
13 use self::analyze::CleanupKind;
14 use self::debuginfo::FunctionDebugContext;
15 use self::place::PlaceRef;
16 use rustc::mir::traversal;
17
18 use self::operand::{OperandRef, OperandValue};
19
20 /// Master context for codegenning from MIR.
21 pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
22     instance: Instance<'tcx>,
23
24     mir: mir::ReadOnlyBodyCache<'a, 'tcx>,
25
26     debug_context: Option<FunctionDebugContext<Bx::DIScope>>,
27
28     llfn: Bx::Function,
29
30     cx: &'a Bx::CodegenCx,
31
32     fn_abi: FnAbi<'tcx, Ty<'tcx>>,
33
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>>,
42
43     /// A `Block` for each MIR `BasicBlock`
44     blocks: IndexVec<mir::BasicBlock, Bx::BasicBlock>,
45
46     /// The funclet status of each basic block
47     cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
48
49     /// When targeting MSVC, this stores the cleanup info for each funclet
50     /// BB. This is initialized as we compute the funclets' head block in RPO.
51     funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
52
53     /// This stores the landing-pad block for a given BB, computed lazily on GNU
54     /// and eagerly on MSVC.
55     landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
56
57     /// Cached unreachable block
58     unreachable_block: Option<Bx::BasicBlock>,
59
60     /// The location where each MIR arg/var/tmp/ret is stored. This is
61     /// usually an `PlaceRef` representing an alloca, but not always:
62     /// sometimes we can skip the alloca and just store the value
63     /// directly using an `OperandRef`, which makes for tighter LLVM
64     /// IR. The conditions for using an `OperandRef` are as follows:
65     ///
66     /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
67     /// - the operand must never be referenced indirectly
68     ///     - we should not take its address using the `&` operator
69     ///     - nor should it appear in a place path like `tmp.a`
70     /// - the operand must be defined by an rvalue that can generate immediate
71     ///   values
72     ///
73     /// Avoiding allocs can also be important for certain intrinsics,
74     /// notably `expect`.
75     locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
76
77     /// All `VarDebuginfo` from the MIR body, partitioned by `Local`.
78     /// This is `None` if no variable debuginfo/names are needed.
79     per_local_var_debug_info: Option<IndexVec<mir::Local, Vec<&'a mir::VarDebugInfo<'tcx>>>>,
80 }
81
82 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
83     pub fn monomorphize<T>(&self, value: &T) -> T
84         where T: TypeFoldable<'tcx>
85     {
86         self.cx.tcx().subst_and_normalize_erasing_regions(
87             self.instance.substs,
88             ty::ParamEnv::reveal_all(),
89             value,
90         )
91     }
92 }
93
94 enum LocalRef<'tcx, V> {
95     Place(PlaceRef<'tcx, V>),
96     /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
97     /// `*p` is the fat pointer that references the actual unsized place.
98     /// Every time it is initialized, we have to reallocate the place
99     /// and update the fat pointer. That's the reason why it is indirect.
100     UnsizedPlace(PlaceRef<'tcx, V>),
101     Operand(Option<OperandRef<'tcx, V>>),
102 }
103
104 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
105     fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
106         bx: &mut Bx,
107         layout: TyLayout<'tcx>,
108     ) -> LocalRef<'tcx, V> {
109         if layout.is_zst() {
110             // Zero-size temporaries aren't always initialized, which
111             // doesn't matter because they don't contain data, but
112             // we need something in the operand.
113             LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
114         } else {
115             LocalRef::Operand(None)
116         }
117     }
118 }
119
120 ///////////////////////////////////////////////////////////////////////////
121
122 pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
123     cx: &'a Bx::CodegenCx,
124     llfn: Bx::Function,
125     mir: ReadOnlyBodyCache<'a, 'tcx>,
126     instance: Instance<'tcx>,
127     sig: ty::FnSig<'tcx>,
128 ) {
129     assert!(!instance.substs.needs_infer());
130
131     let fn_abi = FnAbi::new(cx, sig, &[]);
132     debug!("fn_abi: {:?}", fn_abi);
133
134     let debug_context =
135         cx.create_function_debug_context(instance, sig, llfn, &mir);
136
137     let mut bx = Bx::new_block(cx, llfn, "start");
138
139     if mir.basic_blocks().iter().any(|bb| bb.is_cleanup) {
140         bx.set_personality_fn(cx.eh_personality());
141     }
142
143     bx.sideeffect();
144
145     let cleanup_kinds = analyze::cleanup_kinds(&mir);
146     // Allocate a `Block` for every basic block, except
147     // the start block, if nothing loops back to it.
148     let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
149     let block_bxs: IndexVec<mir::BasicBlock, Bx::BasicBlock> =
150         mir.basic_blocks().indices().map(|bb| {
151             if bb == mir::START_BLOCK && !reentrant_start_block {
152                 bx.llbb()
153             } else {
154                 bx.build_sibling_block(&format!("{:?}", bb)).llbb()
155             }
156         }).collect();
157
158     let (landing_pads, funclets) = create_funclets(&mir, &mut bx, &cleanup_kinds, &block_bxs);
159     let mir_body: &Body<'_> = mir.body();
160     let mut fx = FunctionCx {
161         instance,
162         mir,
163         llfn,
164         fn_abi,
165         cx,
166         personality_slot: None,
167         blocks: block_bxs,
168         unreachable_block: None,
169         cleanup_kinds,
170         landing_pads,
171         funclets,
172         locals: IndexVec::new(),
173         debug_context,
174         per_local_var_debug_info: debuginfo::per_local_var_debug_info(cx.tcx(), mir_body),
175     };
176
177     let memory_locals = analyze::non_ssa_locals(&fx);
178
179     // Allocate variable and temp allocas
180     fx.locals = {
181         let args = arg_local_refs(&mut bx, &fx, &memory_locals);
182
183         let mut allocate_local = |local| {
184             let decl = &mir_body.local_decls[local];
185             let layout = bx.layout_of(fx.monomorphize(&decl.ty));
186             assert!(!layout.ty.has_erasable_regions());
187
188             if local == mir::RETURN_PLACE && fx.fn_abi.ret.is_indirect() {
189                 debug!("alloc: {:?} (return place) -> place", local);
190                 let llretptr = bx.get_param(0);
191                 return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
192             }
193
194             if memory_locals.contains(local) {
195                 debug!("alloc: {:?} -> place", local);
196                 if layout.is_unsized() {
197                     LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut bx, layout))
198                 } else {
199                     LocalRef::Place(PlaceRef::alloca(&mut bx, layout))
200                 }
201             } else {
202                 debug!("alloc: {:?} -> operand", local);
203                 LocalRef::new_operand(&mut bx, layout)
204             }
205         };
206
207         let retptr = allocate_local(mir::RETURN_PLACE);
208         iter::once(retptr)
209             .chain(args.into_iter())
210             .chain(mir_body.vars_and_temps_iter().map(allocate_local))
211             .collect()
212     };
213
214     // Apply debuginfo to the newly allocated locals.
215     fx.debug_introduce_locals(&mut bx);
216
217     // Branch to the START block, if it's not the entry block.
218     if reentrant_start_block {
219         bx.br(fx.blocks[mir::START_BLOCK]);
220     }
221
222     // Up until here, IR instructions for this function have explicitly not been annotated with
223     // source code location, so we don't step into call setup code. From here on, source location
224     // emitting should be enabled.
225     if let Some(debug_context) = &mut fx.debug_context {
226         debug_context.source_locations_enabled = true;
227     }
228
229     let rpo = traversal::reverse_postorder(&mir_body);
230     let mut visited = BitSet::new_empty(mir_body.basic_blocks().len());
231
232     // Codegen the body of each block using reverse postorder
233     for (bb, _) in rpo {
234         visited.insert(bb.index());
235         fx.codegen_block(bb);
236     }
237
238     // Remove blocks that haven't been visited, or have no
239     // predecessors.
240     for bb in mir_body.basic_blocks().indices() {
241         // Unreachable block
242         if !visited.contains(bb.index()) {
243             debug!("codegen_mir: block {:?} was not visited", bb);
244             unsafe {
245                 bx.delete_basic_block(fx.blocks[bb]);
246             }
247         }
248     }
249 }
250
251 fn create_funclets<'a, 'b, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
252     mir: &'b Body<'tcx>,
253     bx: &mut Bx,
254     cleanup_kinds: &IndexVec<mir::BasicBlock, CleanupKind>,
255     block_bxs: &IndexVec<mir::BasicBlock, Bx::BasicBlock>,
256 ) -> (
257     IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
258     IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
259 ) {
260     block_bxs.iter_enumerated().zip(cleanup_kinds).map(|((bb, &llbb), cleanup_kind)| {
261         match *cleanup_kind {
262             CleanupKind::Funclet if base::wants_msvc_seh(bx.sess()) => {}
263             _ => return (None, None)
264         }
265
266         let funclet;
267         let ret_llbb;
268         match mir[bb].terminator.as_ref().map(|t| &t.kind) {
269             // This is a basic block that we're aborting the program for,
270             // notably in an `extern` function. These basic blocks are inserted
271             // so that we assert that `extern` functions do indeed not panic,
272             // and if they do we abort the process.
273             //
274             // On MSVC these are tricky though (where we're doing funclets). If
275             // we were to do a cleanuppad (like below) the normal functions like
276             // `longjmp` would trigger the abort logic, terminating the
277             // program. Instead we insert the equivalent of `catch(...)` for C++
278             // which magically doesn't trigger when `longjmp` files over this
279             // frame.
280             //
281             // Lots more discussion can be found on #48251 but this codegen is
282             // modeled after clang's for:
283             //
284             //      try {
285             //          foo();
286             //      } catch (...) {
287             //          bar();
288             //      }
289             Some(&mir::TerminatorKind::Abort) => {
290                 let mut cs_bx = bx.build_sibling_block(&format!("cs_funclet{:?}", bb));
291                 let mut cp_bx = bx.build_sibling_block(&format!("cp_funclet{:?}", bb));
292                 ret_llbb = cs_bx.llbb();
293
294                 let cs = cs_bx.catch_switch(None, None, 1);
295                 cs_bx.add_handler(cs, cp_bx.llbb());
296
297                 // The "null" here is actually a RTTI type descriptor for the
298                 // C++ personality function, but `catch (...)` has no type so
299                 // it's null. The 64 here is actually a bitfield which
300                 // represents that this is a catch-all block.
301                 let null = bx.const_null(bx.type_i8p());
302                 let sixty_four = bx.const_i32(64);
303                 funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
304                 cp_bx.br(llbb);
305             }
306             _ => {
307                 let mut cleanup_bx = bx.build_sibling_block(&format!("funclet_{:?}", bb));
308                 ret_llbb = cleanup_bx.llbb();
309                 funclet = cleanup_bx.cleanup_pad(None, &[]);
310                 cleanup_bx.br(llbb);
311             }
312         };
313
314         (Some(ret_llbb), Some(funclet))
315     }).unzip()
316 }
317
318 /// Produces, for each argument, a `Value` pointing at the
319 /// argument's value. As arguments are places, these are always
320 /// indirect.
321 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
322     bx: &mut Bx,
323     fx: &FunctionCx<'a, 'tcx, Bx>,
324     memory_locals: &BitSet<mir::Local>,
325 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
326     let mir = fx.mir;
327     let mut idx = 0;
328     let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
329
330     mir.args_iter().enumerate().map(|(arg_index, local)| {
331         let arg_decl = &mir.local_decls[local];
332
333         if Some(local) == mir.spread_arg {
334             // This argument (e.g., the last argument in the "rust-call" ABI)
335             // is a tuple that was spread at the ABI level and now we have
336             // to reconstruct it into a tuple local variable, from multiple
337             // individual LLVM function arguments.
338
339             let arg_ty = fx.monomorphize(&arg_decl.ty);
340             let tupled_arg_tys = match arg_ty.kind {
341                 ty::Tuple(ref tys) => tys,
342                 _ => bug!("spread argument isn't a tuple?!")
343             };
344
345             let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
346             for i in 0..tupled_arg_tys.len() {
347                 let arg = &fx.fn_abi.args[idx];
348                 idx += 1;
349                 if arg.pad.is_some() {
350                     llarg_idx += 1;
351                 }
352                 let pr_field = place.project_field(bx, i);
353                 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
354             }
355
356             return LocalRef::Place(place);
357         }
358
359         if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
360             let arg_ty = fx.monomorphize(&arg_decl.ty);
361
362             let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
363             bx.va_start(va_list.llval);
364
365             return LocalRef::Place(va_list);
366         }
367
368         let arg = &fx.fn_abi.args[idx];
369         idx += 1;
370         if arg.pad.is_some() {
371             llarg_idx += 1;
372         }
373
374         if !memory_locals.contains(local) {
375             // We don't have to cast or keep the argument in the alloca.
376             // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
377             // of putting everything in allocas just so we can use llvm.dbg.declare.
378             let local = |op| LocalRef::Operand(Some(op));
379             match arg.mode {
380                 PassMode::Ignore => {
381                     return local(OperandRef::new_zst(bx, arg.layout));
382                 }
383                 PassMode::Direct(_) => {
384                     let llarg = bx.get_param(llarg_idx);
385                     llarg_idx += 1;
386                     return local(
387                         OperandRef::from_immediate_or_packed_pair(bx, llarg, arg.layout));
388                 }
389                 PassMode::Pair(..) => {
390                     let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
391                     llarg_idx += 2;
392
393                     return local(OperandRef {
394                         val: OperandValue::Pair(a, b),
395                         layout: arg.layout
396                     });
397                 }
398                 _ => {}
399             }
400         }
401
402         if arg.is_sized_indirect() {
403             // Don't copy an indirect argument to an alloca, the caller
404             // already put it in a temporary alloca and gave it up.
405             // FIXME: lifetimes
406             let llarg = bx.get_param(llarg_idx);
407             llarg_idx += 1;
408             LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
409         } else if arg.is_unsized_indirect() {
410             // As the storage for the indirect argument lives during
411             // the whole function call, we just copy the fat pointer.
412             let llarg = bx.get_param(llarg_idx);
413             llarg_idx += 1;
414             let llextra = bx.get_param(llarg_idx);
415             llarg_idx += 1;
416             let indirect_operand = OperandValue::Pair(llarg, llextra);
417
418             let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
419             indirect_operand.store(bx, tmp);
420             LocalRef::UnsizedPlace(tmp)
421         } else {
422             let tmp = PlaceRef::alloca(bx, arg.layout);
423             bx.store_fn_arg(arg, &mut llarg_idx, tmp);
424             LocalRef::Place(tmp)
425         }
426     }).collect()
427 }
428
429 mod analyze;
430 mod block;
431 pub mod constant;
432 pub mod debuginfo;
433 pub mod place;
434 pub mod operand;
435 mod rvalue;
436 mod statement;