Skip to main content

rustc_mir_transform/
check_enums.rs

1use rustc_abi::{Scalar, Size, TagEncoding, Variants, WrappingRange};
2use rustc_attr_ir::lang_items::LangItem;
3use rustc_index::IndexVec;
4use rustc_middle::mir::visit::Visitor;
5use rustc_middle::mir::*;
6use rustc_middle::ty::layout::PrimitiveExt;
7use rustc_middle::ty::{self, Ty, TyCtxt, TypingEnv};
8use rustc_span::bug;
9use tracing::debug;
10
11use crate::PassPolicy;
12
13/// This pass inserts checks for a valid enum discriminant where they are most
14/// likely to find UB, because checking everywhere like Miri would generate too
15/// much MIR.
16pub(super) struct CheckEnums;
17
18impl<'tcx> crate::MirPass<'tcx> for CheckEnums {
19    fn policy(&self, ctx: &crate::PassCtx<'_>) -> PassPolicy {
20        // When UB checks are enabled this is part of their semantics, not an optimization.
21        PassPolicy::optional(ctx.ub_checks())
22    }
23
24    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
25        // This pass emits new panics. If for whatever reason we do not have a panic
26        // implementation, running this pass may cause otherwise-valid code to not compile.
27        if tcx.lang_items().get(LangItem::PanicImpl).is_none() {
28            return;
29        }
30
31        let typing_env = body.typing_env(tcx);
32        let basic_blocks = body.basic_blocks.as_mut();
33        let local_decls = &mut body.local_decls;
34
35        // This operation inserts new blocks. Each insertion changes the Location for all
36        // statements/blocks after. Iterating or visiting the MIR in order would require updating
37        // our current location after every insertion. By iterating backwards, we dodge this issue:
38        // The only Locations that an insertion changes have already been handled.
39        for block in basic_blocks.indices().rev() {
40            for statement_index in (0..basic_blocks[block].statements.len()).rev() {
41                let location = Location { block, statement_index };
42                let statement = &basic_blocks[block].statements[statement_index];
43                let source_info = statement.source_info;
44
45                let mut finder = EnumFinder::new(tcx, local_decls, typing_env);
46                finder.visit_statement(statement, location);
47
48                for check in finder.into_found_enums() {
49                    debug!("Inserting enum check");
50                    // Note: this split inserts a Goto(new_block) terminator,
51                    // which we later overwrite when we insert the check.
52                    let new_block = split_block(basic_blocks, location, source_info);
53
54                    match check {
55                        EnumCheckType::Direct { op_size, .. }
56                        | EnumCheckType::WithNiche { op_size, .. }
57                            if op_size.bytes() == 0 =>
58                        {
59                            // It is never valid to use a ZST as a discriminant for an inhabited enum, but that will
60                            // have been caught by the type checker. Do nothing but ensure that a bug has been signaled.
61                            tcx.dcx().span_delayed_bug(
62                                source_info.span,
63                                "cannot build enum discriminant from zero-sized type",
64                            );
65                        }
66                        EnumCheckType::Direct { source_op, discr, op_size, valid_discrs } => {
67                            insert_direct_enum_check(
68                                tcx,
69                                local_decls,
70                                basic_blocks,
71                                block,
72                                source_op,
73                                discr,
74                                op_size,
75                                valid_discrs,
76                                source_info,
77                                new_block,
78                            )
79                        }
80                        EnumCheckType::Uninhabited => insert_uninhabited_enum_check(
81                            tcx,
82                            local_decls,
83                            &mut basic_blocks[block],
84                            source_info,
85                            new_block,
86                        ),
87                        EnumCheckType::WithNiche {
88                            source_op,
89                            discr,
90                            op_size,
91                            offset,
92                            valid_range,
93                        } => insert_niche_check(
94                            tcx,
95                            local_decls,
96                            &mut basic_blocks[block],
97                            source_op,
98                            valid_range,
99                            discr,
100                            op_size,
101                            offset,
102                            source_info,
103                            new_block,
104                        ),
105                    }
106                }
107            }
108        }
109    }
110}
111
112/// Represent the different kind of enum checks we can insert.
113enum EnumCheckType<'tcx> {
114    /// We know we try to create an uninhabited enum from an inhabited variant.
115    Uninhabited,
116    /// We know the enum does no niche optimizations and can thus easily compute
117    /// the valid discriminants.
118    Direct {
119        source_op: Operand<'tcx>,
120        discr: TyAndSize<'tcx>,
121        op_size: Size,
122        valid_discrs: Vec<u128>,
123    },
124    /// We try to construct an enum that has a niche.
125    WithNiche {
126        source_op: Operand<'tcx>,
127        discr: TyAndSize<'tcx>,
128        op_size: Size,
129        offset: Size,
130        valid_range: WrappingRange,
131    },
132}
133
134#[derive(Debug, Copy, Clone)]
135struct TyAndSize<'tcx> {
136    pub ty: Ty<'tcx>,
137    pub size: Size,
138}
139
140/// A [Visitor] that finds the construction of enums and evaluates which checks
141/// we should apply.
142struct EnumFinder<'a, 'tcx> {
143    tcx: TyCtxt<'tcx>,
144    local_decls: &'a mut LocalDecls<'tcx>,
145    typing_env: TypingEnv<'tcx>,
146    enums: Vec<EnumCheckType<'tcx>>,
147}
148
149impl<'a, 'tcx> EnumFinder<'a, 'tcx> {
150    fn new(
151        tcx: TyCtxt<'tcx>,
152        local_decls: &'a mut LocalDecls<'tcx>,
153        typing_env: TypingEnv<'tcx>,
154    ) -> Self {
155        EnumFinder { tcx, local_decls, typing_env, enums: Vec::new() }
156    }
157
158    /// Returns the found enum creations and which checks should be inserted.
159    fn into_found_enums(self) -> Vec<EnumCheckType<'tcx>> {
160        self.enums
161    }
162}
163
164impl<'a, 'tcx> Visitor<'tcx> for EnumFinder<'a, 'tcx> {
165    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
166        if let Rvalue::Cast(CastKind::Transmute, op, ty) = rvalue {
167            let ty::Adt(adt_def, _) = ty.kind() else {
168                return;
169            };
170            if !adt_def.is_enum() {
171                return;
172            }
173
174            let Ok(enum_layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
175                return;
176            };
177            let Ok(op_layout) = self
178                .tcx
179                .layout_of(self.typing_env.as_query_input(op.ty(self.local_decls, self.tcx)))
180            else {
181                return;
182            };
183
184            match enum_layout.variants {
185                Variants::Empty if op_layout.is_uninhabited() => return,
186                // An empty enum that tries to be constructed from an inhabited value, this
187                // is never correct.
188                Variants::Empty => {
189                    // The enum layout is uninhabited but we construct it from sth inhabited.
190                    // This is always UB.
191                    self.enums.push(EnumCheckType::Uninhabited);
192                }
193                // Construction of Single value enums is always fine.
194                Variants::Single { .. } => {}
195                // Construction of an enum with multiple variants but no niche optimizations.
196                Variants::Multiple {
197                    tag_encoding: TagEncoding::Direct,
198                    tag: Scalar::Initialized { value, .. },
199                    ..
200                } => {
201                    let valid_discrs =
202                        adt_def.discriminants(self.tcx).map(|(_, discr)| discr.val).collect();
203
204                    let discr =
205                        TyAndSize { ty: value.to_int_ty(self.tcx), size: value.size(&self.tcx) };
206                    self.enums.push(EnumCheckType::Direct {
207                        source_op: op.to_copy(),
208                        discr,
209                        op_size: op_layout.size,
210                        valid_discrs,
211                    });
212                }
213                // Construction of an enum with multiple variants and niche optimizations.
214                Variants::Multiple {
215                    tag_encoding: TagEncoding::Niche { .. },
216                    tag: Scalar::Initialized { value, valid_range, .. },
217                    tag_field,
218                    ..
219                } => {
220                    let discr =
221                        TyAndSize { ty: value.to_int_ty(self.tcx), size: value.size(&self.tcx) };
222                    self.enums.push(EnumCheckType::WithNiche {
223                        source_op: op.to_copy(),
224                        discr,
225                        op_size: op_layout.size,
226                        offset: enum_layout.fields.offset(tag_field.as_usize()),
227                        valid_range,
228                    });
229                }
230                _ => return,
231            }
232
233            self.super_rvalue(rvalue, location);
234        }
235    }
236}
237
238fn split_block(
239    basic_blocks: &mut IndexVec<BasicBlock, BasicBlockData<'_>>,
240    location: Location,
241    source_info: SourceInfo,
242) -> BasicBlock {
243    basic_blocks.push_with(|new_block_idx, basic_blocks| {
244        let block_data = &mut basic_blocks[location.block];
245
246        // Drain every statement after this one
247        let remaining_stmts = block_data.statements.split_off(location.statement_index);
248
249        // replace the old terminator with a goto to the new block
250        let new_terminator = Terminator { source_info, kind: TerminatorKind::goto(new_block_idx) };
251        let old_terminator = std::mem::replace(block_data.terminator_mut(), new_terminator);
252
253        // move the old terminator to the new basic block
254        BasicBlockData::new_stmts(remaining_stmts, old_terminator, block_data.is_cleanup)
255    })
256}
257
258/// Inserts the cast of an operand (any type) to a u128 value that holds the discriminant value.
259fn insert_discr_cast_to_u128<'tcx>(
260    tcx: TyCtxt<'tcx>,
261    local_decls: &mut IndexVec<Local, LocalDecl<'tcx>>,
262    block_data: &mut BasicBlockData<'tcx>,
263    source_op: Operand<'tcx>,
264    discr: TyAndSize<'tcx>,
265    op_size: Size,
266    offset: Option<Size>,
267    source_info: SourceInfo,
268) -> Place<'tcx> {
269    let get_ty_for_size = |tcx: TyCtxt<'tcx>, size: Size| -> Ty<'tcx> {
270        match size.bytes() {
271            1 => tcx.types.u8,
272            2 => tcx.types.u16,
273            4 => tcx.types.u32,
274            8 => tcx.types.u64,
275            16 => tcx.types.u128,
276            invalid => bug!("Found discriminant with invalid size, has {} bytes", invalid),
277        }
278    };
279
280    let (cast_kind, discr_ty_bits) = if discr.size.bytes() < op_size.bytes() {
281        // The discriminant is less wide than the operand, cast the operand into
282        // [MaybeUninit; N] and then index into it.
283        let mu = Ty::new_maybe_uninit(tcx, tcx.types.u8);
284        let array_len = op_size.bytes();
285        let mu_array_ty = Ty::new_array(tcx, mu, array_len);
286        let mu_array =
287            local_decls.push(LocalDecl::with_source_info(mu_array_ty, source_info)).into();
288        let rvalue = Rvalue::Cast(CastKind::Transmute, source_op, mu_array_ty);
289        block_data
290            .statements
291            .push(Statement::new(source_info, StatementKind::Assign(Box::new((mu_array, rvalue)))));
292
293        // Index into the array of MaybeUninit to get something that is actually
294        // as wide as the discriminant.
295        let offset = offset.unwrap_or(Size::ZERO);
296        let smaller_mu_array = mu_array.project_deeper(
297            &[ProjectionElem::Subslice {
298                from: offset.bytes(),
299                to: offset.bytes() + discr.size.bytes(),
300                from_end: false,
301            }],
302            tcx,
303        );
304
305        (CastKind::Transmute, Operand::Copy(smaller_mu_array))
306    } else {
307        let operand_int_ty = get_ty_for_size(tcx, op_size);
308
309        let op_as_int =
310            local_decls.push(LocalDecl::with_source_info(operand_int_ty, source_info)).into();
311        let rvalue = Rvalue::Cast(CastKind::Transmute, source_op, operand_int_ty);
312        block_data.statements.push(Statement::new(
313            source_info,
314            StatementKind::Assign(Box::new((op_as_int, rvalue))),
315        ));
316
317        (CastKind::IntToInt, Operand::Copy(op_as_int))
318    };
319
320    // Cast the resulting value to the actual discriminant integer type.
321    let rvalue = Rvalue::Cast(cast_kind, discr_ty_bits, discr.ty);
322    let discr_in_discr_ty =
323        local_decls.push(LocalDecl::with_source_info(discr.ty, source_info)).into();
324    block_data.statements.push(Statement::new(
325        source_info,
326        StatementKind::Assign(Box::new((discr_in_discr_ty, rvalue))),
327    ));
328
329    // Cast the discriminant to a u128 (base for comparisons of enum discriminants).
330    let const_u128 = Ty::new_uint(tcx, ty::UintTy::U128);
331    let rvalue = Rvalue::Cast(CastKind::IntToInt, Operand::Copy(discr_in_discr_ty), const_u128);
332    let discr = local_decls.push(LocalDecl::with_source_info(const_u128, source_info)).into();
333    block_data
334        .statements
335        .push(Statement::new(source_info, StatementKind::Assign(Box::new((discr, rvalue)))));
336
337    discr
338}
339
340// note: This function replaces the current_block terminator.
341fn insert_direct_enum_check<'tcx>(
342    tcx: TyCtxt<'tcx>,
343    local_decls: &mut IndexVec<Local, LocalDecl<'tcx>>,
344    basic_blocks: &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
345    current_block: BasicBlock,
346    source_op: Operand<'tcx>,
347    discr: TyAndSize<'tcx>,
348    op_size: Size,
349    discriminants: Vec<u128>,
350    source_info: SourceInfo,
351    new_block: BasicBlock,
352) {
353    // Local for masked out bits of the discriminant type.
354    let discr_masked =
355        local_decls.push(LocalDecl::with_source_info(tcx.types.u128, source_info)).into();
356
357    // Insert a new target block that is branched to in case of an invalid discriminant.
358    let invalid_discr_block_data = BasicBlockData::new(
359        Terminator {
360            source_info,
361            kind: TerminatorKind::Assert {
362                cond: Operand::Constant(Box::new(ConstOperand {
363                    span: source_info.span,
364                    user_ty: None,
365                    const_: Const::Val(ConstValue::from_bool(false), tcx.types.bool),
366                })),
367                expected: true,
368                target: new_block,
369                msg: Box::new(AssertKind::InvalidEnumConstruction(Operand::Copy(discr_masked))),
370                // This calls panic_invalid_enum_construction, which is #[rustc_nounwind].
371                // We never want to insert an unwind into unsafe code, because unwinding could
372                // make a failing UB check turn into much worse UB when we start unwinding.
373                unwind: UnwindAction::Unreachable,
374            },
375        },
376        false,
377    );
378
379    let invalid_discr_block = basic_blocks.push(invalid_discr_block_data);
380    let block_data = &mut basic_blocks[current_block];
381    let discr_place = insert_discr_cast_to_u128(
382        tcx,
383        local_decls,
384        block_data,
385        source_op,
386        discr,
387        op_size,
388        None,
389        source_info,
390    );
391
392    // Mask out the bits of the discriminant type.
393    let mask = discr.size.unsigned_int_max();
394    let rvalue = Rvalue::BinaryOp(
395        BinOp::BitAnd,
396        Box::new((
397            Operand::Copy(discr_place),
398            Operand::Constant(Box::new(ConstOperand {
399                span: source_info.span,
400                user_ty: None,
401                const_: Const::Val(ConstValue::from_u128(mask), tcx.types.u128),
402            })),
403        )),
404    );
405    block_data
406        .statements
407        .push(Statement::new(source_info, StatementKind::Assign(Box::new((discr_masked, rvalue)))));
408
409    // Branch based on the discriminant value.
410    block_data.terminator = Some(Terminator {
411        source_info,
412        kind: TerminatorKind::SwitchInt {
413            discr: Operand::Copy(discr_masked),
414            targets: SwitchTargets::new(
415                discriminants
416                    .into_iter()
417                    .map(|discr_val| (discr.size.truncate(discr_val), new_block)),
418                invalid_discr_block,
419            ),
420        },
421    });
422}
423
424// Note: this function replaces the block's terminator
425fn insert_uninhabited_enum_check<'tcx>(
426    tcx: TyCtxt<'tcx>,
427    local_decls: &mut IndexVec<Local, LocalDecl<'tcx>>,
428    block_data: &mut BasicBlockData<'tcx>,
429    source_info: SourceInfo,
430    new_block: BasicBlock,
431) {
432    let is_ok: Place<'_> =
433        local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
434    block_data.statements.push(Statement::new(
435        source_info,
436        StatementKind::Assign(Box::new((
437            is_ok,
438            Rvalue::Use(
439                Operand::Constant(Box::new(ConstOperand {
440                    span: source_info.span,
441                    user_ty: None,
442                    const_: Const::Val(ConstValue::from_bool(false), tcx.types.bool),
443                })),
444                WithRetag::Yes, // it's a bool, retag doesn't matter
445            ),
446        ))),
447    ));
448
449    block_data.terminator = Some(Terminator {
450        source_info,
451        kind: TerminatorKind::Assert {
452            cond: Operand::Copy(is_ok),
453            expected: true,
454            target: new_block,
455            msg: Box::new(AssertKind::InvalidEnumConstruction(Operand::Constant(Box::new(
456                ConstOperand {
457                    span: source_info.span,
458                    user_ty: None,
459                    const_: Const::Val(ConstValue::from_u128(0), tcx.types.u128),
460                },
461            )))),
462            // This calls panic_invalid_enum_construction, which is #[rustc_nounwind].
463            // We never want to insert an unwind into unsafe code, because unwinding could
464            // make a failing UB check turn into much worse UB when we start unwinding.
465            unwind: UnwindAction::Unreachable,
466        },
467    });
468}
469
470// Note: this function replaces the block's terminator.
471fn insert_niche_check<'tcx>(
472    tcx: TyCtxt<'tcx>,
473    local_decls: &mut IndexVec<Local, LocalDecl<'tcx>>,
474    block_data: &mut BasicBlockData<'tcx>,
475    source_op: Operand<'tcx>,
476    valid_range: WrappingRange,
477    discr: TyAndSize<'tcx>,
478    op_size: Size,
479    offset: Size,
480    source_info: SourceInfo,
481    new_block: BasicBlock,
482) {
483    let discr = insert_discr_cast_to_u128(
484        tcx,
485        local_decls,
486        block_data,
487        source_op,
488        discr,
489        op_size,
490        Some(offset),
491        source_info,
492    );
493
494    // Compare the discriminant against the valid_range.
495    let start_const = Operand::Constant(Box::new(ConstOperand {
496        span: source_info.span,
497        user_ty: None,
498        const_: Const::Val(ConstValue::from_u128(valid_range.start), tcx.types.u128),
499    }));
500    let end_start_diff_const = Operand::Constant(Box::new(ConstOperand {
501        span: source_info.span,
502        user_ty: None,
503        const_: Const::Val(
504            ConstValue::from_u128(u128::wrapping_sub(valid_range.end, valid_range.start)),
505            tcx.types.u128,
506        ),
507    }));
508
509    let discr_diff: Place<'_> =
510        local_decls.push(LocalDecl::with_source_info(tcx.types.u128, source_info)).into();
511    block_data.statements.push(Statement::new(
512        source_info,
513        StatementKind::Assign(Box::new((
514            discr_diff,
515            Rvalue::BinaryOp(BinOp::Sub, Box::new((Operand::Copy(discr), start_const))),
516        ))),
517    ));
518
519    let is_ok: Place<'_> =
520        local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
521    block_data.statements.push(Statement::new(
522        source_info,
523        StatementKind::Assign(Box::new((
524            is_ok,
525            Rvalue::BinaryOp(
526                // This is a `WrappingRange`, so make sure to get the wrapping right.
527                BinOp::Le,
528                Box::new((Operand::Copy(discr_diff), end_start_diff_const)),
529            ),
530        ))),
531    ));
532
533    block_data.terminator = Some(Terminator {
534        source_info,
535        kind: TerminatorKind::Assert {
536            cond: Operand::Copy(is_ok),
537            expected: true,
538            target: new_block,
539            msg: Box::new(AssertKind::InvalidEnumConstruction(Operand::Copy(discr))),
540            // This calls panic_invalid_enum_construction, which is #[rustc_nounwind].
541            // We never want to insert an unwind into unsafe code, because unwinding could
542            // make a failing UB check turn into much worse UB when we start unwinding.
543            unwind: UnwindAction::Unreachable,
544        },
545    });
546}