-
Notifications
You must be signed in to change notification settings - Fork 61
/
builder.rs
2441 lines (2164 loc) · 96.1 KB
/
builder.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
use std::borrow::Cow;
use std::cell::Cell;
use std::convert::TryFrom;
use std::ops::Deref;
use gccjit::{
BinaryOp, Block, ComparisonOp, Context, Function, LValue, Location, RValue, ToRValue, Type,
UnaryOp,
};
use rustc_apfloat::{ieee, Float, Round, Status};
use rustc_codegen_ssa::common::{
AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope, TypeKind,
};
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
use rustc_codegen_ssa::mir::place::PlaceRef;
use rustc_codegen_ssa::traits::{
BackendTypes, BaseTypeMethods, BuilderMethods, ConstMethods, HasCodegen, LayoutTypeMethods,
OverflowOp, StaticBuilderMethods,
};
use rustc_codegen_ssa::MemFlags;
use rustc_data_structures::fx::FxHashSet;
use rustc_middle::bug;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
use rustc_middle::ty::layout::{
FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasParamEnv, HasTyCtxt, LayoutError, LayoutOfHelpers,
TyAndLayout,
};
use rustc_middle::ty::{Instance, ParamEnv, Ty, TyCtxt};
use rustc_span::def_id::DefId;
use rustc_span::Span;
use rustc_target::abi::call::FnAbi;
use rustc_target::abi::{self, Align, HasDataLayout, Size, TargetDataLayout, WrappingRange};
use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, Target, WasmCAbi};
use crate::common::{type_is_pointer, SignType, TypeReflection};
use crate::context::CodegenCx;
use crate::intrinsic::llvm;
use crate::type_of::LayoutGccExt;
// TODO(antoyo)
type Funclet = ();
enum ExtremumOperation {
Max,
Min,
}
pub struct Builder<'a: 'gcc, 'gcc, 'tcx> {
pub cx: &'a CodegenCx<'gcc, 'tcx>,
pub block: Block<'gcc>,
pub location: Option<Location<'gcc>>,
value_counter: Cell<u64>,
}
impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> {
fn with_cx(cx: &'a CodegenCx<'gcc, 'tcx>, block: Block<'gcc>) -> Self {
Builder { cx, block, location: None, value_counter: Cell::new(0) }
}
fn next_value_counter(&self) -> u64 {
self.value_counter.set(self.value_counter.get() + 1);
self.value_counter.get()
}
fn atomic_extremum(
&mut self,
operation: ExtremumOperation,
dst: RValue<'gcc>,
src: RValue<'gcc>,
order: AtomicOrdering,
) -> RValue<'gcc> {
let size = get_maybe_pointer_size(src);
let func = self.current_func();
let load_ordering = match order {
// TODO(antoyo): does this make sense?
AtomicOrdering::AcquireRelease | AtomicOrdering::Release => AtomicOrdering::Acquire,
_ => order,
};
let previous_value =
self.atomic_load(dst.get_type(), dst, load_ordering, Size::from_bytes(size));
let previous_var =
func.new_local(self.location, previous_value.get_type(), "previous_value");
let return_value = func.new_local(self.location, previous_value.get_type(), "return_value");
self.llbb().add_assignment(self.location, previous_var, previous_value);
self.llbb().add_assignment(self.location, return_value, previous_var.to_rvalue());
let while_block = func.new_block("while");
let after_block = func.new_block("after_while");
self.llbb().end_with_jump(self.location, while_block);
// NOTE: since jumps were added and compare_exchange doesn't expect this, the current block in the
// state need to be updated.
self.switch_to_block(while_block);
let comparison_operator = match operation {
ExtremumOperation::Max => ComparisonOp::LessThan,
ExtremumOperation::Min => ComparisonOp::GreaterThan,
};
let cond1 = self.context.new_comparison(
self.location,
comparison_operator,
previous_var.to_rvalue(),
self.context.new_cast(self.location, src, previous_value.get_type()),
);
let compare_exchange =
self.compare_exchange(dst, previous_var, src, order, load_ordering, false);
let cond2 = self.cx.context.new_unary_op(
self.location,
UnaryOp::LogicalNegate,
compare_exchange.get_type(),
compare_exchange,
);
let cond = self.cx.context.new_binary_op(
self.location,
BinaryOp::LogicalAnd,
self.cx.bool_type,
cond1,
cond2,
);
while_block.end_with_conditional(self.location, cond, while_block, after_block);
// NOTE: since jumps were added in a place rustc does not expect, the current block in the
// state need to be updated.
self.switch_to_block(after_block);
return_value.to_rvalue()
}
fn compare_exchange(
&self,
dst: RValue<'gcc>,
cmp: LValue<'gcc>,
src: RValue<'gcc>,
order: AtomicOrdering,
failure_order: AtomicOrdering,
weak: bool,
) -> RValue<'gcc> {
let size = get_maybe_pointer_size(src);
let compare_exchange =
self.context.get_builtin_function(format!("__atomic_compare_exchange_{}", size));
let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc());
let failure_order = self.context.new_rvalue_from_int(self.i32_type, failure_order.to_gcc());
let weak = self.context.new_rvalue_from_int(self.bool_type, weak as i32);
let void_ptr_type = self.context.new_type::<*mut ()>();
let volatile_void_ptr_type = void_ptr_type.make_volatile();
let dst = self.context.new_cast(self.location, dst, volatile_void_ptr_type);
let expected =
self.context.new_cast(self.location, cmp.get_address(self.location), void_ptr_type);
// NOTE: not sure why, but we have the wrong type here.
let int_type = compare_exchange.get_param(2).to_rvalue().get_type();
let src = self.context.new_bitcast(self.location, src, int_type);
self.context.new_call(
self.location,
compare_exchange,
&[dst, expected, src, weak, order, failure_order],
)
}
pub fn assign(&self, lvalue: LValue<'gcc>, value: RValue<'gcc>) {
self.llbb().add_assignment(self.location, lvalue, value);
}
fn check_call<'b>(
&mut self,
_typ: &str,
func: Function<'gcc>,
args: &'b [RValue<'gcc>],
) -> Cow<'b, [RValue<'gcc>]> {
let mut all_args_match = true;
let mut param_types = vec![];
let param_count = func.get_param_count();
for (index, arg) in args.iter().enumerate().take(param_count) {
let param = func.get_param(index as i32);
let param = param.to_rvalue().get_type();
if param != arg.get_type() {
all_args_match = false;
}
param_types.push(param);
}
if all_args_match {
return Cow::Borrowed(args);
}
let casted_args: Vec<_> = param_types
.into_iter()
.zip(args.iter())
.map(|(expected_ty, &actual_val)| {
let actual_ty = actual_val.get_type();
if expected_ty != actual_ty {
self.bitcast(actual_val, expected_ty)
} else {
actual_val
}
})
.collect();
debug_assert_eq!(casted_args.len(), args.len());
Cow::Owned(casted_args)
}
fn check_ptr_call<'b>(
&mut self,
_typ: &str,
func_ptr: RValue<'gcc>,
args: &'b [RValue<'gcc>],
) -> Cow<'b, [RValue<'gcc>]> {
let mut all_args_match = true;
let mut param_types = vec![];
let gcc_func = func_ptr.get_type().dyncast_function_ptr_type().expect("function ptr");
for (index, arg) in args.iter().enumerate().take(gcc_func.get_param_count()) {
let param = gcc_func.get_param_type(index);
if param != arg.get_type() {
all_args_match = false;
}
param_types.push(param);
}
let mut on_stack_param_indices = FxHashSet::default();
if let Some(indices) = self.on_stack_params.borrow().get(&gcc_func) {
on_stack_param_indices.clone_from(indices);
}
if all_args_match {
return Cow::Borrowed(args);
}
let func_name = format!("{:?}", func_ptr);
let mut casted_args: Vec<_> = param_types
.into_iter()
.zip(args.iter())
.enumerate()
.map(|(index, (expected_ty, &actual_val))| {
if llvm::ignore_arg_cast(&func_name, index, args.len()) {
return actual_val;
}
let actual_ty = actual_val.get_type();
if expected_ty != actual_ty {
if !actual_ty.is_vector()
&& !expected_ty.is_vector()
&& (actual_ty.is_integral() && expected_ty.is_integral())
|| (actual_ty.get_pointee().is_some()
&& expected_ty.get_pointee().is_some())
{
self.context.new_cast(self.location, actual_val, expected_ty)
} else if on_stack_param_indices.contains(&index) {
let ty = actual_val.get_type();
// It's possible that the value behind the pointer is actually not exactly
// the expected type, so to go around that, we add a cast before
// dereferencing the value.
if let Some(pointee_val) = ty.get_pointee()
&& pointee_val != expected_ty
{
let new_val = self.context.new_cast(
self.location,
actual_val,
expected_ty.make_pointer(),
);
new_val.dereference(self.location).to_rvalue()
} else {
actual_val.dereference(self.location).to_rvalue()
}
} else {
// FIXME: this condition seems wrong: it will pass when both types are not
// a vector.
assert!(
(!expected_ty.is_vector() || actual_ty.is_vector())
&& (expected_ty.is_vector() || !actual_ty.is_vector()),
"{:?} (is vector: {}) -> {:?} (is vector: {}), Function: {:?}[{}]",
actual_ty,
actual_ty.is_vector(),
expected_ty,
expected_ty.is_vector(),
func_ptr,
index
);
// TODO(antoyo): perhaps use __builtin_convertvector for vector casting.
// TODO: remove bitcast now that vector types can be compared?
// ==> We use bitcast to avoid having to do many manual casts from e.g. __m256i to __v32qi (in
// the case of _mm256_aesenc_epi128).
self.bitcast(actual_val, expected_ty)
}
} else {
actual_val
}
})
.collect();
// NOTE: to take into account variadic functions.
for arg in args.iter().skip(casted_args.len()) {
casted_args.push(*arg);
}
Cow::Owned(casted_args)
}
fn check_store(&mut self, val: RValue<'gcc>, ptr: RValue<'gcc>) -> RValue<'gcc> {
let stored_ty = self.cx.val_ty(val);
let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
self.bitcast(ptr, stored_ptr_ty)
}
pub fn current_func(&self) -> Function<'gcc> {
self.block.get_function()
}
fn function_call(
&mut self,
func: RValue<'gcc>,
args: &[RValue<'gcc>],
_funclet: Option<&Funclet>,
) -> RValue<'gcc> {
// TODO(antoyo): remove when the API supports a different type for functions.
let func: Function<'gcc> = self.cx.rvalue_as_function(func);
let args = self.check_call("call", func, args);
// gccjit requires to use the result of functions, even when it's not used.
// That's why we assign the result to a local or call add_eval().
let return_type = func.get_return_type();
let void_type = self.context.new_type::<()>();
let current_func = self.block.get_function();
if return_type != void_type {
let result = current_func.new_local(
self.location,
return_type,
format!("returnValue{}", self.next_value_counter()),
);
self.block.add_assignment(
self.location,
result,
self.cx.context.new_call(self.location, func, &args),
);
result.to_rvalue()
} else {
self.block
.add_eval(self.location, self.cx.context.new_call(self.location, func, &args));
// Return dummy value when not having return value.
self.context.new_rvalue_zero(self.isize_type)
}
}
fn function_ptr_call(
&mut self,
typ: Type<'gcc>,
mut func_ptr: RValue<'gcc>,
args: &[RValue<'gcc>],
_funclet: Option<&Funclet>,
) -> RValue<'gcc> {
let gcc_func = match func_ptr.get_type().dyncast_function_ptr_type() {
Some(func) => func,
None => {
// NOTE: due to opaque pointers now being used, we need to cast here.
let new_func_type = typ.dyncast_function_ptr_type().expect("function ptr");
func_ptr = self.context.new_cast(self.location, func_ptr, typ);
new_func_type
}
};
let func_name = format!("{:?}", func_ptr);
let previous_arg_count = args.len();
let orig_args = args;
let args = {
let function_address_names = self.function_address_names.borrow();
let original_function_name = function_address_names.get(&func_ptr);
func_ptr = llvm::adjust_function(self.context, &func_name, func_ptr, args);
llvm::adjust_intrinsic_arguments(
self,
gcc_func,
args.into(),
&func_name,
original_function_name,
)
};
let args_adjusted = args.len() != previous_arg_count;
let args = self.check_ptr_call("call", func_ptr, &args);
// gccjit requires to use the result of functions, even when it's not used.
// That's why we assign the result to a local or call add_eval().
let return_type = gcc_func.get_return_type();
let void_type = self.context.new_type::<()>();
let current_func = self.block.get_function();
if return_type != void_type {
let return_value = self.cx.context.new_call_through_ptr(self.location, func_ptr, &args);
let return_value = llvm::adjust_intrinsic_return_value(
self,
return_value,
&func_name,
&args,
args_adjusted,
orig_args,
);
let result = current_func.new_local(
self.location,
return_value.get_type(),
format!("ptrReturnValue{}", self.next_value_counter()),
);
self.block.add_assignment(self.location, result, return_value);
result.to_rvalue()
} else {
#[cfg(not(feature = "master"))]
if gcc_func.get_param_count() == 0 {
// FIXME(antoyo): As a temporary workaround for unsupported LLVM intrinsics.
self.block.add_eval(
self.location,
self.cx.context.new_call_through_ptr(self.location, func_ptr, &[]),
);
} else {
self.block.add_eval(
self.location,
self.cx.context.new_call_through_ptr(self.location, func_ptr, &args),
);
}
#[cfg(feature = "master")]
self.block.add_eval(
self.location,
self.cx.context.new_call_through_ptr(self.location, func_ptr, &args),
);
// Return dummy value when not having return value.
self.context.new_rvalue_zero(self.isize_type)
}
}
pub fn overflow_call(
&self,
func: Function<'gcc>,
args: &[RValue<'gcc>],
_funclet: Option<&Funclet>,
) -> RValue<'gcc> {
// gccjit requires to use the result of functions, even when it's not used.
// That's why we assign the result to a local.
let return_type = self.context.new_type::<bool>();
let current_func = self.block.get_function();
// TODO(antoyo): return the new_call() directly? Since the overflow function has no side-effects.
let result = current_func.new_local(
self.location,
return_type,
format!("overflowReturnValue{}", self.next_value_counter()),
);
self.block.add_assignment(
self.location,
result,
self.cx.context.new_call(self.location, func, args),
);
result.to_rvalue()
}
}
impl<'gcc, 'tcx> HasCodegen<'tcx> for Builder<'_, 'gcc, 'tcx> {
type CodegenCx = CodegenCx<'gcc, 'tcx>;
}
impl<'tcx> HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.cx.tcx()
}
}
impl HasDataLayout for Builder<'_, '_, '_> {
fn data_layout(&self) -> &TargetDataLayout {
self.cx.data_layout()
}
}
impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
type LayoutOfResult = TyAndLayout<'tcx>;
#[inline]
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
self.cx.handle_layout_err(err, span, ty)
}
}
impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
#[inline]
fn handle_fn_abi_err(
&self,
err: FnAbiError<'tcx>,
span: Span,
fn_abi_request: FnAbiRequest<'tcx>,
) -> ! {
self.cx.handle_fn_abi_err(err, span, fn_abi_request)
}
}
impl<'a, 'gcc, 'tcx> Deref for Builder<'a, 'gcc, 'tcx> {
type Target = CodegenCx<'gcc, 'tcx>;
fn deref<'b>(&'b self) -> &'a Self::Target {
self.cx
}
}
impl<'gcc, 'tcx> BackendTypes for Builder<'_, 'gcc, 'tcx> {
type Value = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Value;
type Function = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Function;
type BasicBlock = <CodegenCx<'gcc, 'tcx> as BackendTypes>::BasicBlock;
type Type = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Type;
type Funclet = <CodegenCx<'gcc, 'tcx> as BackendTypes>::Funclet;
type DIScope = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DIScope;
type DILocation = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DILocation;
type DIVariable = <CodegenCx<'gcc, 'tcx> as BackendTypes>::DIVariable;
}
fn set_rvalue_location<'a, 'gcc, 'tcx>(
bx: &mut Builder<'a, 'gcc, 'tcx>,
rvalue: RValue<'gcc>,
) -> RValue<'gcc> {
if bx.location.is_some() {
#[cfg(feature = "master")]
rvalue.set_location(bx.location.unwrap());
}
rvalue
}
impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
fn build(cx: &'a CodegenCx<'gcc, 'tcx>, block: Block<'gcc>) -> Builder<'a, 'gcc, 'tcx> {
Builder::with_cx(cx, block)
}
fn llbb(&self) -> Block<'gcc> {
self.block
}
fn append_block(cx: &'a CodegenCx<'gcc, 'tcx>, func: RValue<'gcc>, name: &str) -> Block<'gcc> {
let func = cx.rvalue_as_function(func);
func.new_block(name)
}
fn append_sibling_block(&mut self, name: &str) -> Block<'gcc> {
let func = self.current_func();
func.new_block(name)
}
fn switch_to_block(&mut self, block: Self::BasicBlock) {
self.block = block;
}
fn ret_void(&mut self) {
self.llbb().end_with_void_return(self.location)
}
fn ret(&mut self, mut value: RValue<'gcc>) {
if self.structs_as_pointer.borrow().contains(&value) {
// NOTE: hack to workaround a limitation of the rustc API: see comment on
// CodegenCx.structs_as_pointer
value = value.dereference(self.location).to_rvalue();
}
let expected_return_type = self.current_func().get_return_type();
if !expected_return_type.is_compatible_with(value.get_type()) {
// NOTE: due to opaque pointers now being used, we need to cast here.
value = self.context.new_cast(self.location, value, expected_return_type);
}
self.llbb().end_with_return(self.location, value);
}
fn br(&mut self, dest: Block<'gcc>) {
self.llbb().end_with_jump(self.location, dest)
}
fn cond_br(&mut self, cond: RValue<'gcc>, then_block: Block<'gcc>, else_block: Block<'gcc>) {
self.llbb().end_with_conditional(self.location, cond, then_block, else_block)
}
fn switch(
&mut self,
value: RValue<'gcc>,
default_block: Block<'gcc>,
cases: impl ExactSizeIterator<Item = (u128, Block<'gcc>)>,
) {
let mut gcc_cases = vec![];
let typ = self.val_ty(value);
for (on_val, dest) in cases {
let on_val = self.const_uint_big(typ, on_val);
gcc_cases.push(self.context.new_case(on_val, on_val, dest));
}
self.block.end_with_switch(self.location, value, default_block, &gcc_cases);
}
#[cfg(feature = "master")]
fn invoke(
&mut self,
typ: Type<'gcc>,
fn_attrs: Option<&CodegenFnAttrs>,
_fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
func: RValue<'gcc>,
args: &[RValue<'gcc>],
then: Block<'gcc>,
catch: Block<'gcc>,
_funclet: Option<&Funclet>,
instance: Option<Instance<'tcx>>,
) -> RValue<'gcc> {
let try_block = self.current_func().new_block("try");
let current_block = self.block;
self.block = try_block;
let call = self.call(typ, fn_attrs, None, func, args, None, instance); // TODO(antoyo): use funclet here?
self.block = current_block;
let return_value =
self.current_func().new_local(self.location, call.get_type(), "invokeResult");
try_block.add_assignment(self.location, return_value, call);
try_block.end_with_jump(self.location, then);
if self.cleanup_blocks.borrow().contains(&catch) {
self.block.add_try_finally(self.location, try_block, catch);
} else {
self.block.add_try_catch(self.location, try_block, catch);
}
self.block.end_with_jump(self.location, then);
return_value.to_rvalue()
}
#[cfg(not(feature = "master"))]
fn invoke(
&mut self,
typ: Type<'gcc>,
fn_attrs: Option<&CodegenFnAttrs>,
fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
func: RValue<'gcc>,
args: &[RValue<'gcc>],
then: Block<'gcc>,
catch: Block<'gcc>,
_funclet: Option<&Funclet>,
instance: Option<Instance<'tcx>>,
) -> RValue<'gcc> {
let call_site = self.call(typ, fn_attrs, None, func, args, None, instance);
let condition = self.context.new_rvalue_from_int(self.bool_type, 1);
self.llbb().end_with_conditional(self.location, condition, then, catch);
if let Some(_fn_abi) = fn_abi {
// TODO(bjorn3): Apply function attributes
}
call_site
}
fn unreachable(&mut self) {
let func = self.context.get_builtin_function("__builtin_unreachable");
self.block.add_eval(self.location, self.context.new_call(self.location, func, &[]));
let return_type = self.block.get_function().get_return_type();
let void_type = self.context.new_type::<()>();
if return_type == void_type {
self.block.end_with_void_return(self.location)
} else {
let return_value =
self.current_func().new_local(self.location, return_type, "unreachableReturn");
self.block.end_with_return(self.location, return_value)
}
}
fn add(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_add(a, b)
}
fn fadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
a + b
}
fn sub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_sub(a, b)
}
fn fsub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
a - b
}
fn mul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_mul(a, b)
}
fn fmul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.cx.context.new_binary_op(self.location, BinaryOp::Mult, a.get_type(), a, b)
}
fn udiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_udiv(a, b)
}
fn exactudiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
// TODO(antoyo): poison if not exact.
let a_type = a.get_type().to_unsigned(self);
let a = self.gcc_int_cast(a, a_type);
let b_type = b.get_type().to_unsigned(self);
let b = self.gcc_int_cast(b, b_type);
a / b
}
fn sdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_sdiv(a, b)
}
fn exactsdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
// TODO(antoyo): poison if not exact.
// FIXME(antoyo): rustc_codegen_ssa::mir::intrinsic uses different types for a and b but they
// should be the same.
let typ = a.get_type().to_signed(self);
let b = self.context.new_cast(self.location, b, typ);
a / b
}
fn fdiv(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
a / b
}
fn urem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_urem(a, b)
}
fn srem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_srem(a, b)
}
fn frem(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
// TODO(antoyo): add check in libgccjit since using the binary operator % causes the following error:
// during RTL pass: expand
// libgccjit.so: error: in expmed_mode_index, at expmed.h:240
// 0x7f0101d58dc6 expmed_mode_index
// ../../../gcc/gcc/expmed.h:240
// 0x7f0101d58e35 expmed_op_cost_ptr
// ../../../gcc/gcc/expmed.h:262
// 0x7f0101d594a1 sdiv_cost_ptr
// ../../../gcc/gcc/expmed.h:531
// 0x7f0101d594f3 sdiv_cost
// ../../../gcc/gcc/expmed.h:549
// 0x7f0101d6af7e expand_divmod(int, tree_code, machine_mode, rtx_def*, rtx_def*, rtx_def*, int, optab_methods)
// ../../../gcc/gcc/expmed.cc:4356
// 0x7f0101d94f9e expand_expr_divmod
// ../../../gcc/gcc/expr.cc:8929
// 0x7f0101d97a26 expand_expr_real_2(separate_ops*, rtx_def*, machine_mode, expand_modifier)
// ../../../gcc/gcc/expr.cc:9566
// 0x7f0101bef6ef expand_gimple_stmt_1
// ../../../gcc/gcc/cfgexpand.cc:3967
// 0x7f0101bef910 expand_gimple_stmt
// ../../../gcc/gcc/cfgexpand.cc:4028
// 0x7f0101bf6ee7 expand_gimple_basic_block
// ../../../gcc/gcc/cfgexpand.cc:6069
// 0x7f0101bf9194 execute
// ../../../gcc/gcc/cfgexpand.cc:6795
let a_type = a.get_type();
let a_type_unqualified = a_type.unqualified();
if a_type.is_compatible_with(self.cx.float_type) {
let fmodf = self.context.get_builtin_function("fmodf");
// FIXME(antoyo): this seems to produce the wrong result.
return self.context.new_call(self.location, fmodf, &[a, b]);
}
#[cfg(feature = "master")]
match self.cx.type_kind(a_type) {
TypeKind::Half | TypeKind::Float => {
let fmodf = self.context.get_builtin_function("fmodf");
return self.context.new_call(self.location, fmodf, &[a, b]);
}
TypeKind::Double => {
let fmod = self.context.get_builtin_function("fmod");
return self.context.new_call(self.location, fmod, &[a, b]);
}
TypeKind::FP128 => {
let fmodl = self.context.get_builtin_function("fmodl");
return self.context.new_call(self.location, fmodl, &[a, b]);
}
_ => (),
}
if let Some(vector_type) = a_type_unqualified.dyncast_vector() {
assert_eq!(a_type_unqualified, b.get_type().unqualified());
let num_units = vector_type.get_num_units();
let new_elements: Vec<_> = (0..num_units)
.map(|i| {
let index = self.context.new_rvalue_from_long(self.cx.type_u32(), i as _);
let x = self.extract_element(a, index).to_rvalue();
let y = self.extract_element(b, index).to_rvalue();
self.frem(x, y)
})
.collect();
return self.context.new_rvalue_from_vector(self.location, a_type, &new_elements);
}
assert_eq!(a_type_unqualified, self.cx.double_type);
let fmod = self.context.get_builtin_function("fmod");
self.context.new_call(self.location, fmod, &[a, b])
}
fn shl(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_shl(a, b)
}
fn lshr(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_lshr(a, b)
}
fn ashr(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
// TODO(antoyo): check whether behavior is an arithmetic shift for >> .
// It seems to be if the value is signed.
self.gcc_lshr(a, b)
}
fn and(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.gcc_and(a, b)
}
fn or(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
self.cx.gcc_or(a, b, self.location)
}
fn xor(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_xor(a, b))
}
fn neg(&mut self, a: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_neg(a))
}
fn fneg(&mut self, a: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(
self,
self.cx.context.new_unary_op(self.location, UnaryOp::Minus, a.get_type(), a),
)
}
fn not(&mut self, a: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_not(a))
}
fn unchecked_sadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_add(a, b))
}
fn unchecked_uadd(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_add(a, b))
}
fn unchecked_ssub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_sub(a, b))
}
fn unchecked_usub(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
// TODO(antoyo): should generate poison value?
set_rvalue_location(self, self.gcc_sub(a, b))
}
fn unchecked_smul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_mul(a, b))
}
fn unchecked_umul(&mut self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> {
set_rvalue_location(self, self.gcc_mul(a, b))
}
fn fadd_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
set_rvalue_location(self, lhs + rhs)
}
fn fsub_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
set_rvalue_location(self, lhs - rhs)
}
fn fmul_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
set_rvalue_location(self, lhs * rhs)
}
fn fdiv_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
set_rvalue_location(self, lhs / rhs)
}
fn frem_fast(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
let result = self.frem(lhs, rhs);
set_rvalue_location(self, result);
result
}
fn fadd_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs + rhs
}
fn fsub_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs - rhs
}
fn fmul_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs * rhs
}
fn fdiv_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs / rhs
}
fn frem_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
self.frem(lhs, rhs)
}
fn checked_binop(
&mut self,
oop: OverflowOp,
typ: Ty<'_>,
lhs: Self::Value,
rhs: Self::Value,
) -> (Self::Value, Self::Value) {
self.gcc_checked_binop(oop, typ, lhs, rhs)
}
fn alloca(&mut self, size: Size, align: Align) -> RValue<'gcc> {
let ty = self.cx.type_array(self.cx.type_i8(), size.bytes()).get_aligned(align.bytes());
// TODO(antoyo): It might be better to return a LValue, but fixing the rustc API is non-trivial.
self.current_func()
.new_local(self.location, ty, format!("stack_var_{}", self.next_value_counter()))
.get_address(self.location)
}
fn dynamic_alloca(&mut self, _len: RValue<'gcc>, _align: Align) -> RValue<'gcc> {
unimplemented!();
}
fn load(&mut self, pointee_ty: Type<'gcc>, ptr: RValue<'gcc>, align: Align) -> RValue<'gcc> {
let block = self.llbb();
let function = block.get_function();
// NOTE: instead of returning the dereference here, we have to assign it to a variable in
// the current basic block. Otherwise, it could be used in another basic block, causing a
// dereference after a drop, for instance.
// FIXME(antoyo): this check that we don't call get_aligned() a second time on a type.
// Ideally, we shouldn't need to do this check.
let aligned_type = if pointee_ty == self.cx.u128_type || pointee_ty == self.cx.i128_type {
pointee_ty
} else {
pointee_ty.get_aligned(align.bytes())
};
let ptr = self.context.new_cast(self.location, ptr, aligned_type.make_pointer());
let deref = ptr.dereference(self.location).to_rvalue();
let loaded_value = function.new_local(
self.location,
aligned_type,
format!("loadedValue{}", self.next_value_counter()),
);
block.add_assignment(self.location, loaded_value, deref);
loaded_value.to_rvalue()
}
fn volatile_load(&mut self, ty: Type<'gcc>, ptr: RValue<'gcc>) -> RValue<'gcc> {
let ptr = self.context.new_cast(self.location, ptr, ty.make_volatile().make_pointer());
ptr.dereference(self.location).to_rvalue()
}
fn atomic_load(
&mut self,
_ty: Type<'gcc>,
ptr: RValue<'gcc>,
order: AtomicOrdering,
size: Size,
) -> RValue<'gcc> {
// TODO(antoyo): use ty.
// TODO(antoyo): handle alignment.
let atomic_load =
self.context.get_builtin_function(format!("__atomic_load_{}", size.bytes()));
let ordering = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc());
let volatile_const_void_ptr_type =
self.context.new_type::<()>().make_const().make_volatile().make_pointer();
let ptr = self.context.new_cast(self.location, ptr, volatile_const_void_ptr_type);
self.context.new_call(self.location, atomic_load, &[ptr, ordering])
}
fn load_operand(
&mut self,
place: PlaceRef<'tcx, RValue<'gcc>>,
) -> OperandRef<'tcx, RValue<'gcc>> {
assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
if place.layout.is_zst() {
return OperandRef::zero_sized(place.layout);
}
fn scalar_load_metadata<'a, 'gcc, 'tcx>(
bx: &mut Builder<'a, 'gcc, 'tcx>,
load: RValue<'gcc>,
scalar: &abi::Scalar,