rustc_mir_transform/
lower_intrinsics.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! Lowers intrinsic calls

use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_middle::{bug, span_bug};
use rustc_span::sym;

use crate::take_array;

pub(super) struct LowerIntrinsics;

impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics {
    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
        let local_decls = &body.local_decls;
        for block in body.basic_blocks.as_mut() {
            let terminator = block.terminator.as_mut().unwrap();
            if let TerminatorKind::Call { func, args, destination, target, .. } =
                &mut terminator.kind
                && let ty::FnDef(def_id, generic_args) = *func.ty(local_decls, tcx).kind()
                && let Some(intrinsic) = tcx.intrinsic(def_id)
            {
                match intrinsic.name {
                    sym::unreachable => {
                        terminator.kind = TerminatorKind::Unreachable;
                    }
                    sym::ub_checks => {
                        let target = target.unwrap();
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::NullaryOp(NullOp::UbChecks, tcx.types.bool),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::forget => {
                        let target = target.unwrap();
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
                                    span: terminator.source_info.span,
                                    user_ty: None,
                                    const_: Const::zero_sized(tcx.types.unit),
                                }))),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::copy_nonoverlapping => {
                        let target = target.unwrap();
                        let Ok([src, dst, count]) = take_array(args) else {
                            bug!("Wrong arguments for copy_non_overlapping intrinsic");
                        };
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Intrinsic(Box::new(
                                NonDivergingIntrinsic::CopyNonOverlapping(
                                    rustc_middle::mir::CopyNonOverlapping {
                                        src: src.node,
                                        dst: dst.node,
                                        count: count.node,
                                    },
                                ),
                            )),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::assume => {
                        let target = target.unwrap();
                        let Ok([arg]) = take_array(args) else {
                            bug!("Wrong arguments for assume intrinsic");
                        };
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Intrinsic(Box::new(
                                NonDivergingIntrinsic::Assume(arg.node),
                            )),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::wrapping_add
                    | sym::wrapping_sub
                    | sym::wrapping_mul
                    | sym::three_way_compare
                    | sym::unchecked_add
                    | sym::unchecked_sub
                    | sym::unchecked_mul
                    | sym::unchecked_div
                    | sym::unchecked_rem
                    | sym::unchecked_shl
                    | sym::unchecked_shr => {
                        let target = target.unwrap();
                        let Ok([lhs, rhs]) = take_array(args) else {
                            bug!("Wrong arguments for {} intrinsic", intrinsic.name);
                        };
                        let bin_op = match intrinsic.name {
                            sym::wrapping_add => BinOp::Add,
                            sym::wrapping_sub => BinOp::Sub,
                            sym::wrapping_mul => BinOp::Mul,
                            sym::three_way_compare => BinOp::Cmp,
                            sym::unchecked_add => BinOp::AddUnchecked,
                            sym::unchecked_sub => BinOp::SubUnchecked,
                            sym::unchecked_mul => BinOp::MulUnchecked,
                            sym::unchecked_div => BinOp::Div,
                            sym::unchecked_rem => BinOp::Rem,
                            sym::unchecked_shl => BinOp::ShlUnchecked,
                            sym::unchecked_shr => BinOp::ShrUnchecked,
                            _ => bug!("unexpected intrinsic"),
                        };
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::BinaryOp(bin_op, Box::new((lhs.node, rhs.node))),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
                        let target = target.unwrap();
                        let Ok([lhs, rhs]) = take_array(args) else {
                            bug!("Wrong arguments for {} intrinsic", intrinsic.name);
                        };
                        let bin_op = match intrinsic.name {
                            sym::add_with_overflow => BinOp::AddWithOverflow,
                            sym::sub_with_overflow => BinOp::SubWithOverflow,
                            sym::mul_with_overflow => BinOp::MulWithOverflow,
                            _ => bug!("unexpected intrinsic"),
                        };
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::BinaryOp(bin_op, Box::new((lhs.node, rhs.node))),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::size_of | sym::min_align_of => {
                        let target = target.unwrap();
                        let tp_ty = generic_args.type_at(0);
                        let null_op = match intrinsic.name {
                            sym::size_of => NullOp::SizeOf,
                            sym::min_align_of => NullOp::AlignOf,
                            _ => bug!("unexpected intrinsic"),
                        };
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::NullaryOp(null_op, tp_ty),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::read_via_copy => {
                        let Ok([arg]) = take_array(args) else {
                            span_bug!(terminator.source_info.span, "Wrong number of arguments");
                        };
                        let derefed_place = if let Some(place) = arg.node.place()
                            && let Some(local) = place.as_local()
                        {
                            tcx.mk_place_deref(local.into())
                        } else {
                            span_bug!(
                                terminator.source_info.span,
                                "Only passing a local is supported"
                            );
                        };
                        // Add new statement at the end of the block that does the read, and patch
                        // up the terminator.
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::Use(Operand::Copy(derefed_place)),
                            ))),
                        });
                        terminator.kind = match *target {
                            None => {
                                // No target means this read something uninhabited,
                                // so it must be unreachable.
                                TerminatorKind::Unreachable
                            }
                            Some(target) => TerminatorKind::Goto { target },
                        }
                    }
                    sym::write_via_move => {
                        let target = target.unwrap();
                        let Ok([ptr, val]) = take_array(args) else {
                            span_bug!(
                                terminator.source_info.span,
                                "Wrong number of arguments for write_via_move intrinsic",
                            );
                        };
                        let derefed_place = if let Some(place) = ptr.node.place()
                            && let Some(local) = place.as_local()
                        {
                            tcx.mk_place_deref(local.into())
                        } else {
                            span_bug!(
                                terminator.source_info.span,
                                "Only passing a local is supported"
                            );
                        };
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                derefed_place,
                                Rvalue::Use(val.node),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::discriminant_value => {
                        let target = target.unwrap();
                        let Ok([arg]) = take_array(args) else {
                            span_bug!(
                                terminator.source_info.span,
                                "Wrong arguments for discriminant_value intrinsic"
                            );
                        };
                        let arg = arg.node.place().unwrap();
                        let arg = tcx.mk_place_deref(arg);
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::Discriminant(arg),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::offset => {
                        let target = target.unwrap();
                        let Ok([ptr, delta]) = take_array(args) else {
                            span_bug!(
                                terminator.source_info.span,
                                "Wrong number of arguments for offset intrinsic",
                            );
                        };
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::BinaryOp(BinOp::Offset, Box::new((ptr.node, delta.node))),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::transmute | sym::transmute_unchecked => {
                        let dst_ty = destination.ty(local_decls, tcx).ty;
                        let Ok([arg]) = take_array(args) else {
                            span_bug!(
                                terminator.source_info.span,
                                "Wrong number of arguments for transmute intrinsic",
                            );
                        };

                        // Always emit the cast, even if we transmute to an uninhabited type,
                        // because that lets CTFE and codegen generate better error messages
                        // when such a transmute actually ends up reachable.
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::Cast(CastKind::Transmute, arg.node, dst_ty),
                            ))),
                        });
                        if let Some(target) = *target {
                            terminator.kind = TerminatorKind::Goto { target };
                        } else {
                            terminator.kind = TerminatorKind::Unreachable;
                        }
                    }
                    sym::aggregate_raw_ptr => {
                        let Ok([data, meta]) = take_array(args) else {
                            span_bug!(
                                terminator.source_info.span,
                                "Wrong number of arguments for aggregate_raw_ptr intrinsic",
                            );
                        };
                        let target = target.unwrap();
                        let pointer_ty = generic_args.type_at(0);
                        let kind = if let ty::RawPtr(pointee_ty, mutability) = pointer_ty.kind() {
                            AggregateKind::RawPtr(*pointee_ty, *mutability)
                        } else {
                            span_bug!(
                                terminator.source_info.span,
                                "Return type of aggregate_raw_ptr intrinsic must be a raw pointer",
                            );
                        };
                        let fields = [data.node, meta.node];
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::Aggregate(Box::new(kind), fields.into()),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    sym::ptr_metadata => {
                        let Ok([ptr]) = take_array(args) else {
                            span_bug!(
                                terminator.source_info.span,
                                "Wrong number of arguments for ptr_metadata intrinsic",
                            );
                        };
                        let target = target.unwrap();
                        block.statements.push(Statement {
                            source_info: terminator.source_info,
                            kind: StatementKind::Assign(Box::new((
                                *destination,
                                Rvalue::UnaryOp(UnOp::PtrMetadata, ptr.node),
                            ))),
                        });
                        terminator.kind = TerminatorKind::Goto { target };
                    }
                    _ => {}
                }
            }
        }
    }
}