-
Notifications
You must be signed in to change notification settings - Fork 97
/
intrinsic.rs
1773 lines (1673 loc) · 78.4 KB
/
intrinsic.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! this module handles intrinsics
use super::typ::{self, pointee_type};
use super::PropertyClass;
use crate::codegen_cprover_gotoc::GotocCtx;
use cbmc::goto_program::{
arithmetic_overflow_result_type, ArithmeticOverflowResult, BinaryOperator, BuiltinFn, Expr,
Location, Stmt, Type, ARITH_OVERFLOW_OVERFLOWED_FIELD, ARITH_OVERFLOW_RESULT_FIELD,
};
use rustc_middle::mir::{BasicBlock, Operand, Place};
use rustc_middle::ty::layout::{LayoutOf, ValidityRequirement};
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty::{Instance, InstanceDef};
use rustc_span::Span;
use tracing::debug;
struct SizeAlign {
size: Expr,
align: Expr,
}
enum VTableInfo {
Size,
Align,
}
impl<'tcx> GotocCtx<'tcx> {
fn binop<F: FnOnce(Expr, Expr) -> Expr>(
&mut self,
p: &Place<'tcx>,
mut fargs: Vec<Expr>,
f: F,
) -> Stmt {
let arg1 = fargs.remove(0);
let arg2 = fargs.remove(0);
let e = f(arg1, arg2);
self.codegen_expr_to_place(p, e)
}
/// Given a call to an compiler intrinsic, generate the call and the `goto` terminator
/// Note that in some cases, the intrinsic might never return (e.g. `panic`) in which case
/// there is no terminator.
pub fn codegen_funcall_of_intrinsic(
&mut self,
func: &Operand<'tcx>,
args: &[Operand<'tcx>],
destination: &Place<'tcx>,
target: &Option<BasicBlock>,
span: Span,
) -> Stmt {
let instance = self.get_intrinsic_instance(func).unwrap();
if let Some(target) = target {
let loc = self.codegen_span(&span);
let fargs = self.codegen_funcall_args(args, false);
Stmt::block(
vec![
self.codegen_intrinsic(instance, fargs, destination, Some(span)),
Stmt::goto(self.current_fn().find_label(target), loc),
],
loc,
)
} else {
self.codegen_never_return_intrinsic(instance, Some(span))
}
}
/// Returns `Some(instance)` if the function is an intrinsic; `None` otherwise
fn get_intrinsic_instance(&self, func: &Operand<'tcx>) -> Option<Instance<'tcx>> {
let funct = self.operand_ty(func);
match &funct.kind() {
ty::FnDef(defid, subst) => {
let instance =
Instance::resolve(self.tcx, ty::ParamEnv::reveal_all(), *defid, subst)
.unwrap()
.unwrap();
if matches!(instance.def, InstanceDef::Intrinsic(_)) {
Some(instance)
} else {
None
}
}
_ => None,
}
}
/// Returns true if the `func` is a call to a compiler intrinsic; false otherwise.
pub fn is_intrinsic(&self, func: &Operand<'tcx>) -> bool {
self.get_intrinsic_instance(func).is_some()
}
/// Handles codegen for non returning intrinsics
/// Non returning intrinsics are not associated with a destination
pub fn codegen_never_return_intrinsic(
&mut self,
instance: Instance<'tcx>,
span: Option<Span>,
) -> Stmt {
let intrinsic = self.symbol_name(instance);
let intrinsic = intrinsic.as_str();
debug!("codegen_never_return_intrinsic:\n\tinstance {:?}\n\tspan {:?}", instance, span);
match intrinsic {
"abort" => {
self.codegen_fatal_error(PropertyClass::Assertion, "reached intrinsic::abort", span)
}
// Transmuting to an uninhabited type is UB.
"transmute" => self.codegen_fatal_error(
PropertyClass::SafetyCheck,
"transmuting to uninhabited type has undefined behavior",
span,
),
_ => self.codegen_fatal_error(
PropertyClass::UnsupportedConstruct,
&format!("Unsupported intrinsic {intrinsic}"),
span,
),
}
}
/// c.f. `rustc_codegen_llvm::intrinsic` `impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx>`
/// `fn codegen_intrinsic_call`
/// c.f. <https://doc.rust-lang.org/std/intrinsics/index.html>
fn codegen_intrinsic(
&mut self,
instance: Instance<'tcx>,
mut fargs: Vec<Expr>,
p: &Place<'tcx>,
span: Option<Span>,
) -> Stmt {
let intrinsic = self.symbol_name(instance);
let intrinsic = intrinsic.as_str();
let loc = self.codegen_span_option(span);
debug!(?instance, "codegen_intrinsic");
debug!(?fargs, "codegen_intrinsic");
debug!(?p, "codegen_intrinsic");
debug!(?span, "codegen_intrinsic");
let sig = instance.ty(self.tcx, ty::ParamEnv::reveal_all()).fn_sig(self.tcx);
let sig = self.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
let ret_ty = self.monomorphize(sig.output());
let farg_types = sig.inputs();
let cbmc_ret_ty = self.codegen_ty(ret_ty);
// Codegens a simple intrinsic: ie. one which maps directly to a matching goto construct
// We need to use this macro form because of a known limitation in rust
// `codegen_simple_intrinsic!(self.get_sqrt(), Type::float())` gives the error message:
// error[E0499]: cannot borrow `*self` as mutable more than once at a time
// --> src/librustc_codegen_llvm/gotoc/intrinsic.rs:76:63
// |
// 76 | codegen_simple_intrinsic!(self.get_sqrt(), Type::double())
// | ---- ------------------------ ^^^^ second mutable borrow occurs here
// | | |
// | | first borrow later used by call
// | first mutable borrow occurs here
// To solve this, we need to store the `self.get_sqrt()` into a temporary variable.
// Using the macro form allows us to keep the call as a oneliner, while still making rust happy.
// TODO: https://github.com/model-checking/kani/issues/5
macro_rules! codegen_simple_intrinsic {
($f:ident) => {{
let mm = self.symbol_table.machine_model();
let casted_fargs =
Expr::cast_arguments_to_target_equivalent_function_parameter_types(
&BuiltinFn::$f.as_expr(),
fargs,
mm,
);
let e = BuiltinFn::$f.call(casted_fargs, loc);
self.codegen_expr_to_place(p, e)
}};
}
// Intrinsics which encode a simple arithmetic operation with overflow check
macro_rules! codegen_op_with_overflow_check {
($f:ident) => {{
let a = fargs.remove(0);
let b = fargs.remove(0);
let op_type = a.typ().clone();
let res = a.$f(b);
// add to symbol table
let struct_tag = self.codegen_arithmetic_overflow_result_type(op_type.clone());
assert_eq!(*res.typ(), struct_tag);
// store the result in a temporary variable
let (var, decl) = self.decl_temp_variable(struct_tag, Some(res), loc);
let check = self.codegen_assert(
var.clone()
.member(ARITH_OVERFLOW_OVERFLOWED_FIELD, &self.symbol_table)
.cast_to(Type::c_bool())
.not(),
PropertyClass::ArithmeticOverflow,
format!("attempt to compute {} which would overflow", intrinsic).as_str(),
loc,
);
self.codegen_expr_to_place(
p,
Expr::statement_expression(
vec![
decl,
check,
var.member(ARITH_OVERFLOW_RESULT_FIELD, &self.symbol_table)
.as_stmt(loc),
],
op_type,
),
)
}};
}
// Intrinsics which encode a division operation with overflow check
macro_rules! codegen_op_with_div_overflow_check {
($f:ident) => {{
let a = fargs.remove(0);
let b = fargs.remove(0);
let div_does_not_overflow = self.div_does_not_overflow(a.clone(), b.clone());
let div_overflow_check = self.codegen_assert(
div_does_not_overflow,
PropertyClass::ArithmeticOverflow,
format!("attempt to compute {} which would overflow", intrinsic).as_str(),
loc,
);
let res = a.$f(b);
let expr_place = self.codegen_expr_to_place(p, res);
Stmt::block(vec![div_overflow_check, expr_place], loc)
}};
}
// Intrinsics which encode a simple wrapping arithmetic operation
macro_rules! codegen_wrapping_op {
($f:ident) => {{ codegen_intrinsic_binop!($f) }};
}
// Intrinsics which encode a simple binary operation
macro_rules! codegen_intrinsic_binop {
($f:ident) => {{ self.binop(p, fargs, |a, b| a.$f(b)) }};
}
// Intrinsics which encode a simple binary operation which need a machine model
macro_rules! codegen_intrinsic_binop_with_mm {
($f:ident) => {{
let arg1 = fargs.remove(0);
let arg2 = fargs.remove(0);
let e = arg1.$f(arg2, self.symbol_table.machine_model());
self.codegen_expr_to_place(p, e)
}};
}
// Intrinsics which encode count intrinsics (ctlz, cttz)
// The `allow_zero` flag determines if calling these builtins with 0 causes UB
macro_rules! codegen_count_intrinsic {
($builtin: ident, $allow_zero: expr) => {{
let arg = fargs.remove(0);
self.codegen_expr_to_place(p, arg.$builtin($allow_zero))
}};
}
// Intrinsics which encode a value known during compilation
macro_rules! codegen_intrinsic_const {
() => {{
let value = self
.tcx
.const_eval_instance(ty::ParamEnv::reveal_all(), instance, span)
.unwrap();
// We assume that the intrinsic has type checked at this point, so
// we can use the place type as the expression type.
let e = self.codegen_const_value(value, self.place_ty(p), span.as_ref());
self.codegen_expr_to_place(p, e)
}};
}
macro_rules! codegen_size_align {
($which: ident) => {{
let tp_ty = instance.substs.type_at(0);
let arg = fargs.remove(0);
let size_align = self.size_and_align_of_dst(tp_ty, arg);
self.codegen_expr_to_place(p, size_align.$which)
}};
}
// Most atomic intrinsics do:
// 1. Perform an operation on a primary argument (e.g., addition)
// 2. Return the previous value of the primary argument
// The primary argument is always passed by reference. In a sequential
// context, atomic orderings can be ignored.
//
// Atomic binops are transformed as follows:
// -------------------------
// var = atomic_op(var1, var2)
// -------------------------
// unsigned char tmp;
// tmp = *var1;
// *var1 = op(*var1, var2);
// var = tmp;
// -------------------------
// Note: Atomic arithmetic operations wrap around on overflow.
macro_rules! codegen_atomic_binop {
($op: ident) => {{
let loc = self.codegen_span_option(span);
self.store_concurrent_construct(intrinsic, loc);
let var1_ref = fargs.remove(0);
let var1 = var1_ref.dereference();
let (tmp, decl_stmt) =
self.decl_temp_variable(var1.typ().clone(), Some(var1.to_owned()), loc);
let var2 = fargs.remove(0);
let op_expr = (var1.clone()).$op(var2).with_location(loc);
let assign_stmt = (var1.clone()).assign(op_expr, loc);
let res_stmt = self.codegen_expr_to_place(p, tmp.clone());
Stmt::atomic_block(vec![decl_stmt, assign_stmt, res_stmt], loc)
}};
}
macro_rules! unstable_codegen {
($($tt:tt)*) => {{
let e = self.codegen_unimplemented_expr(
&format!("'{}' intrinsic", intrinsic),
cbmc_ret_ty,
loc,
"https://github.com/model-checking/kani/issues/new/choose",
);
self.codegen_expr_to_place(p, e)
}};
}
if let Some(stripped) = intrinsic.strip_prefix("simd_shuffle") {
assert!(fargs.len() == 3, "`simd_shuffle` had unexpected arguments {fargs:?}");
let n: u64 = self.simd_shuffle_length(stripped, farg_types, span);
return self.codegen_intrinsic_simd_shuffle(fargs, p, farg_types, ret_ty, n, span);
}
match intrinsic {
"add_with_overflow" => {
self.codegen_op_with_overflow(BinaryOperator::OverflowResultPlus, fargs, p, loc)
}
"arith_offset" => self.codegen_offset(intrinsic, instance, fargs, p, loc),
"assert_inhabited" => self.codegen_assert_intrinsic(instance, intrinsic, span),
"assert_mem_uninitialized_valid" => {
self.codegen_assert_intrinsic(instance, intrinsic, span)
}
"assert_zero_valid" => self.codegen_assert_intrinsic(instance, intrinsic, span),
// https://doc.rust-lang.org/core/intrinsics/fn.assume.html
// Informs the optimizer that a condition is always true.
// If the condition is false, the behavior is undefined.
"assume" => self.codegen_assert_assume(
fargs.remove(0).cast_to(Type::bool()),
PropertyClass::Assume,
"assumption failed",
loc,
),
"atomic_and_seqcst" => codegen_atomic_binop!(bitand),
"atomic_and_acquire" => codegen_atomic_binop!(bitand),
"atomic_and_acqrel" => codegen_atomic_binop!(bitand),
"atomic_and_release" => codegen_atomic_binop!(bitand),
"atomic_and_relaxed" => codegen_atomic_binop!(bitand),
name if name.starts_with("atomic_cxchg") => {
self.codegen_atomic_cxchg(intrinsic, fargs, p, loc)
}
"atomic_fence_seqcst" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_fence_acquire" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_fence_acqrel" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_fence_release" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_load_seqcst" => self.codegen_atomic_load(intrinsic, fargs, p, loc),
"atomic_load_acquire" => self.codegen_atomic_load(intrinsic, fargs, p, loc),
"atomic_load_relaxed" => self.codegen_atomic_load(intrinsic, fargs, p, loc),
"atomic_load_unordered" => self.codegen_atomic_load(intrinsic, fargs, p, loc),
"atomic_max_seqcst" => codegen_atomic_binop!(max),
"atomic_max_acquire" => codegen_atomic_binop!(max),
"atomic_max_acqrel" => codegen_atomic_binop!(max),
"atomic_max_release" => codegen_atomic_binop!(max),
"atomic_max_relaxed" => codegen_atomic_binop!(max),
"atomic_min_seqcst" => codegen_atomic_binop!(min),
"atomic_min_acquire" => codegen_atomic_binop!(min),
"atomic_min_acqrel" => codegen_atomic_binop!(min),
"atomic_min_release" => codegen_atomic_binop!(min),
"atomic_min_relaxed" => codegen_atomic_binop!(min),
"atomic_nand_seqcst" => codegen_atomic_binop!(bitnand),
"atomic_nand_acquire" => codegen_atomic_binop!(bitnand),
"atomic_nand_acqrel" => codegen_atomic_binop!(bitnand),
"atomic_nand_release" => codegen_atomic_binop!(bitnand),
"atomic_nand_relaxed" => codegen_atomic_binop!(bitnand),
"atomic_or_seqcst" => codegen_atomic_binop!(bitor),
"atomic_or_acquire" => codegen_atomic_binop!(bitor),
"atomic_or_acqrel" => codegen_atomic_binop!(bitor),
"atomic_or_release" => codegen_atomic_binop!(bitor),
"atomic_or_relaxed" => codegen_atomic_binop!(bitor),
"atomic_singlethreadfence_seqcst" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_singlethreadfence_acquire" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_singlethreadfence_acqrel" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_singlethreadfence_release" => self.codegen_atomic_noop(intrinsic, loc),
"atomic_store_seqcst" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_store_release" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_store_relaxed" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_store_unordered" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_umax_seqcst" => codegen_atomic_binop!(max),
"atomic_umax_acquire" => codegen_atomic_binop!(max),
"atomic_umax_acqrel" => codegen_atomic_binop!(max),
"atomic_umax_release" => codegen_atomic_binop!(max),
"atomic_umax_relaxed" => codegen_atomic_binop!(max),
"atomic_umin_seqcst" => codegen_atomic_binop!(min),
"atomic_umin_acquire" => codegen_atomic_binop!(min),
"atomic_umin_acqrel" => codegen_atomic_binop!(min),
"atomic_umin_release" => codegen_atomic_binop!(min),
"atomic_umin_relaxed" => codegen_atomic_binop!(min),
"atomic_xadd_seqcst" => codegen_atomic_binop!(plus),
"atomic_xadd_acquire" => codegen_atomic_binop!(plus),
"atomic_xadd_acqrel" => codegen_atomic_binop!(plus),
"atomic_xadd_release" => codegen_atomic_binop!(plus),
"atomic_xadd_relaxed" => codegen_atomic_binop!(plus),
"atomic_xchg_seqcst" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_xchg_acquire" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_xchg_acqrel" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_xchg_release" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_xchg_relaxed" => self.codegen_atomic_store(intrinsic, fargs, p, loc),
"atomic_xor_seqcst" => codegen_atomic_binop!(bitxor),
"atomic_xor_acquire" => codegen_atomic_binop!(bitxor),
"atomic_xor_acqrel" => codegen_atomic_binop!(bitxor),
"atomic_xor_release" => codegen_atomic_binop!(bitxor),
"atomic_xor_relaxed" => codegen_atomic_binop!(bitxor),
"atomic_xsub_seqcst" => codegen_atomic_binop!(sub),
"atomic_xsub_acquire" => codegen_atomic_binop!(sub),
"atomic_xsub_acqrel" => codegen_atomic_binop!(sub),
"atomic_xsub_release" => codegen_atomic_binop!(sub),
"atomic_xsub_relaxed" => codegen_atomic_binop!(sub),
"bitreverse" => self.codegen_expr_to_place(p, fargs.remove(0).bitreverse()),
// black_box is an identity function that hints to the compiler
// to be maximally pessimistic to limit optimizations
"black_box" => self.codegen_expr_to_place(p, fargs.remove(0)),
"breakpoint" => Stmt::skip(loc),
"bswap" => self.codegen_expr_to_place(p, fargs.remove(0).bswap()),
"caller_location" => self.codegen_unimplemented_stmt(
intrinsic,
loc,
"https://github.com/model-checking/kani/issues/374",
),
"ceilf32" => codegen_simple_intrinsic!(Ceilf),
"ceilf64" => codegen_simple_intrinsic!(Ceil),
"copy" => self.codegen_copy(intrinsic, false, fargs, farg_types, Some(p), loc),
"copy_nonoverlapping" => unreachable!(
"Expected `core::intrinsics::unreachable` to be handled by `StatementKind::CopyNonOverlapping`"
),
"copysignf32" => codegen_simple_intrinsic!(Copysignf),
"copysignf64" => codegen_simple_intrinsic!(Copysign),
"cosf32" => codegen_simple_intrinsic!(Cosf),
"cosf64" => codegen_simple_intrinsic!(Cos),
"ctlz" => codegen_count_intrinsic!(ctlz, true),
"ctlz_nonzero" => codegen_count_intrinsic!(ctlz, false),
"ctpop" => self.codegen_expr_to_place(p, fargs.remove(0).popcount()),
"cttz" => codegen_count_intrinsic!(cttz, true),
"cttz_nonzero" => codegen_count_intrinsic!(cttz, false),
"discriminant_value" => {
let ty = instance.substs.type_at(0);
let e = self.codegen_get_discriminant(fargs.remove(0).dereference(), ty, ret_ty);
self.codegen_expr_to_place(p, e)
}
"exact_div" => self.codegen_exact_div(fargs, p, loc),
"exp2f32" => unstable_codegen!(codegen_simple_intrinsic!(Exp2f)),
"exp2f64" => unstable_codegen!(codegen_simple_intrinsic!(Exp2)),
"expf32" => unstable_codegen!(codegen_simple_intrinsic!(Expf)),
"expf64" => unstable_codegen!(codegen_simple_intrinsic!(Exp)),
"fabsf32" => codegen_simple_intrinsic!(Fabsf),
"fabsf64" => codegen_simple_intrinsic!(Fabs),
"fadd_fast" => {
let fargs_clone = fargs.clone();
let binop_stmt = codegen_intrinsic_binop!(plus);
self.add_finite_args_checks(intrinsic, fargs_clone, binop_stmt, span)
}
"fdiv_fast" => {
let fargs_clone = fargs.clone();
let binop_stmt = codegen_intrinsic_binop!(div);
self.add_finite_args_checks(intrinsic, fargs_clone, binop_stmt, span)
}
"floorf32" => codegen_simple_intrinsic!(Floorf),
"floorf64" => codegen_simple_intrinsic!(Floor),
"fmaf32" => unstable_codegen!(codegen_simple_intrinsic!(Fmaf)),
"fmaf64" => unstable_codegen!(codegen_simple_intrinsic!(Fma)),
"fmul_fast" => {
let fargs_clone = fargs.clone();
let binop_stmt = codegen_intrinsic_binop!(mul);
self.add_finite_args_checks(intrinsic, fargs_clone, binop_stmt, span)
}
"forget" => Stmt::skip(loc),
"fsub_fast" => {
let fargs_clone = fargs.clone();
let binop_stmt = codegen_intrinsic_binop!(sub);
self.add_finite_args_checks(intrinsic, fargs_clone, binop_stmt, span)
}
"likely" => self.codegen_expr_to_place(p, fargs.remove(0)),
"log10f32" => unstable_codegen!(codegen_simple_intrinsic!(Log10f)),
"log10f64" => unstable_codegen!(codegen_simple_intrinsic!(Log10)),
"log2f32" => unstable_codegen!(codegen_simple_intrinsic!(Log2f)),
"log2f64" => unstable_codegen!(codegen_simple_intrinsic!(Log2)),
"logf32" => unstable_codegen!(codegen_simple_intrinsic!(Logf)),
"logf64" => unstable_codegen!(codegen_simple_intrinsic!(Log)),
"maxnumf32" => codegen_simple_intrinsic!(Fmaxf),
"maxnumf64" => codegen_simple_intrinsic!(Fmax),
"min_align_of" => codegen_intrinsic_const!(),
"min_align_of_val" => codegen_size_align!(align),
"minnumf32" => codegen_simple_intrinsic!(Fminf),
"minnumf64" => codegen_simple_intrinsic!(Fmin),
"mul_with_overflow" => {
self.codegen_op_with_overflow(BinaryOperator::OverflowResultMult, fargs, p, loc)
}
"nearbyintf32" => codegen_simple_intrinsic!(Nearbyintf),
"nearbyintf64" => codegen_simple_intrinsic!(Nearbyint),
"needs_drop" => codegen_intrinsic_const!(),
// As of https://github.com/rust-lang/rust/pull/110822 the `offset` intrinsic is lowered to `mir::BinOp::Offset`
"offset" => unreachable!(
"Expected `core::intrinsics::unreachable` to be handled by `BinOp::OffSet`"
),
"powf32" => unstable_codegen!(codegen_simple_intrinsic!(Powf)),
"powf64" => unstable_codegen!(codegen_simple_intrinsic!(Pow)),
"powif32" => unstable_codegen!(codegen_simple_intrinsic!(Powif)),
"powif64" => unstable_codegen!(codegen_simple_intrinsic!(Powi)),
"pref_align_of" => codegen_intrinsic_const!(),
"ptr_guaranteed_cmp" => self.codegen_ptr_guaranteed_cmp(fargs, p),
"ptr_offset_from" => self.codegen_ptr_offset_from(fargs, p, loc),
"ptr_offset_from_unsigned" => self.codegen_ptr_offset_from_unsigned(fargs, p, loc),
"raw_eq" => self.codegen_intrinsic_raw_eq(instance, fargs, p, loc),
"rintf32" => codegen_simple_intrinsic!(Rintf),
"rintf64" => codegen_simple_intrinsic!(Rint),
"rotate_left" => codegen_intrinsic_binop!(rol),
"rotate_right" => codegen_intrinsic_binop!(ror),
"roundf32" => codegen_simple_intrinsic!(Roundf),
"roundf64" => codegen_simple_intrinsic!(Round),
"saturating_add" => codegen_intrinsic_binop_with_mm!(saturating_add),
"saturating_sub" => codegen_intrinsic_binop_with_mm!(saturating_sub),
"sinf32" => codegen_simple_intrinsic!(Sinf),
"sinf64" => codegen_simple_intrinsic!(Sin),
"simd_add" => self.codegen_simd_op_with_overflow(
Expr::plus,
Expr::add_overflow_p,
fargs,
intrinsic,
p,
loc,
),
"simd_and" => codegen_intrinsic_binop!(bitand),
// TODO: `simd_div` and `simd_rem` don't check for overflow cases.
// <https://github.com/model-checking/kani/issues/1970>
"simd_div" => codegen_intrinsic_binop!(div),
"simd_eq" => self.codegen_simd_cmp(Expr::vector_eq, fargs, p, span, farg_types, ret_ty),
"simd_extract" => {
self.codegen_intrinsic_simd_extract(fargs, p, farg_types, ret_ty, span)
}
"simd_ge" => self.codegen_simd_cmp(Expr::vector_ge, fargs, p, span, farg_types, ret_ty),
"simd_gt" => self.codegen_simd_cmp(Expr::vector_gt, fargs, p, span, farg_types, ret_ty),
"simd_insert" => {
self.codegen_intrinsic_simd_insert(fargs, p, cbmc_ret_ty, farg_types, span, loc)
}
"simd_le" => self.codegen_simd_cmp(Expr::vector_le, fargs, p, span, farg_types, ret_ty),
"simd_lt" => self.codegen_simd_cmp(Expr::vector_lt, fargs, p, span, farg_types, ret_ty),
"simd_mul" => self.codegen_simd_op_with_overflow(
Expr::mul,
Expr::mul_overflow_p,
fargs,
intrinsic,
p,
loc,
),
"simd_ne" => {
self.codegen_simd_cmp(Expr::vector_neq, fargs, p, span, farg_types, ret_ty)
}
"simd_or" => codegen_intrinsic_binop!(bitor),
// TODO: `simd_div` and `simd_rem` don't check for overflow cases.
// <https://github.com/model-checking/kani/issues/1970>
"simd_rem" => codegen_intrinsic_binop!(rem),
// TODO: `simd_shl` and `simd_shr` don't check overflow cases.
// <https://github.com/model-checking/kani/issues/1963>
"simd_shl" => codegen_intrinsic_binop!(shl),
"simd_shr" => {
if fargs[0].typ().base_type().unwrap().is_signed(self.symbol_table.machine_model())
{
codegen_intrinsic_binop!(ashr)
} else {
codegen_intrinsic_binop!(lshr)
}
}
// "simd_shuffle#" => handled in an `if` preceding this match
"simd_sub" => self.codegen_simd_op_with_overflow(
Expr::sub,
Expr::sub_overflow_p,
fargs,
intrinsic,
p,
loc,
),
"simd_xor" => codegen_intrinsic_binop!(bitxor),
"size_of" => unreachable!(),
"size_of_val" => codegen_size_align!(size),
"sqrtf32" => unstable_codegen!(codegen_simple_intrinsic!(Sqrtf)),
"sqrtf64" => unstable_codegen!(codegen_simple_intrinsic!(Sqrt)),
"sub_with_overflow" => {
self.codegen_op_with_overflow(BinaryOperator::OverflowResultMinus, fargs, p, loc)
}
"transmute" => self.codegen_intrinsic_transmute(fargs, ret_ty, p),
"truncf32" => codegen_simple_intrinsic!(Truncf),
"truncf64" => codegen_simple_intrinsic!(Trunc),
"try" => self.codegen_unimplemented_stmt(
intrinsic,
loc,
"https://github.com/model-checking/kani/issues/267",
),
"type_id" => codegen_intrinsic_const!(),
"type_name" => codegen_intrinsic_const!(),
"unaligned_volatile_load" => {
unstable_codegen!(self.codegen_expr_to_place(p, fargs.remove(0).dereference()))
}
"unchecked_add" => codegen_op_with_overflow_check!(add_overflow_result),
"unchecked_div" => codegen_op_with_div_overflow_check!(div),
"unchecked_mul" => codegen_op_with_overflow_check!(mul_overflow_result),
"unchecked_rem" => codegen_op_with_div_overflow_check!(rem),
"unchecked_shl" => codegen_intrinsic_binop!(shl),
"unchecked_shr" => {
if fargs[0].typ().is_signed(self.symbol_table.machine_model()) {
codegen_intrinsic_binop!(ashr)
} else {
codegen_intrinsic_binop!(lshr)
}
}
"unchecked_sub" => codegen_op_with_overflow_check!(sub_overflow_result),
"unlikely" => self.codegen_expr_to_place(p, fargs.remove(0)),
"unreachable" => unreachable!(
"Expected `std::intrinsics::unreachable` to be handled by `TerminatorKind::Unreachable`"
),
"volatile_copy_memory" => unstable_codegen!(codegen_intrinsic_copy!(Memmove)),
"volatile_copy_nonoverlapping_memory" => {
unstable_codegen!(codegen_intrinsic_copy!(Memcpy))
}
"volatile_load" => self.codegen_volatile_load(fargs, farg_types, p, loc),
"volatile_store" => {
assert!(self.place_ty(p).is_unit());
self.codegen_volatile_store(fargs, farg_types, loc)
}
"vtable_size" => self.vtable_info(VTableInfo::Size, fargs, p, loc),
"vtable_align" => self.vtable_info(VTableInfo::Align, fargs, p, loc),
"wrapping_add" => codegen_wrapping_op!(plus),
"wrapping_mul" => codegen_wrapping_op!(mul),
"wrapping_sub" => codegen_wrapping_op!(sub),
"write_bytes" => {
assert!(self.place_ty(p).is_unit());
self.codegen_write_bytes(fargs, farg_types, loc)
}
// Unimplemented
_ => self.codegen_unimplemented_stmt(
intrinsic,
loc,
"https://github.com/model-checking/kani/issues/new/choose",
),
}
}
// Fast math intrinsics for floating point operations like `fadd_fast`
// assume that their inputs are finite:
// https://doc.rust-lang.org/std/intrinsics/fn.fadd_fast.html
// This function adds assertions to the statement which performs the
// operation and checks for overflow failures.
fn add_finite_args_checks(
&mut self,
intrinsic: &str,
mut fargs: Vec<Expr>,
stmt: Stmt,
span: Option<Span>,
) -> Stmt {
let arg1 = fargs.remove(0);
let arg2 = fargs.remove(0);
let msg1 = format!("first argument for {intrinsic} is finite");
let msg2 = format!("second argument for {intrinsic} is finite");
let loc = self.codegen_span_option(span);
let finite_check1 = self.codegen_assert_assume(
arg1.is_finite(),
PropertyClass::FiniteCheck,
msg1.as_str(),
loc,
);
let finite_check2 = self.codegen_assert_assume(
arg2.is_finite(),
PropertyClass::FiniteCheck,
msg2.as_str(),
loc,
);
Stmt::block(vec![finite_check1, finite_check2, stmt], loc)
}
fn div_does_not_overflow(&self, a: Expr, b: Expr) -> Expr {
let mm = self.symbol_table.machine_model();
let atyp = a.typ();
let btyp = b.typ();
let dividend_is_int_min = if atyp.is_signed(mm) {
a.clone().eq(atyp.min_int_expr(mm))
} else {
Expr::bool_false()
};
let divisor_is_minus_one =
if btyp.is_signed(mm) { b.clone().eq(btyp.one().neg()) } else { Expr::bool_false() };
dividend_is_int_min.and(divisor_is_minus_one).not()
}
/// Intrinsics of the form *_with_overflow
fn codegen_op_with_overflow(
&mut self,
binop: BinaryOperator,
mut fargs: Vec<Expr>,
place: &Place<'tcx>,
loc: Location,
) -> Stmt {
let place_ty = self.place_ty(place);
let result_type = self.codegen_ty(place_ty);
let left = fargs.remove(0);
let right = fargs.remove(0);
let res = self.codegen_binop_with_overflow(binop, left, right, result_type.clone(), loc);
self.codegen_expr_to_place(
place,
Expr::statement_expression(vec![res.as_stmt(loc)], result_type),
)
}
fn codegen_exact_div(&mut self, mut fargs: Vec<Expr>, p: &Place<'tcx>, loc: Location) -> Stmt {
// Check for undefined behavior conditions defined in
// https://doc.rust-lang.org/std/intrinsics/fn.exact_div.html
let a = fargs.remove(0);
let b = fargs.remove(0);
let atyp = a.typ();
let btyp = b.typ();
let division_is_exact = a.clone().rem(b.clone()).eq(atyp.zero());
let divisor_is_nonzero = b.clone().neq(btyp.zero());
let division_does_not_overflow = self.div_does_not_overflow(a.clone(), b.clone());
Stmt::block(
vec![
self.codegen_assert_assume(
division_is_exact,
PropertyClass::ExactDiv,
"exact_div arguments divide exactly",
loc,
),
self.codegen_assert_assume(
divisor_is_nonzero,
PropertyClass::ExactDiv,
"exact_div divisor is nonzero",
loc,
),
self.codegen_assert_assume(
division_does_not_overflow,
PropertyClass::ExactDiv,
"exact_div division does not overflow",
loc,
),
self.codegen_expr_to_place(p, a.div(b)),
],
loc,
)
}
/// Generates either a panic or no-op for `assert_*` intrinsics.
/// These are intrinsics that statically compile to panics if the type
/// layout is invalid so we get a message that mentions the offending type.
///
/// <https://doc.rust-lang.org/std/intrinsics/fn.assert_inhabited.html>
/// <https://doc.rust-lang.org/std/intrinsics/fn.assert_mem_uninitialized_valid.html>
/// <https://doc.rust-lang.org/std/intrinsics/fn.assert_zero_valid.html>
fn codegen_assert_intrinsic(
&mut self,
instance: Instance<'tcx>,
intrinsic: &str,
span: Option<Span>,
) -> Stmt {
let ty = instance.substs.type_at(0);
let layout = self.layout_of(ty);
// Note: We follow the pattern seen in `codegen_panic_intrinsic` from `rustc_codegen_ssa`
// https://github.com/rust-lang/rust/blob/master/compiler/rustc_codegen_ssa/src/mir/block.rs
// For all intrinsics we first check `is_uninhabited` to give a more
// precise error message
if layout.abi.is_uninhabited() {
return self.codegen_fatal_error(
PropertyClass::SafetyCheck,
&format!("attempted to instantiate uninhabited type `{ty}`"),
span,
);
}
let param_env_and_type = ty::ParamEnv::reveal_all().and(ty);
// Then we check if the type allows "raw" initialization for the cases
// where memory is zero-initialized or entirely uninitialized
if intrinsic == "assert_zero_valid"
&& !self
.tcx
.check_validity_requirement((ValidityRequirement::Zero, param_env_and_type))
.unwrap()
{
return self.codegen_fatal_error(
PropertyClass::SafetyCheck,
&format!("attempted to zero-initialize type `{ty}`, which is invalid"),
span,
);
}
if intrinsic == "assert_mem_uninitialized_valid"
&& !self
.tcx
.check_validity_requirement((
ValidityRequirement::UninitMitigated0x01Fill,
param_env_and_type,
))
.unwrap()
{
return self.codegen_fatal_error(
PropertyClass::SafetyCheck,
&format!("attempted to leave type `{ty}` uninitialized, which is invalid"),
span,
);
}
// Otherwise we generate a no-op statement
let loc = self.codegen_span_option(span);
Stmt::skip(loc)
}
/// An atomic load simply returns the value referenced
/// in its argument (as in other atomic operations)
/// -------------------------
/// var = atomic_load(var1)
/// -------------------------
/// var = *var1;
/// -------------------------
fn codegen_atomic_load(
&mut self,
intrinsic: &str,
mut fargs: Vec<Expr>,
p: &Place<'tcx>,
loc: Location,
) -> Stmt {
self.store_concurrent_construct(intrinsic, loc);
let var1_ref = fargs.remove(0);
let var1 = var1_ref.dereference().with_location(loc);
let res_stmt = self.codegen_expr_to_place(p, var1);
Stmt::atomic_block(vec![res_stmt], loc)
}
/// An atomic compare-and-exchange updates the value referenced in
/// its primary argument and returns a tuple that contains:
/// * the previous value
/// * a boolean value indicating whether the operation was successful or not
/// In a sequential context, the update is always sucessful so we assume the
/// second value to be true.
/// -------------------------
/// var = atomic_cxchg(var1, var2, var3)
/// -------------------------
/// unsigned char tmp;
/// tmp = *var1;
/// if (*var1 == var2) *var1 = var3;
/// var = (tmp, true);
/// -------------------------
fn codegen_atomic_cxchg(
&mut self,
intrinsic: &str,
mut fargs: Vec<Expr>,
p: &Place<'tcx>,
loc: Location,
) -> Stmt {
self.store_concurrent_construct(intrinsic, loc);
let var1_ref = fargs.remove(0);
let var1 = var1_ref.dereference().with_location(loc);
let (tmp, decl_stmt) =
self.decl_temp_variable(var1.typ().clone(), Some(var1.to_owned()), loc);
let var2 = fargs.remove(0).with_location(loc);
let var3 = fargs.remove(0).with_location(loc);
let eq_expr = (var1.clone()).eq(var2);
let assign_stmt = var1.assign(var3, loc);
let cond_update_stmt = Stmt::if_then_else(eq_expr, assign_stmt, None, loc);
let place_type = self.place_ty(p);
let res_type = self.codegen_ty(place_type);
let tuple_expr =
Expr::struct_expr_from_values(res_type, vec![tmp, Expr::c_true()], &self.symbol_table)
.with_location(loc);
let res_stmt = self.codegen_expr_to_place(p, tuple_expr);
Stmt::atomic_block(vec![decl_stmt, cond_update_stmt, res_stmt], loc)
}
/// An atomic store updates the value referenced in
/// its primary argument and returns its previous value
/// -------------------------
/// var = atomic_store(var1, var2)
/// -------------------------
/// unsigned char tmp;
/// tmp = *var1;
/// *var1 = var2;
/// var = tmp;
/// -------------------------
fn codegen_atomic_store(
&mut self,
intrinsic: &str,
mut fargs: Vec<Expr>,
p: &Place<'tcx>,
loc: Location,
) -> Stmt {
self.store_concurrent_construct(intrinsic, loc);
let var1_ref = fargs.remove(0);
let var1 = var1_ref.dereference().with_location(loc);
let (tmp, decl_stmt) =
self.decl_temp_variable(var1.typ().clone(), Some(var1.to_owned()), loc);
let var2 = fargs.remove(0).with_location(loc);
let assign_stmt = var1.assign(var2, loc);
let res_stmt = self.codegen_expr_to_place(p, tmp);
Stmt::atomic_block(vec![decl_stmt, assign_stmt, res_stmt], loc)
}
/// Atomic no-ops (e.g., atomic_fence) are transformed into SKIP statements
fn codegen_atomic_noop(&mut self, intrinsic: &str, loc: Location) -> Stmt {
self.store_concurrent_construct(intrinsic, loc);
let skip_stmt = Stmt::skip(loc);
Stmt::atomic_block(vec![skip_stmt], loc)
}
/// Copies `count * size_of::<T>()` bytes from `src` to `dst`.
///
/// Note that this function handles code generation for:
/// 1. The `copy` intrinsic.
/// <https://doc.rust-lang.org/core/intrinsics/fn.copy.html>
/// 2. The `CopyNonOverlapping` statement.
/// <https://doc.rust-lang.org/core/intrinsics/fn.copy_nonoverlapping.html>
///
/// Undefined behavior if any of these conditions are violated:
/// * Both `src`/`dst` must be properly aligned (done by alignment checks)
/// * Both `src`/`dst` must be valid for reads/writes of `count *
/// size_of::<T>()` bytes (done by calls to `memmove`)
/// * (Exclusive to nonoverlapping copy) The region of memory beginning
/// at `src` with a size of `count * size_of::<T>()` bytes must *not*
/// overlap with the region of memory beginning at `dst` with the same
/// size.
/// In addition, we check that computing `count` in bytes (i.e., the third
/// argument of the copy built-in call) would not overflow.
pub fn codegen_copy(
&mut self,
intrinsic: &str,
is_non_overlapping: bool,
mut fargs: Vec<Expr>,
farg_types: &[Ty<'tcx>],
p: Option<&Place<'tcx>>,
loc: Location,
) -> Stmt {
// The two first arguments are pointers. It's safe to cast them to void
// pointers or directly unwrap the `pointee_type` result as seen later.
let src = fargs.remove(0).cast_to(Type::void_pointer());
let dst = fargs.remove(0).cast_to(Type::void_pointer());
// Generate alignment checks for both pointers
let src_align = self.is_ptr_aligned(farg_types[0], src.clone());
let src_align_check = self.codegen_assert_assume(
src_align,
PropertyClass::SafetyCheck,
"`src` must be properly aligned",
loc,
);
let dst_align = self.is_ptr_aligned(farg_types[1], dst.clone());
let dst_align_check = self.codegen_assert_assume(
dst_align,
PropertyClass::SafetyCheck,
"`dst` must be properly aligned",
loc,
);
// Compute the number of bytes to be copied
let count = fargs.remove(0);
let pointee_type = pointee_type(farg_types[0]).unwrap();
let (count_bytes, overflow_check) =
self.count_in_bytes(count, pointee_type, Type::size_t(), intrinsic, loc);
// Build the call to the copy built-in (`memmove` or `memcpy`)
let copy_builtin = if is_non_overlapping { BuiltinFn::Memcpy } else { BuiltinFn::Memmove };
let copy_call = copy_builtin.call(vec![dst.clone(), src, count_bytes.clone()], loc);
// The C implementations of `memmove` and `memcpy` do not allow an
// invalid pointer for `src` nor `dst`, but the LLVM implementations
// specify that a zero-length copy is a no-op:
// https://llvm.org/docs/LangRef.html#llvm-memmove-intrinsic
// https://llvm.org/docs/LangRef.html#llvm-memcpy-intrinsic
// This comes up specifically when handling the empty string; CBMC will
// fail on passing a reference to it unless we codegen this zero check.
let copy_if_nontrivial = count_bytes.is_zero().ternary(dst, copy_call);
let copy_expr = if let Some(p) = p {
self.codegen_expr_to_place(p, copy_if_nontrivial)
} else {
copy_if_nontrivial.as_stmt(loc)
};
Stmt::block(vec![src_align_check, dst_align_check, overflow_check, copy_expr], loc)
}
// In some contexts (e.g., compilation-time evaluation),
// `ptr_guaranteed_cmp` compares two pointers and returns:
// * 2 if the result is unknown.
// * 1 if they are guaranteed to be equal.
// * 0 if they are guaranteed to be not equal.
// But at runtime, this intrinsic behaves as a regular pointer comparison.
// Therefore, we return 1 if the pointers are equal and 0 otherwise.
//
// This intrinsic replaces `ptr_guaranteed_eq` and `ptr_guaranteed_ne`:
// https://doc.rust-lang.org/beta/std/primitive.pointer.html#method.guaranteed_eq
fn codegen_ptr_guaranteed_cmp(&mut self, mut fargs: Vec<Expr>, p: &Place<'tcx>) -> Stmt {