-
Notifications
You must be signed in to change notification settings - Fork 9
/
codegen.rs
1384 lines (1303 loc) · 50.6 KB
/
codegen.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::collections::HashMap;
use concrete_ir::{
BinOp, ConstValue, DefId, FnBody, LocalKind, ModuleBody, Operand, Place, PlaceElem,
ProgramBody, Rvalue, Span, Ty, TyKind, ValueTree,
};
use concrete_session::Session;
use melior::{
dialect::{
arith, cf, func,
llvm::{self, r#type::pointer, AllocaOptions, LoadStoreOptions},
ods,
},
ir::{
attribute::{
DenseI32ArrayAttribute, FlatSymbolRefAttribute, FloatAttribute, IntegerAttribute,
StringAttribute, TypeAttribute,
},
r#type::{FunctionType, IntegerType},
Attribute, Block, Identifier, Location, Module as MeliorModule, Region, Type, Value,
ValueLike,
},
Context as MeliorContext,
};
use crate::errors::CodegenError;
/// Global codegen context
#[derive(Debug, Clone, Copy)]
pub(crate) struct CodegenCtx<'a> {
/// The MLIR context.
pub mlir_context: &'a MeliorContext,
/// The MLIR module.
pub mlir_module: &'a MeliorModule<'a>,
/// The compile session info.
pub session: &'a Session,
/// The program IR.
pub program: &'a ProgramBody,
}
/// Codegen context for a module
#[derive(Debug, Clone, Copy)]
struct ModuleCodegenCtx<'a> {
pub ctx: CodegenCtx<'a>,
/// The id of the module.
pub module_id: DefId,
}
impl<'a> ModuleCodegenCtx<'a> {
/// Gets the module IR body.
pub fn get_module_body(&self) -> &ModuleBody {
self.ctx
.program
.modules
.get(&self.module_id)
.expect("module should exist")
}
/// Gets a MLIR location from the given span, or unknown if the span is `None`.
pub fn get_location(&self, span: Option<Span>) -> Location {
if let Some(span) = span {
let (_, line, col) = self.ctx.session.sources[self.module_id.program_id]
.get_offset_line(span.from)
.unwrap();
Location::new(
self.ctx.mlir_context,
self.ctx.program.file_paths[&self.module_id.program_id]
.file_name()
.unwrap()
.to_str()
.unwrap(),
line + 1,
col + 1,
)
} else {
Location::unknown(self.ctx.mlir_context)
}
}
}
/// Compiles the program within the context.
pub(crate) fn compile_program(ctx: CodegenCtx) -> Result<(), CodegenError> {
for module_id in &ctx.program.top_level_modules {
let ctx = ModuleCodegenCtx {
ctx,
module_id: *module_id,
};
compile_module(ctx)?;
}
Ok(())
}
/// Compiles the given module within the context.
fn compile_module(ctx: ModuleCodegenCtx) -> Result<(), CodegenError> {
let body = ctx.get_module_body();
for fn_id in body.functions.iter() {
let ctx = FunctionCodegenCtx {
module_ctx: ctx,
function_id: *fn_id,
};
compile_function(ctx)?;
}
for mod_id in body.modules.iter() {
let mut sub_ctx = ctx;
sub_ctx.module_id = *mod_id;
compile_module(sub_ctx)?;
}
Ok(())
}
/// Context used when compiling code within a function body.
#[derive(Debug, Clone, Copy)]
struct FunctionCodegenCtx<'a> {
pub module_ctx: ModuleCodegenCtx<'a>,
pub function_id: DefId,
}
impl<'a> FunctionCodegenCtx<'a> {
/// Gets the function IR body.
pub fn get_fn_body(&self) -> &FnBody {
self.module_ctx
.ctx
.program
.functions
.get(&self.function_id)
.expect("function body should exist")
}
/// Gets the function argument types and return type.
pub fn get_fn_signature(&self) -> &(Vec<Ty>, Ty) {
self.module_ctx
.ctx
.program
.function_signatures
.get(&self.function_id)
.expect("function body should exist")
}
pub fn context(&self) -> &MeliorContext {
self.module_ctx.ctx.mlir_context
}
}
/// Compiles the given function IR.
fn compile_function(ctx: FunctionCodegenCtx) -> Result<(), CodegenError> {
let body = ctx.get_fn_body();
let body_signature = ctx.get_fn_signature();
// Functions only have 1 region with multiple blocks within.
let region = Region::new();
// Compile the parameter types.
let params_ty: Vec<_> = body_signature
.0
.iter()
.map(|x| {
(
compile_type(ctx.module_ctx, x),
ctx.module_ctx.get_location(x.span),
)
})
.collect();
if !body.is_extern {
// The entry block doesn't exist in the IR, its where we create all the stack allocations for the locals.
let entry_block = region.append_block(Block::new(¶ms_ty));
let mut locals = HashMap::new();
// Store the return local index for easier use.
let mut return_local = None;
// Keep track of the parameter index so we can get it from the block argument.
// Since all the locals are together in a unspecified order in the IR.
let mut param_index = 0;
let location = Location::unknown(ctx.context());
let const1 = entry_block
.append_operation(arith::constant(
ctx.context(),
IntegerAttribute::new(IntegerType::new(ctx.context(), 64).into(), 1).into(),
location,
))
.result(0)?
.into();
for (index, local) in body.locals.iter().enumerate() {
// Get the MLIR local type.
let local_mlir_type = compile_type(ctx.module_ctx, &local.ty);
match local.kind {
// User-declared variable binding or compiler-introduced temporary.
LocalKind::Temp => {
let ptr: Value = entry_block
.append_operation(llvm::alloca(
ctx.context(),
const1,
pointer(ctx.context(), 0),
location,
AllocaOptions::new()
.elem_type(Some(TypeAttribute::new(local_mlir_type))),
))
.result(0)?
.into();
locals.insert(index, ptr);
}
// Argument local.
LocalKind::Arg => {
let arg_value: Value = entry_block.argument(param_index)?.into();
param_index += 1;
let ptr: Value = entry_block
.append_operation(llvm::alloca(
ctx.context(),
const1,
pointer(ctx.context(), 0),
location,
AllocaOptions::new()
.elem_type(Some(TypeAttribute::new(local_mlir_type))),
))
.result(0)?
.into();
entry_block.append_operation(llvm::store(
ctx.context(),
arg_value,
ptr,
location,
LoadStoreOptions::default(),
));
locals.insert(index, ptr);
}
// Return pointer.
LocalKind::ReturnPointer => {
if let TyKind::Unit = local.ty.kind {
} else {
return_local = Some(index);
let ptr: Value = entry_block
.append_operation(llvm::alloca(
ctx.context(),
const1,
pointer(ctx.context(), 0),
location,
AllocaOptions::new()
.elem_type(Some(TypeAttribute::new(local_mlir_type))),
))
.result(0)?
.into();
locals.insert(index, ptr);
}
}
}
}
// Create in advance all the needed blocks, 1 block per IR block.
// Since we use stack allocas we don't need to handle block arguments within.
// The optimizer takes care of deciding if this allocas are better kept in the stack or in a register
// based on register allocation and whether the address of the allocas is used somewhere.
// Since register variables can't have their address taken.
let mut blocks = Vec::with_capacity(body.basic_blocks.len());
for _ in body.basic_blocks.iter() {
let mlir_block = region.append_block(Block::new(&[]));
blocks.push(mlir_block);
}
// Jump from the entry block to the first IR block.
entry_block.append_operation(cf::br(&blocks[0], &[], Location::unknown(ctx.context())));
// Process each block.
for (block, mlir_block) in body.basic_blocks.iter().zip(blocks.iter()) {
// Within blocks there is no control flow, so we simply give the current block to the
// codegen functions.
for statement in &block.statements {
match &statement.kind {
concrete_ir::StatementKind::Assign(place, rvalue) => {
let (value, _ty) = compile_rvalue(&ctx, mlir_block, rvalue, &locals)?;
compile_store_place(&ctx, mlir_block, place, value, &locals)?;
}
concrete_ir::StatementKind::StorageLive(_) => {}
concrete_ir::StatementKind::StorageDead(_) => {}
}
}
// Jump based on the terminator.
match &block.terminator.kind {
concrete_ir::TerminatorKind::Goto { target } => {
mlir_block.append_operation(cf::br(
&blocks[*target],
&[],
Location::unknown(ctx.context()),
));
}
concrete_ir::TerminatorKind::Return => {
// Load the return value from the return local and return it.
if let Some(ret_local) = return_local {
let ptr = locals.get(&ret_local).unwrap();
let value = mlir_block
.append_operation(llvm::load(
ctx.context(),
*ptr,
compile_type(ctx.module_ctx, &body.locals[ret_local].ty),
Location::unknown(ctx.context()),
LoadStoreOptions::default(),
))
.result(0)?
.into();
mlir_block.append_operation(func::r#return(
&[value],
Location::unknown(ctx.context()),
));
} else {
mlir_block.append_operation(func::r#return(
&[],
Location::unknown(ctx.context()),
));
}
}
concrete_ir::TerminatorKind::Unreachable => {
mlir_block
.append_operation(llvm::unreachable(Location::unknown(ctx.context())));
}
// Function calls are terminators because a function may be diverging (i.e it doesn't return).
concrete_ir::TerminatorKind::Call {
func,
args,
destination,
target,
} => {
let target_fn_body = ctx.module_ctx.ctx.program.functions.get(func).unwrap();
let target_fn_body_sig = ctx
.module_ctx
.ctx
.program
.function_signatures
.get(func)
.unwrap();
let args: Vec<Value> = args
.iter()
.map(|x| compile_rvalue(&ctx, mlir_block, x, &locals).map(|x| x.0))
.collect::<Result<_, _>>()?;
let fn_symbol = FlatSymbolRefAttribute::new(
ctx.context(),
&target_fn_body.get_mangled_name(),
);
let ret_type = match &target_fn_body_sig.1.kind {
TyKind::Unit => None,
_ => Some(compile_type(ctx.module_ctx, &target_fn_body_sig.1)),
};
let result = mlir_block.append_operation(func::call(
ctx.context(),
fn_symbol,
&args,
ret_type.as_slice(),
Location::unknown(ctx.context()),
));
if result.result_count() > 0 {
compile_store_place(
&ctx,
mlir_block,
destination,
result.result(0)?.into(),
&locals,
)?;
}
if let Some(target) = target {
mlir_block.append_operation(cf::br(
&blocks[*target],
&[],
Location::unknown(ctx.context()),
));
} else {
mlir_block
.append_operation(llvm::unreachable(Location::unknown(ctx.context())));
}
}
// A switch int is used for branching by matching against 1 or multiple values.
concrete_ir::TerminatorKind::SwitchInt {
discriminator,
targets,
} => {
let (condition, _condition_ty) =
compile_load_operand(&ctx, mlir_block, discriminator, &locals)?;
// Case constant values to match against.
let mut case_values = Vec::new();
// MLIR detail to tell how many arguments we pass, since it can take a dynamic amount of arguments.
let mut cases_operands_count = Vec::new();
// The block destinations.
let mut dests: Vec<(&Block, _)> = Vec::new();
cases_operands_count.push(0);
for (value, target) in targets.values.iter().zip(targets.targets.iter()) {
let target = *target;
let block = &blocks[target];
let value = value_tree_to_int(value)
.expect("constant value can't be converted to int");
case_values.push(value);
cases_operands_count.push(1);
dests.push((block, [].as_slice()));
}
mlir_block.append_operation(cf::switch(
ctx.context(),
&case_values,
condition,
condition.r#type(),
// Default dest block
(&blocks[*targets.targets.last().unwrap()], &[]),
// Destinations
&dests,
Location::unknown(ctx.context()),
)?);
}
}
}
}
let param_types: Vec<_> = params_ty.iter().map(|x| x.0).collect();
// If the return type is unit, pass a empty slice to mlir.
let return_type = match &body_signature.1.kind {
TyKind::Unit => None,
_ => Some(compile_type(ctx.module_ctx, &body_signature.1)),
};
// Create the function mlir attribute.
let func_type = FunctionType::new(ctx.context(), ¶m_types, return_type.as_slice());
let mut fn_attributes = vec![];
if body.is_extern {
// extern declared functions need private visibility
fn_attributes.push((
Identifier::new(ctx.context(), "sym_visibility"),
StringAttribute::new(ctx.context(), "private").into(),
));
}
let func_op = func::func(
ctx.context(),
StringAttribute::new(ctx.context(), &body.get_mangled_name()),
TypeAttribute::new(func_type.into()),
region,
&fn_attributes,
Location::unknown(ctx.context()),
);
ctx.module_ctx
.ctx
.mlir_module
.body()
.append_operation(func_op);
Ok(())
}
/// Compiles a rvalue.
fn compile_rvalue<'c: 'b, 'b>(
ctx: &'c FunctionCodegenCtx,
block: &'b Block<'c>,
info: &Rvalue,
locals: &'b HashMap<usize, Value<'c, '_>>,
) -> Result<(Value<'c, 'b>, Ty), CodegenError> {
Ok(match info {
Rvalue::Use(info) => compile_load_operand(ctx, block, info, locals)?,
Rvalue::LogicOp(_, _) => todo!(),
Rvalue::BinaryOp(op, (lhs, rhs)) => compile_binop(ctx, block, op, lhs, rhs, locals)?,
Rvalue::UnaryOp(_, _) => todo!(),
Rvalue::Ref(_mutability, place) => {
let mut value = locals[&place.local];
let mut local_ty = ctx.get_fn_body().locals[place.local].ty.clone();
// Handle the projection.
for projection in &place.projection {
match projection {
PlaceElem::Deref => {
local_ty = match local_ty.kind {
TyKind::Ref(inner, _) => *(inner.clone()),
TyKind::Ptr(inner, _) => *(inner.clone()),
_ => unreachable!(),
};
value = block
.append_operation(llvm::load(
ctx.context(),
value,
compile_type(ctx.module_ctx, &local_ty),
Location::unknown(ctx.context()),
LoadStoreOptions::default(),
))
.result(0)?
.into();
}
PlaceElem::Field(_) => todo!(),
PlaceElem::Index(_) => todo!(),
PlaceElem::ConstantIndex(_) => todo!(),
}
}
(value, local_ty)
}
Rvalue::Cast(op, target_ty, _span) => {
let location = Location::unknown(ctx.context());
let target_ty = target_ty.clone();
let target_mlir_ty = compile_type(ctx.module_ctx, &target_ty);
let (value, current_ty) = compile_load_operand(ctx, block, op, locals)?;
let is_signed = target_ty.kind.is_signed();
if target_ty.kind.is_ptr_like() {
// int to ptr
if current_ty.kind.is_int() {
let value = block
.append_operation(
ods::llvm::inttoptr(ctx.context(), target_mlir_ty, value, location)
.into(),
)
.result(0)?
.into();
(value, target_ty.clone())
} else if current_ty.kind.is_ptr_like() {
// ptr to ptr: noop
(value, target_ty.clone())
} else {
unreachable!("cast from {:?} to ptr", current_ty.kind)
}
} else if target_ty.kind.is_int() {
if current_ty.kind.is_int() {
// int to int casts
match current_ty
.kind
.get_bit_width()
.unwrap()
.cmp(&target_ty.kind.get_bit_width().unwrap())
{
std::cmp::Ordering::Less => {
if is_signed {
let value = block
.append_operation(arith::extsi(value, target_mlir_ty, location))
.result(0)?
.into();
(value, target_ty.clone())
} else {
let value = block
.append_operation(arith::extui(value, target_mlir_ty, location))
.result(0)?
.into();
(value, target_ty.clone())
}
}
std::cmp::Ordering::Equal => (value, target_ty.clone()),
std::cmp::Ordering::Greater => {
let value = block
.append_operation(arith::trunci(value, target_mlir_ty, location))
.result(0)?
.into();
(value, target_ty.clone())
}
}
} else if current_ty.kind.is_float() {
// float to int
if is_signed {
let value = block
.append_operation(arith::fptosi(value, target_mlir_ty, location))
.result(0)?
.into();
(value, target_ty.clone())
} else {
let value = block
.append_operation(arith::fptoui(value, target_mlir_ty, location))
.result(0)?
.into();
(value, target_ty.clone())
}
} else if current_ty.kind.is_ptr_like() {
// ptr to int
let value = block
.append_operation(
ods::llvm::ptrtoint(ctx.context(), target_mlir_ty, value, location)
.into(),
)
.result(0)?
.into();
(value, target_ty.clone())
} else {
todo!("cast from {:?} to {:?}", current_ty, target_ty)
}
} else {
todo!("cast from {:?} to {:?}", current_ty, target_ty)
}
}
})
}
/// Compiles a binary operation.
fn compile_binop<'c: 'b, 'b>(
ctx: &'c FunctionCodegenCtx,
block: &'b Block<'c>,
op: &BinOp,
lhs: &Operand,
rhs: &Operand,
locals: &HashMap<usize, Value<'c, '_>>,
) -> Result<(Value<'c, 'b>, Ty), CodegenError> {
let (lhs, lhs_ty) = compile_load_operand(ctx, block, lhs, locals)?;
let (rhs, _rhs_ty) = compile_load_operand(ctx, block, rhs, locals)?;
let location = Location::unknown(ctx.context());
let is_float = matches!(lhs_ty.kind, TyKind::Float(_));
let is_signed = matches!(lhs_ty.kind, TyKind::Int(_));
Ok(match op {
BinOp::Add => {
let value = if is_float {
block
.append_operation(arith::addf(lhs, rhs, location))
.result(0)?
.into()
} else {
block
.append_operation(arith::addi(lhs, rhs, location))
.result(0)?
.into()
};
(value, lhs_ty)
}
BinOp::Sub => {
let value = if is_float {
block
.append_operation(arith::subf(lhs, rhs, location))
.result(0)?
.into()
} else {
block
.append_operation(arith::subi(lhs, rhs, location))
.result(0)?
.into()
};
(value, lhs_ty)
}
BinOp::Mul => {
let value = if is_float {
block
.append_operation(arith::mulf(lhs, rhs, location))
.result(0)?
.into()
} else {
block
.append_operation(arith::muli(lhs, rhs, location))
.result(0)?
.into()
};
(value, lhs_ty)
}
BinOp::Div => {
let value = if is_float {
block
.append_operation(arith::divf(lhs, rhs, location))
.result(0)?
.into()
} else if is_signed {
block
.append_operation(arith::divsi(lhs, rhs, location))
.result(0)?
.into()
} else {
block
.append_operation(arith::divui(lhs, rhs, location))
.result(0)?
.into()
};
(value, lhs_ty)
}
BinOp::Mod => {
let value = if is_float {
block
.append_operation(arith::remf(lhs, rhs, location))
.result(0)?
.into()
} else if is_signed {
block
.append_operation(arith::remsi(lhs, rhs, location))
.result(0)?
.into()
} else {
block
.append_operation(arith::remui(lhs, rhs, location))
.result(0)?
.into()
};
(value, lhs_ty)
}
BinOp::BitXor => todo!(),
BinOp::BitAnd => todo!(),
BinOp::BitOr => todo!(),
BinOp::Shl => todo!(),
BinOp::Shr => todo!(),
BinOp::Eq => {
let value = if is_float {
block
.append_operation(arith::cmpf(
ctx.context(),
arith::CmpfPredicate::Oeq,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Eq,
lhs,
rhs,
location,
))
.result(0)?
.into()
};
(
value,
Ty {
span: None,
kind: TyKind::Bool,
},
)
}
BinOp::Lt => {
let value = if is_float {
block
.append_operation(arith::cmpf(
ctx.context(),
arith::CmpfPredicate::Olt,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else if is_signed {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Slt,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Ult,
lhs,
rhs,
location,
))
.result(0)?
.into()
};
(
value,
Ty {
span: None,
kind: TyKind::Bool,
},
)
}
BinOp::Le => {
let value = if is_float {
block
.append_operation(arith::cmpf(
ctx.context(),
arith::CmpfPredicate::Ole,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else if is_signed {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Sle,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Ule,
lhs,
rhs,
location,
))
.result(0)?
.into()
};
(
value,
Ty {
span: None,
kind: TyKind::Bool,
},
)
}
BinOp::Ne => {
let value = if is_float {
block
.append_operation(arith::cmpf(
ctx.context(),
arith::CmpfPredicate::One,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Ult,
lhs,
rhs,
location,
))
.result(0)?
.into()
};
(
value,
Ty {
span: None,
kind: TyKind::Bool,
},
)
}
BinOp::Ge => {
let value = if is_float {
block
.append_operation(arith::cmpf(
ctx.context(),
arith::CmpfPredicate::Ole,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else if is_signed {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Sge,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Uge,
lhs,
rhs,
location,
))
.result(0)?
.into()
};
(
value,
Ty {
span: None,
kind: TyKind::Bool,
},
)
}
BinOp::Gt => {
let value = if is_float {
block
.append_operation(arith::cmpf(
ctx.context(),
arith::CmpfPredicate::Ogt,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else if is_signed {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Sgt,
lhs,
rhs,
location,
))
.result(0)?
.into()
} else {
block
.append_operation(arith::cmpi(
ctx.context(),
arith::CmpiPredicate::Ugt,
lhs,
rhs,
location,
))
.result(0)?
.into()
};
(
value,
Ty {
span: None,
kind: TyKind::Bool,
},
)
}
})
}
fn compile_load_operand<'c: 'b, 'b>(
ctx: &'c FunctionCodegenCtx,
block: &'b Block<'c>,
info: &Operand,
locals: &HashMap<usize, Value<'c, '_>>,
) -> Result<(Value<'c, 'b>, Ty), CodegenError> {
Ok(match info {
Operand::Place(info) => compile_load_place(ctx, block, info, locals)?,
Operand::Const(data) => match &data.data {
concrete_ir::ConstKind::Param(_) => todo!(),
concrete_ir::ConstKind::Value(value) => {
(compile_value_tree(ctx, block, value)?, data.ty.clone())
}
concrete_ir::ConstKind::Expr(_) => todo!(),
},
})
}
/// Compiles a store to a given place in memory.
fn compile_store_place<'c: 'b, 'b>(
ctx: &'c FunctionCodegenCtx,
block: &'b Block<'c>,
info: &Place,
value: Value<'c, 'b>,
locals: &HashMap<usize, Value<'c, '_>>,
) -> Result<(), CodegenError> {
let mut ptr = locals[&info.local];
let local = &ctx.get_fn_body().locals[info.local];
let mut local_ty = local.ty.clone();
for proj in &info.projection {
match proj {
PlaceElem::Deref => {
ptr = block
.append_operation(llvm::load(
ctx.context(),
ptr,
compile_type(ctx.module_ctx, &local_ty),
Location::unknown(ctx.context()),
LoadStoreOptions::default(),
))
.result(0)?
.into();
local_ty = match local_ty.kind {
TyKind::Ref(inner, _) => *inner,
TyKind::Ptr(inner, _) => *inner,
ty => unreachable!("tried to deref: {:?}", ty),
};
}
PlaceElem::Field(field_idx) => {
ptr = block
.append_operation(llvm::get_element_ptr(
ctx.context(),
ptr,
DenseI32ArrayAttribute::new(
ctx.context(),
&[0, (*field_idx).try_into().unwrap()],
),