forked from model-checking/kani
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrvalue.rs
1296 lines (1223 loc) · 58.5 KB
/
rvalue.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
use super::typ::pointee_type;
use crate::codegen_cprover_gotoc::codegen::place::{ProjectedPlace, TypeOrVariant};
use crate::codegen_cprover_gotoc::codegen::PropertyClass;
use crate::codegen_cprover_gotoc::utils::{dynamic_fat_ptr, slice_fat_ptr};
use crate::codegen_cprover_gotoc::{GotocCtx, VtableCtx};
use crate::kani_middle::coercion::{
extract_unsize_casting, CoerceUnsizedInfo, CoerceUnsizedIterator, CoercionBase,
};
use crate::unwrap_or_return_codegen_unimplemented;
use cbmc::goto_program::{Expr, Location, Stmt, Symbol, Type};
use cbmc::MachineModel;
use cbmc::{btree_string_map, InternString, InternedString};
use num::bigint::BigInt;
use rustc_middle::mir::{AggregateKind, BinOp, CastKind, NullOp, Operand, Place, Rvalue, UnOp};
use rustc_middle::ty::adjustment::PointerCast;
use rustc_middle::ty::layout::LayoutOf;
use rustc_middle::ty::{self, Instance, IntTy, Ty, TyCtxt, UintTy, VtblEntry};
use rustc_target::abi::{FieldsShape, Size, TagEncoding, VariantIdx, Variants};
use std::collections::BTreeMap;
use tracing::{debug, trace, warn};
impl<'tcx> GotocCtx<'tcx> {
fn codegen_comparison(&mut self, op: &BinOp, e1: &Operand<'tcx>, e2: &Operand<'tcx>) -> Expr {
let left_op = self.codegen_operand(e1);
let right_op = self.codegen_operand(e2);
let is_float = self.operand_ty(e1).is_floating_point();
comparison_expr(op, left_op, right_op, is_float)
}
/// This function codegen comparison for fat pointers.
/// Fat pointer comparison must compare the raw data pointer as well as its metadata portion.
///
/// Since vtable pointer comparison is not well defined and it has many nuances, we decided to
/// fail if the user code performs such comparison.
///
/// See <https://github.com/model-checking/kani/issues/327> for more details.
fn codegen_comparison_fat_ptr(
&mut self,
op: &BinOp,
left_op: &Operand<'tcx>,
right_op: &Operand<'tcx>,
loc: Location,
) -> Expr {
debug!(?op, ?left_op, ?right_op, "codegen_comparison_fat_ptr");
let left_typ = self.operand_ty(left_op);
let right_typ = self.operand_ty(left_op);
assert_eq!(left_typ, right_typ, "Cannot compare pointers of different types");
assert!(self.is_fat_pointer(left_typ));
if self.is_vtable_fat_pointer(left_typ) {
// Codegen an assertion failure since vtable comparison is not stable.
let ret_type = Type::Bool;
let body = vec![
self.codegen_assert_assume_false(
PropertyClass::SafetyCheck,
format!("Reached unstable vtable comparison '{op:?}'").as_str(),
loc,
),
ret_type.nondet().as_stmt(loc).with_location(loc),
];
Expr::statement_expression(body, ret_type).with_location(loc)
} else {
// Compare data pointer.
let left_ptr = self.codegen_operand(left_op);
let left_data = left_ptr.clone().member("data", &self.symbol_table);
let right_ptr = self.codegen_operand(right_op);
let right_data = right_ptr.clone().member("data", &self.symbol_table);
let data_cmp = comparison_expr(op, left_data.clone(), right_data.clone(), false);
// Compare the slice metadata (this logic could be adapted to compare vtable if needed).
let left_len = left_ptr.member("len", &self.symbol_table);
let right_len = right_ptr.member("len", &self.symbol_table);
let metadata_cmp = comparison_expr(op, left_len, right_len, false);
// Join the results.
// https://github.com/rust-lang/rust/pull/29781
match op {
// Only equal if both parts are equal.
BinOp::Eq => data_cmp.and(metadata_cmp),
// It is different if any is different.
BinOp::Ne => data_cmp.or(metadata_cmp),
// If data is different, only compare data.
// If data is equal, apply operator to metadata.
BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
let data_eq =
comparison_expr(&BinOp::Eq, left_data.clone(), right_data.clone(), false);
let data_strict_comp =
comparison_expr(&get_strict_operator(op), left_data, right_data, false);
data_strict_comp.or(data_eq.and(metadata_cmp))
}
_ => unreachable!("Unexpected operator {:?}", op),
}
}
}
fn codegen_unchecked_scalar_binop(
&mut self,
op: &BinOp,
e1: &Operand<'tcx>,
e2: &Operand<'tcx>,
) -> Expr {
let ce1 = self.codegen_operand(e1);
let ce2 = self.codegen_operand(e2);
match op {
BinOp::BitAnd => ce1.bitand(ce2),
BinOp::BitOr => ce1.bitor(ce2),
BinOp::BitXor => ce1.bitxor(ce2),
BinOp::Div => ce1.div(ce2),
BinOp::Rem => ce1.rem(ce2),
_ => unreachable!("Unexpected {:?}", op),
}
}
fn codegen_scalar_binop(&mut self, op: &BinOp, e1: &Operand<'tcx>, e2: &Operand<'tcx>) -> Expr {
let ce1 = self.codegen_operand(e1);
let ce2 = self.codegen_operand(e2);
match op {
BinOp::Add => ce1.plus(ce2),
BinOp::Sub => ce1.sub(ce2),
BinOp::Mul => ce1.mul(ce2),
BinOp::Shl => ce1.shl(ce2),
BinOp::Shr => {
if self.operand_ty(e1).is_signed() {
ce1.ashr(ce2)
} else {
ce1.lshr(ce2)
}
}
_ => unreachable!(),
}
}
/// Codegens expressions of the type `let a = [4u8; 6];`
fn codegen_rvalue_repeat(
&mut self,
op: &Operand<'tcx>,
sz: ty::Const<'tcx>,
res_ty: Ty<'tcx>,
loc: Location,
) -> Expr {
let res_t = self.codegen_ty(res_ty);
let op_expr = self.codegen_operand(op);
let width = sz.try_eval_usize(self.tcx, ty::ParamEnv::reveal_all()).unwrap();
Expr::struct_expr(
res_t,
btree_string_map![("0", op_expr.array_constant(width))],
&self.symbol_table,
)
.with_location(loc)
}
fn codegen_rvalue_len(&mut self, p: &Place<'tcx>) -> Expr {
let pt = self.place_ty(p);
match pt.kind() {
ty::Array(_, sz) => self.codegen_const(*sz, None),
ty::Slice(_) => unwrap_or_return_codegen_unimplemented!(self, self.codegen_place(p))
.fat_ptr_goto_expr
.unwrap()
.member("len", &self.symbol_table),
_ => unreachable!("Len(_) called on type that has no length: {:?}", pt),
}
}
fn codegen_rvalue_checked_binary_op(
&mut self,
op: &BinOp,
e1: &Operand<'tcx>,
e2: &Operand<'tcx>,
res_ty: Ty<'tcx>,
) -> Expr {
let ce1 = self.codegen_operand(e1);
let ce2 = self.codegen_operand(e2);
fn shift_max(t: Ty<'_>, mm: &MachineModel) -> Expr {
match t.kind() {
ty::Int(k) => match k {
IntTy::I8 => Expr::int_constant(7, Type::signed_int(8)),
IntTy::I16 => Expr::int_constant(15, Type::signed_int(16)),
IntTy::I32 => Expr::int_constant(31, Type::signed_int(32)),
IntTy::I64 => Expr::int_constant(63, Type::signed_int(64)),
IntTy::I128 => Expr::int_constant(127, Type::signed_int(128)),
IntTy::Isize => Expr::int_constant(mm.pointer_width - 1, Type::ssize_t()),
},
ty::Uint(k) => match k {
UintTy::U8 => Expr::int_constant(7, Type::unsigned_int(8)),
UintTy::U16 => Expr::int_constant(15, Type::unsigned_int(16)),
UintTy::U32 => Expr::int_constant(31, Type::unsigned_int(32)),
UintTy::U64 => Expr::int_constant(63, Type::unsigned_int(64)),
UintTy::U128 => Expr::int_constant(127, Type::unsigned_int(128)),
UintTy::Usize => Expr::int_constant(mm.pointer_width - 1, Type::size_t()),
},
_ => unreachable!(),
}
}
match op {
BinOp::Add => {
let res = ce1.add_overflow(ce2);
Expr::struct_expr_from_values(
self.codegen_ty(res_ty),
vec![res.result, res.overflowed.cast_to(Type::c_bool())],
&self.symbol_table,
)
}
BinOp::Sub => {
let res = ce1.sub_overflow(ce2);
Expr::struct_expr_from_values(
self.codegen_ty(res_ty),
vec![res.result, res.overflowed.cast_to(Type::c_bool())],
&self.symbol_table,
)
}
BinOp::Mul => {
let res = ce1.mul_overflow(ce2);
Expr::struct_expr_from_values(
self.codegen_ty(res_ty),
vec![res.result, res.overflowed.cast_to(Type::c_bool())],
&self.symbol_table,
)
}
BinOp::Shl => {
let t1 = self.operand_ty(e1);
let max = shift_max(t1, self.symbol_table.machine_model());
Expr::struct_expr_from_values(
self.codegen_ty(res_ty),
vec![
ce1.shl(ce2.clone()),
ce2.cast_to(self.codegen_ty(t1)).gt(max).cast_to(Type::c_bool()),
],
&self.symbol_table,
)
}
BinOp::Shr => {
let t1 = self.operand_ty(e1);
let max = shift_max(t1, self.symbol_table.machine_model());
Expr::struct_expr_from_values(
self.codegen_ty(res_ty),
vec![
if t1.is_signed() { ce1.ashr(ce2.clone()) } else { ce1.lshr(ce2.clone()) },
ce2.cast_to(self.codegen_ty(t1)).gt(max).cast_to(Type::c_bool()),
],
&self.symbol_table,
)
}
_ => unreachable!(),
}
}
fn codegen_rvalue_binary_op(
&mut self,
op: &BinOp,
e1: &Operand<'tcx>,
e2: &Operand<'tcx>,
loc: Location,
) -> Expr {
match op {
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Shl | BinOp::Shr => {
self.codegen_scalar_binop(op, e1, e2)
}
BinOp::Div | BinOp::Rem | BinOp::BitXor | BinOp::BitAnd | BinOp::BitOr => {
self.codegen_unchecked_scalar_binop(op, e1, e2)
}
BinOp::Eq | BinOp::Lt | BinOp::Le | BinOp::Ne | BinOp::Ge | BinOp::Gt => {
if self.is_fat_pointer(self.operand_ty(e1)) {
self.codegen_comparison_fat_ptr(op, e1, e2, loc)
} else {
self.codegen_comparison(op, e1, e2)
}
}
// https://doc.rust-lang.org/std/primitive.pointer.html#method.offset
BinOp::Offset => {
let ce1 = self.codegen_operand(e1);
let ce2 = self.codegen_operand(e2);
ce1.plus(ce2)
}
}
}
/// This code will generate an expression that initializes an enumeration.
///
/// It will first create a temporary variant with the same enum type.
/// Initialize the case structure and set its discriminant.
/// Finally, it will return the temporary value.
fn codegen_rvalue_enum_aggregate(
&mut self,
variant_index: VariantIdx,
operands: &[Operand<'tcx>],
res_ty: Ty<'tcx>,
loc: Location,
) -> Expr {
let mut stmts = vec![];
let typ = self.codegen_ty(res_ty);
// 1- Create a temporary value of the enum type.
tracing::debug!(?typ, ?res_ty, "aggregate_enum");
let (temp_var, decl) = self.decl_temp_variable(typ.clone(), None, loc);
stmts.push(decl);
if !operands.is_empty() {
// 2- Initialize the members of the temporary variant.
let initial_projection = ProjectedPlace::try_new(
temp_var.clone(),
TypeOrVariant::Type(res_ty),
None,
None,
self,
)
.unwrap();
let variant_proj = self.codegen_variant_lvalue(initial_projection, variant_index);
let variant_expr = variant_proj.goto_expr.clone();
let layout = self.layout_of(res_ty);
let fields = match &layout.variants {
Variants::Single { index } => {
if *index != variant_index {
// This may occur if all variants except for the one pointed by
// index can never be constructed. Generic code might still try
// to initialize the non-existing invariant.
trace!(?res_ty, ?variant_index, "Unreachable invariant");
return Expr::nondet(typ);
}
&layout.fields
}
Variants::Multiple { variants, .. } => &variants[variant_index].fields,
};
debug!(?variant_expr, ?fields, ?operands, "codegen_aggregate enum");
let init_struct = Expr::struct_expr_from_values(
variant_expr.typ().clone(),
fields
.index_by_increasing_offset()
.map(|idx| {
let op = self.codegen_operand(&operands[idx]);
debug!(?op, ?idx, "codegen_aggregate enum op");
op
})
.collect(),
&self.symbol_table,
);
let assign_case = variant_proj.goto_expr.assign(init_struct, loc);
stmts.push(assign_case);
}
// 3- Set discriminant.
let set_discriminant =
self.codegen_set_discriminant(res_ty, temp_var.clone(), variant_index, loc);
stmts.push(set_discriminant);
// 4- Return temporary variable.
stmts.push(temp_var.as_stmt(loc));
Expr::statement_expression(stmts, typ)
}
fn codegen_rvalue_aggregate(
&mut self,
aggregate: &AggregateKind<'tcx>,
operands: &[Operand<'tcx>],
res_ty: Ty<'tcx>,
loc: Location,
) -> Expr {
match *aggregate {
AggregateKind::Array(et) => {
if et.is_unit() {
Expr::struct_expr_from_values(
self.codegen_ty(res_ty),
vec![],
&self.symbol_table,
)
} else {
Expr::struct_expr_from_values(
self.codegen_ty(res_ty),
vec![Expr::array_expr(
self.codegen_ty_raw_array(res_ty),
operands.iter().map(|o| self.codegen_operand(o)).collect(),
)],
&self.symbol_table,
)
}
}
AggregateKind::Adt(_, _, _, _, Some(active_field_index)) => {
assert!(res_ty.is_union());
assert_eq!(operands.len(), 1);
let typ = self.codegen_ty(res_ty);
let components = typ.lookup_components(&self.symbol_table).unwrap();
Expr::union_expr(
typ,
components[active_field_index].name(),
self.codegen_operand(&operands[0]),
&self.symbol_table,
)
}
AggregateKind::Adt(..) if res_ty.is_simd() => {
let typ = self.codegen_ty(res_ty);
let layout = self.layout_of(res_ty);
// TODO: this fails a type consistency check in firecracker/devices, need to
// investigate whether a transmute is needed
Expr::vector_expr(
typ,
layout
.fields
.index_by_increasing_offset()
.map(|idx| self.codegen_operand(&operands[idx]))
.collect(),
)
}
AggregateKind::Adt(_, variant_index, ..) if res_ty.is_enum() => {
// enum
self.codegen_rvalue_enum_aggregate(variant_index, operands, res_ty, loc)
}
AggregateKind::Adt(..) | AggregateKind::Closure(..) | AggregateKind::Tuple => {
let typ = self.codegen_ty(res_ty);
let layout = self.layout_of(res_ty);
Expr::struct_expr_from_values(
typ,
layout
.fields
.index_by_increasing_offset()
.map(|idx| self.codegen_operand(&operands[idx]))
.collect(),
&self.symbol_table,
)
}
AggregateKind::Generator(_, _, _) => {
// 1- Generate direct fields initialization.
// 2- Return union initialization with direct_fields
debug!(?aggregate, ?operands, "codegen_aggregate generator");
let layout = self.layout_of(res_ty);
let discr_field = match &layout.variants {
Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } => {
tag_field
}
Variants::Multiple { .. } => {
unreachable!("Expected generator with direct encoding, got: {layout:?}")
}
Variants::Single { .. } => {
unreachable!("Expected generator with multiple variants, got: {layout:?}")
}
};
let gen_type = self.codegen_ty(res_ty);
let field_name = "direct_fields";
let component = gen_type.lookup_field(field_name, &self.symbol_table).unwrap();
let mut op_idx = 0;
let direct_fields_val = Expr::struct_expr_from_values(
component.typ(),
layout
.fields
.index_by_increasing_offset()
.map(|idx| {
if idx == *discr_field {
let discr_t = self.codegen_enum_discr_typ(res_ty);
Expr::int_constant(0, self.codegen_ty(discr_t))
} else {
let expr = self.codegen_operand(&operands[op_idx]);
op_idx += 1;
expr
}
})
.collect(),
&self.symbol_table,
);
let typ = self.codegen_ty(res_ty);
// union
Expr::union_expr(typ, field_name, direct_fields_val, &self.symbol_table)
}
}
}
pub fn codegen_rvalue(&mut self, rv: &Rvalue<'tcx>, loc: Location) -> Expr {
let res_ty = self.rvalue_ty(rv);
debug!(?rv, "codegen_rvalue");
match rv {
Rvalue::Use(p) => self.codegen_operand(p),
Rvalue::Repeat(op, sz) => {
let sz = self.monomorphize(*sz);
self.codegen_rvalue_repeat(op, sz, res_ty, loc)
}
Rvalue::Ref(_, _, p) | Rvalue::AddressOf(_, p) => self.codegen_place_ref(p),
Rvalue::Len(p) => self.codegen_rvalue_len(p),
// Rust has begun distinguishing "ptr -> num" and "num -> ptr" (providence-relevant casts) but we do not yet:
// Should we? Tracking ticket: https://github.com/model-checking/kani/issues/1274
Rvalue::Cast(
CastKind::IntToInt
| CastKind::FloatToFloat
| CastKind::FloatToInt
| CastKind::IntToFloat
| CastKind::FnPtrToPtr
| CastKind::PtrToPtr
| CastKind::PointerExposeAddress
| CastKind::PointerFromExposedAddress,
e,
t,
) => {
let t = self.monomorphize(*t);
self.codegen_misc_cast(e, t)
}
Rvalue::Cast(CastKind::DynStar, _, _) => {
let ty = self.codegen_ty(res_ty);
self.codegen_unimplemented_expr(
"CastKind::DynStar",
ty,
loc,
"https://github.com/model-checking/kani/issues/1784",
)
}
Rvalue::Cast(CastKind::Pointer(k), e, t) => {
let t = self.monomorphize(*t);
self.codegen_pointer_cast(k, e, t, loc)
}
Rvalue::BinaryOp(op, box (ref e1, ref e2)) => {
self.codegen_rvalue_binary_op(op, e1, e2, loc)
}
Rvalue::CheckedBinaryOp(op, box (ref e1, ref e2)) => {
self.codegen_rvalue_checked_binary_op(op, e1, e2, res_ty)
}
Rvalue::NullaryOp(k, t) => {
let t = self.monomorphize(*t);
let layout = self.layout_of(t);
match k {
NullOp::SizeOf => Expr::int_constant(layout.size.bytes_usize(), Type::size_t()),
NullOp::AlignOf => Expr::int_constant(layout.align.abi.bytes(), Type::size_t()),
}
}
Rvalue::ShallowInitBox(ref operand, content_ty) => {
// The behaviour of ShallowInitBox is simply transmuting *mut u8 to Box<T>.
// See https://github.com/rust-lang/compiler-team/issues/460 for more details.
let operand = self.codegen_operand(operand);
let t = self.monomorphize(*content_ty);
let box_ty = self.tcx.mk_box(t);
let box_ty = self.codegen_ty(box_ty);
let cbmc_t = self.codegen_ty(t);
let box_contents = operand.cast_to(cbmc_t.to_pointer());
self.box_value(box_contents, box_ty)
}
Rvalue::UnaryOp(op, e) => match op {
UnOp::Not => {
if self.operand_ty(e).is_bool() {
self.codegen_operand(e).not()
} else {
self.codegen_operand(e).bitnot()
}
}
UnOp::Neg => self.codegen_operand(e).neg(),
},
Rvalue::Discriminant(p) => {
let place =
unwrap_or_return_codegen_unimplemented!(self, self.codegen_place(p)).goto_expr;
let pt = self.place_ty(p);
self.codegen_get_discriminant(place, pt, res_ty)
}
Rvalue::Aggregate(ref k, operands) => {
self.codegen_rvalue_aggregate(k, operands, res_ty, loc)
}
Rvalue::ThreadLocalRef(def_id) => {
// Since Kani is single-threaded, we treat a thread local like a static variable:
self.store_concurrent_construct("thread local (replaced by static variable)", loc);
self.codegen_static_pointer(*def_id, true)
}
// A CopyForDeref is equivalent to a read from a place at the codegen level.
// https://github.com/rust-lang/rust/blob/1673f1450eeaf4a5452e086db0fe2ae274a0144f/compiler/rustc_middle/src/mir/syntax.rs#L1055
Rvalue::CopyForDeref(place) => {
unwrap_or_return_codegen_unimplemented!(self, self.codegen_place(place)).goto_expr
}
}
}
pub fn codegen_discriminant_field(&self, place: Expr, ty: Ty<'tcx>) -> Expr {
let layout = self.layout_of(ty);
assert!(
matches!(
&layout.variants,
Variants::Multiple { tag_encoding: TagEncoding::Direct, .. }
),
"discriminant field (`case`) only exists for multiple variants and direct encoding"
);
let expr = if ty.is_generator() {
// Generators are translated somewhat differently from enums (see [`GotoCtx::codegen_ty_generator`]).
// As a consequence, the discriminant is accessed as `.direct_fields.case` instead of just `.case`.
place.member("direct_fields", &self.symbol_table)
} else {
place
};
expr.member("case", &self.symbol_table)
}
/// e: ty
/// get the discriminant of e, of type res_ty
pub fn codegen_get_discriminant(&mut self, e: Expr, ty: Ty<'tcx>, res_ty: Ty<'tcx>) -> Expr {
let layout = self.layout_of(ty);
match &layout.variants {
Variants::Single { index } => {
let discr_val = layout
.ty
.discriminant_for_variant(self.tcx, *index)
.map_or(index.as_u32() as u128, |discr| discr.val);
Expr::int_constant(discr_val, self.codegen_ty(res_ty))
}
Variants::Multiple { tag_encoding, .. } => match tag_encoding {
TagEncoding::Direct => {
self.codegen_discriminant_field(e, ty).cast_to(self.codegen_ty(res_ty))
}
TagEncoding::Niche { untagged_variant, niche_variants, niche_start } => {
// This code follows the logic in the ssa codegen backend:
// https://github.com/rust-lang/rust/blob/fee75fbe11b1fad5d93c723234178b2a329a3c03/compiler/rustc_codegen_ssa/src/mir/place.rs#L247
// See also the cranelift backend:
// https://github.com/rust-lang/rust/blob/05d22212e89588e7c443cc6b9bc0e4e02fdfbc8d/compiler/rustc_codegen_cranelift/src/discriminant.rs#L116
let offset = match &layout.fields {
FieldsShape::Arbitrary { offsets, .. } => offsets[0],
_ => unreachable!("niche encoding must have arbitrary fields"),
};
// Compute relative discriminant value (`niche_val - niche_start`).
//
// "We remap `niche_start..=niche_start + n` (which may wrap around) to
// (non-wrap-around) `0..=n`, to be able to check whether the discriminant
// corresponds to a niche variant with one comparison."
// https://github.com/rust-lang/rust/blob/fee75fbe11b1fad5d93c723234178b2a329a3c03/compiler/rustc_codegen_ssa/src/mir/place.rs#L247
//
// Note: niche_variants can only represent values that fit in a u32.
let result_type = self.codegen_ty(res_ty);
let discr_mir_ty = self.codegen_enum_discr_typ(ty);
let discr_type = self.codegen_ty(discr_mir_ty);
let niche_val = self.codegen_get_niche(e, offset, discr_type);
let relative_discr =
wrapping_sub(&niche_val, u64::try_from(*niche_start).unwrap());
let relative_max =
niche_variants.end().as_u32() - niche_variants.start().as_u32();
let is_niche = if relative_max == 0 {
relative_discr.clone().is_zero()
} else {
relative_discr
.clone()
.le(Expr::int_constant(relative_max, relative_discr.typ().clone()))
};
let niche_discr = {
let relative_discr = if relative_max == 0 {
result_type.zero()
} else {
relative_discr.cast_to(result_type.clone())
};
relative_discr.plus(Expr::int_constant(
niche_variants.start().as_u32(),
result_type.clone(),
))
};
is_niche.ternary(
niche_discr,
Expr::int_constant(untagged_variant.as_u32(), result_type),
)
}
},
}
}
/// Extract the niche value from `v`. This value should be of type `niche_ty` and located
/// at byte offset `offset`
pub fn codegen_get_niche(&self, v: Expr, offset: Size, niche_ty: Type) -> Expr {
if offset == Size::ZERO {
v.reinterpret_cast(niche_ty)
} else {
v // t: T
.address_of() // &t: T*
.cast_to(Type::unsigned_int(8).to_pointer()) // (u8 *)&t: u8 *
.plus(Expr::int_constant(offset.bytes(), Type::size_t())) // ((u8 *)&t) + offset: u8 *
.cast_to(niche_ty.to_pointer()) // (N *)(((u8 *)&t) + offset): N *
.dereference() // *(N *)(((u8 *)&t) + offset): N
}
}
fn codegen_fat_ptr_to_fat_ptr_cast(&mut self, src: &Operand<'tcx>, dst_t: Ty<'tcx>) -> Expr {
debug!("codegen_fat_ptr_to_fat_ptr_cast |{:?}| |{:?}|", src, dst_t);
let src_goto_expr = self.codegen_operand(src);
let dst_goto_typ = self.codegen_ty(dst_t);
let dst_data_type = dst_goto_typ.lookup_field_type("data", &self.symbol_table).unwrap();
let dst_data_field = (
"data",
src_goto_expr.clone().member("data", &self.symbol_table).cast_to(dst_data_type),
);
let dst_metadata_field = if let Some(vtable_typ) =
dst_goto_typ.lookup_field_type("vtable", &self.symbol_table)
{
("vtable", src_goto_expr.member("vtable", &self.symbol_table).cast_to(vtable_typ))
} else if let Some(len_typ) = dst_goto_typ.lookup_field_type("len", &self.symbol_table) {
("len", src_goto_expr.member("len", &self.symbol_table).cast_to(len_typ))
} else {
unreachable!("fat pointer with neither vtable nor len. {:?} {:?}", src, dst_t);
};
Expr::struct_expr(
dst_goto_typ,
btree_string_map![dst_data_field, dst_metadata_field],
&self.symbol_table,
)
}
fn codegen_fat_ptr_to_thin_ptr_cast(&mut self, src: &Operand<'tcx>, dst_t: Ty<'tcx>) -> Expr {
debug!("codegen_fat_ptr_to_thin_ptr_cast |{:?}| |{:?}|", src, dst_t);
let src_goto_expr = self.codegen_operand(src);
let dst_goto_typ = self.codegen_ty(dst_t);
// In a vtable fat pointer, the data member is a void pointer,
// so ensure the pointer has the correct type before dereferencing it.
src_goto_expr.member("data", &self.symbol_table).cast_to(dst_goto_typ)
}
/// This handles all kinds of casts, except a limited subset that are instead
/// handled by [`Self::codegen_pointer_cast`].
fn codegen_misc_cast(&mut self, src: &Operand<'tcx>, dst_t: Ty<'tcx>) -> Expr {
let src_t = self.operand_ty(src);
debug!(
"codegen_misc_cast: casting operand {:?} from type {:?} to type {:?}",
src, src_t, dst_t
);
// number casting
if src_t.is_numeric() && dst_t.is_numeric() {
return self.codegen_operand(src).cast_to(self.codegen_ty(dst_t));
}
// Behind the scenes, char is just a 32bit integer
if (src_t.is_integral() && dst_t.is_char()) || (src_t.is_char() && dst_t.is_integral()) {
return self.codegen_operand(src).cast_to(self.codegen_ty(dst_t));
}
// Cast an enum to its discriminant
if src_t.is_enum() && dst_t.is_integral() {
let operand = self.codegen_operand(src);
return self.codegen_get_discriminant(operand, src_t, dst_t);
}
// Cast between fat pointers
if self.is_fat_pointer(src_t) && self.is_fat_pointer(dst_t) {
return self.codegen_fat_ptr_to_fat_ptr_cast(src, dst_t);
}
if self.is_fat_pointer(src_t) && !self.is_fat_pointer(dst_t) {
return self.codegen_fat_ptr_to_thin_ptr_cast(src, dst_t);
}
// pointer casting. from a pointer / reference to another pointer / reference
// notice that if fat pointer is involved, it cannot be the destination, which is t.
match dst_t.kind() {
ty::Ref(_, mut dst_subt, _) | ty::RawPtr(ty::TypeAndMut { ty: mut dst_subt, .. }) => {
// this is a noop in the case dst_subt is a Projection or Opaque type
dst_subt = self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), dst_subt);
match dst_subt.kind() {
ty::Slice(_) | ty::Str | ty::Dynamic(_, _, _) => {
//TODO: this does the wrong thing on Strings/fixme_boxed_str.rs
// if we cast to slice or string, then we know the source is also a slice or string,
// so there shouldn't be anything to do
//DSN The one time I've seen this for dynamic, it was just casting from const* to mut*
// TODO: see if it is accurate
self.codegen_operand(src)
}
_ => match src_t.kind() {
ty::Ref(_, mut src_subt, _)
| ty::RawPtr(ty::TypeAndMut { ty: mut src_subt, .. }) => {
// this is a noop in the case dst_subt is a Projection or Opaque type
src_subt = self
.tcx
.normalize_erasing_regions(ty::ParamEnv::reveal_all(), src_subt);
match src_subt.kind() {
ty::Slice(_) | ty::Str | ty::Dynamic(..) => self
.codegen_operand(src)
.member("data", &self.symbol_table)
.cast_to(self.codegen_ty(dst_t)),
_ => self.codegen_operand(src).cast_to(self.codegen_ty(dst_t)),
}
}
ty::Int(_) | ty::Uint(_) | ty::FnPtr(..) => {
self.codegen_operand(src).cast_to(self.codegen_ty(dst_t))
}
_ => unreachable!(),
},
}
}
ty::Int(_) | ty::Uint(_) => self.codegen_operand(src).cast_to(self.codegen_ty(dst_t)),
_ => unreachable!(),
}
}
/// "Pointer casts" are particular kinds of pointer-to-pointer casts.
/// See the [`PointerCast`] type for specifics.
/// Note that this does not include all casts involving pointers,
/// many of which are instead handled by [`Self::codegen_misc_cast`] instead.
fn codegen_pointer_cast(
&mut self,
k: &PointerCast,
operand: &Operand<'tcx>,
t: Ty<'tcx>,
loc: Location,
) -> Expr {
debug!(cast=?k, op=?operand, ?loc, "codegen_pointer_cast");
match k {
PointerCast::ReifyFnPointer => match self.operand_ty(operand).kind() {
ty::FnDef(def_id, substs) => {
let instance =
Instance::resolve(self.tcx, ty::ParamEnv::reveal_all(), *def_id, substs)
.unwrap()
.unwrap();
// We need to handle this case in a special way because `codegen_operand` compiles FnDefs to dummy structs.
// (cf. the function documentation)
self.codegen_func_expr(instance, None).address_of()
}
_ => unreachable!(),
},
PointerCast::UnsafeFnPointer => self.codegen_operand(operand),
PointerCast::ClosureFnPointer(_) => {
if let ty::Closure(def_id, substs) = self.operand_ty(operand).kind() {
let instance = Instance::resolve_closure(
self.tcx,
*def_id,
substs,
ty::ClosureKind::FnOnce,
)
.expect("failed to normalize and resolve closure during codegen")
.polymorphize(self.tcx);
self.codegen_func_expr(instance, None).address_of()
} else {
unreachable!("{:?} cannot be cast to a fn ptr", operand)
}
}
PointerCast::MutToConstPointer => self.codegen_operand(operand),
PointerCast::ArrayToPointer => {
// TODO: I am not sure whether it is correct or not.
//
// some reasoning is as follows.
// the trouble is to understand whether we have to handle fat pointers and my claim is no.
// if we had to, then [o] necessarily has type [T; n] where *T is a fat pointer, meaning
// T is either [T] or str. but neither type is sized, which shouldn't participate in
// codegen.
match self.operand_ty(operand).kind() {
ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
// ty must be an array
if let ty::Array(_, _) = ty.kind() {
let oe = self.codegen_operand(operand);
oe.dereference() // : struct [T; n]
.member("0", &self.symbol_table) // : T[n]
.array_to_ptr() // : T*
} else {
unreachable!()
}
}
_ => unreachable!(),
}
}
PointerCast::Unsize => {
let src_goto_expr = self.codegen_operand(operand);
let src_mir_type = self.operand_ty(operand);
let dst_mir_type = t;
self.codegen_unsized_cast(src_goto_expr, src_mir_type, dst_mir_type)
}
}
}
/// Generate code for unsized cast. This includes the following:
/// -> (Built-in / Smart) Pointer from array to slice.
/// -> (Built-in / Smart) Pointer from sized type to dyn trait.
/// -> (Built-in / Smart) Pointer from dyn trait to dyn trait.
/// - E.g.: `&(dyn Any + Send)` to `&dyn Any`.
/// -> All the cases above where the pointer refers to a parametrized struct where the type
/// parameter is the target of the unsize casting.
/// - E.g.: `RcBox<String>` to `RcBox<dyn Any>`
fn codegen_unsized_cast(
&mut self,
src_goto_expr: Expr,
src_mir_type: Ty<'tcx>,
dst_mir_type: Ty<'tcx>,
) -> Expr {
// The MIR may include casting that isn't necessary. Detect this early on and return the
// expression for the RHS.
if src_mir_type == dst_mir_type {
return src_goto_expr;
}
// Collect some information about the unsized coercion.
let mut path = self.collect_unsized_cast_path(src_goto_expr, src_mir_type, dst_mir_type);
debug!(cast=?path, "codegen_unsized_cast");
// Handle the leaf which should always be a pointer.
let (ptr_cast_info, ptr_src_expr) = path.pop().unwrap();
let initial_expr = self.codegen_cast_to_fat_pointer(ptr_src_expr, ptr_cast_info);
// Iterate from the back of the path initializing each struct that requires the coercion.
// This code is required for handling smart pointers.
path.into_iter().rfold(initial_expr, |coercion_expr, (info, src_expr)| {
self.codegen_struct_unsized_coercion(src_expr, info, coercion_expr)
})
}
/// Extract path that must be explicitly casted. Add to the tuple the expression type for
/// the current source.
fn collect_unsized_cast_path(
&self,
src_goto_expr: Expr,
src_mir_type: Ty<'tcx>,
dst_mir_type: Ty<'tcx>,
) -> Vec<(CoerceUnsizedInfo<'tcx>, Expr)> {
let mut field_type = src_goto_expr;
CoerceUnsizedIterator::new(self.tcx, src_mir_type, dst_mir_type)
.map(|info| {
let expr = if let Some(field_symbol) = info.field {
// Generate the expression for the current structure and save the type for
// the divergent field.
let field_name = field_symbol.as_str().intern();
let member_type = field_type.clone().member(field_name, &self.symbol_table);
std::mem::replace(&mut field_type, member_type)
} else {
// The end of our traverse. Generate the expression for the current type.
field_type.clone()
};
(info, expr)
})
.collect::<Vec<_>>()
}
/// Generate a struct resulting from an unsized coercion.
/// The resulting expression is basically a field by field assignment to from the
/// source expression, except for the field being coerced.
/// Coercion ignores phantom data structures, so do we.
/// See <https://github.com/rust-lang/rust/issues/26905> for more details.
fn codegen_struct_unsized_coercion(
&mut self,
src_expr: Expr,
info: CoerceUnsizedInfo<'tcx>,
member_coercion: Expr,
) -> Expr {
assert!(info.src_ty.is_adt(), "Expected struct. Found {:?}", info.src_ty);
assert!(info.dst_ty.is_adt(), "Expected struct. Found {:?}", info.dst_ty);
let dst_goto_type = self.codegen_ty(info.dst_ty);
let src_field_exprs = src_expr.struct_field_exprs(&self.symbol_table);
let dst_field_exprs = src_field_exprs
.into_iter()
.map(|(key, val)| {
let new_val = if info.field.unwrap().as_str().intern() == key {
// The type being coerced. Use the provided expression.
member_coercion.clone()
} else {
let dst_member_type =
dst_goto_type.lookup_field_type(key, &self.symbol_table).unwrap();
if &dst_member_type != val.typ() {
// Phantom data is ignored during a coercion, but it's type may still
// change. So we just recreate the empty struct.
assert_eq!(dst_member_type.sizeof(&self.symbol_table), 0);
Expr::struct_expr(dst_member_type, BTreeMap::new(), &self.symbol_table)
} else {
// No coercion is required. Just assign dst.field = src.field.
val
}
};
(key, new_val)
})
.collect();
let dst_expr = Expr::struct_expr(dst_goto_type, dst_field_exprs, &self.symbol_table);
debug!(?dst_expr, "codegen_struct_unsized_coercion");
dst_expr
}
fn codegen_vtable_method_field(
&mut self,
instance: Instance<'tcx>,
t: Ty<'tcx>,
idx: usize,
) -> Expr {
debug!(?instance, typ=?t, %idx, "codegen_vtable_method_field");
let vtable_field_name = self.vtable_field_name(instance.def_id(), idx);
let vtable_type = Type::struct_tag(self.vtable_name(t));
let field_type =
vtable_type.lookup_field_type(vtable_field_name, &self.symbol_table).unwrap();
debug!(?vtable_field_name, ?vtable_type, "codegen_vtable_method_field");
// Lookup in the symbol table using the full symbol table name/key
let fn_name = self.symbol_name(instance);
if let Some(fn_symbol) = self.symbol_table.lookup(&fn_name) {
if self.vtable_ctx.emit_vtable_restrictions {
// Add to the possible method names for this trait type
self.vtable_ctx.add_possible_method(
self.normalized_trait_name(t).into(),
idx,
fn_name.into(),
);
}
// Create a pointer to the method
// Note that the method takes a self* as the first argument, but the vtable field type has a void* as the first arg.
// So we need to cast it at the end.
debug!(?fn_symbol, fn_typ=?fn_symbol.typ, ?field_type, "codegen_vtable_method_field");
Expr::symbol_expression(fn_symbol.name, fn_symbol.typ.clone())
.address_of()
.cast_to(field_type)
} else {
warn!(
"Unable to find vtable symbol for virtual function {}, attempted lookup for symbol name: {}",
self.readable_instance_name(instance),
fn_name,
);
field_type.null()
}
}
/// Generate a function pointer to drop_in_place for entry into the vtable