-
Notifications
You must be signed in to change notification settings - Fork 36
/
mod.rs
1787 lines (1691 loc) · 69.1 KB
/
mod.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
//! LLVM code generation for frawk programs.
mod attr;
pub(crate) mod builtin_functions;
pub(crate) mod intrinsics;
use crate::builtins;
use crate::bytecode::Accum;
use crate::codegen::{
self, intrinsics::register_all, Backend, CodeGenerator, Handles, Jit, Ref, Sig, StrReg,
};
use crate::common::{Either, FileSpec, NodeIx, NumTy, Result, Stage};
use crate::compile::{self, Ty, Typer};
use crate::runtime;
use hashbrown::{HashMap, HashSet};
use libc::c_char;
use llvm_sys::{
analysis::{LLVMVerifierFailureAction, LLVMVerifyModule},
core::*,
execution_engine::*,
prelude::*,
target::*,
};
use petgraph::visit::Dfs;
use smallvec::smallvec;
use intrinsics::IntrinsicMap;
use std::ffi::{CStr, CString};
use std::mem::{self, MaybeUninit};
use std::ptr;
pub(crate) use codegen::Config;
type Pred = llvm_sys::LLVMIntPredicate;
type FPred = llvm_sys::LLVMRealPredicate;
type BuiltinFunc = builtin_functions::Function;
type SmallVec<T> = smallvec::SmallVec<[T; 2]>;
#[derive(Clone)]
struct IterState {
iter_ptr: LLVMValueRef, // ptr to elt type
cur_index: LLVMValueRef, // ptr to integer
len: LLVMValueRef, // integer
}
struct Function {
// NB this is always the same as the matching FuncInfo val; it's in here for convenience.
val: LLVMValueRef,
builder: LLVMBuilderRef,
locals: HashMap<(NumTy, Ty), LLVMValueRef>,
iters: HashMap<(NumTy, Ty), IterState>,
skip_drop: HashSet<(NumTy, Ty)>,
args: SmallVec<(NumTy, Ty)>,
id: usize,
}
struct FuncInfo {
val: LLVMValueRef,
globals: HashMap<(NumTy, Ty), usize>,
num_args: usize,
}
macro_rules! intrinsic {
($name:ident) => {
crate::codegen::intrinsics::$name as *const u8
};
}
struct View<'a> {
f: &'a mut Function,
decls: &'a Vec<FuncInfo>,
tmap: &'a TypeMap,
intrinsics: &'a mut IntrinsicMap,
ctx: LLVMContextRef,
module: LLVMModuleRef,
printfs: &'a mut HashMap<(SmallVec<Ty>, PrintfKind), LLVMValueRef>,
prints: &'a mut HashMap<(usize, /*stdout*/ bool), LLVMValueRef>,
handles: &'a mut Handles,
drop_str: LLVMValueRef,
// We keep an extra builder always pointed at the start of the function. This is because
// binding new string values requires an `alloca`; and we do not want to call `alloca` where a
// string variable is referenced: for example, we do not want to call alloca in a loop.
entry_builder: LLVMBuilderRef,
}
impl<'a> Backend for View<'a> {
type Ty = LLVMTypeRef;
fn void_ptr_ty(&self) -> Self::Ty {
self.tmap.runtime_ty
}
fn u32_ty(&self) -> Self::Ty {
unsafe { LLVMIntTypeInContext(self.ctx, 32) }
}
fn ptr_to(&self, ty: Self::Ty) -> Self::Ty {
unsafe { LLVMPointerType(ty, 0) }
}
fn usize_ty(&self) -> Self::Ty {
unsafe { LLVMIntTypeInContext(self.ctx, (mem::size_of::<*const u8>() * 8) as libc::c_uint) }
}
fn get_ty(&self, ty: compile::Ty) -> Self::Ty {
self.tmap.get_ty(ty)
}
fn register_external_fn(
&mut self,
name: &'static str,
name_c: *const u8,
addr: *const u8,
sig: Sig<Self>,
) -> Result<()> {
let f_ty = unsafe {
LLVMFunctionType(
sig.ret.unwrap_or_else(|| LLVMVoidTypeInContext(self.ctx)),
sig.args.as_mut_ptr(),
sig.args.len() as u32,
0,
)
};
self.intrinsics
.register(name, name_c as *const _, f_ty, sig.attrs, addr as *mut _);
Ok(())
}
}
impl<'a> CodeGenerator for View<'a> {
type Val = LLVMValueRef;
fn bind_val(&mut self, val: Ref, to: Self::Val) -> Result<()> {
unsafe {
// if val is global, then find the relevant parameter and store it directly.
// if val is an existing local, fail
// if val.ty is a string, alloca a new string, store it, then bind the result.
// otherwise, just bind the result directly.
#[cfg(debug_assertions)]
{
if let Ty::Str = val.1 {
use llvm_sys::LLVMTypeKind::*;
// make sure we are passing string values, not pointers here.
assert_eq!(LLVMGetTypeKind(LLVMTypeOf(to)), LLVMIntegerTypeKind);
}
}
if val.1 == Ty::Null {
// We do not store null values explicitly
return Ok(());
}
use Ty::*;
if let Some(ix) = self.decls[self.f.id].globals.get(&val) {
// We're storing into a global variable. If it's a string or map, that means we have to
// alter the reference counts appropriately.
// - if Str, call drop, store, call ref.
// - if Map, load the value, drop it, ref `to` then store it
// - otherwise, just store it directly
let param = LLVMGetParam(self.f.val, *ix as libc::c_uint);
let new_global = to;
match val.1 {
MapIntInt | MapIntStr | MapIntFloat | MapStrInt | MapStrStr | MapStrFloat => {
let prev_global = LLVMBuildLoad(self.f.builder, param, c_str!(""));
self.drop_val(prev_global, val.1);
LLVMBuildStore(self.f.builder, new_global, param);
}
Str => {
self.drop_val(param, Ty::Str);
LLVMBuildStore(self.f.builder, new_global, param);
}
_ => {
LLVMBuildStore(self.f.builder, new_global, param);
}
};
return Ok(());
}
debug_assert!(
self.f.locals.get(&val).is_none(),
"we are inserting {:?}, but there is already something in there: {:?}",
val,
self.f.locals[&val]
);
match val.1 {
MapIntInt | MapIntStr | MapIntFloat | MapStrInt | MapStrStr | MapStrFloat => {
// alloca only fails with an iterator or null type; but we have checked the type
// already.
let loc = self.alloca(val.1).unwrap();
let prev = LLVMBuildLoad(self.f.builder, loc, c_str!(""));
self.drop_val(prev, val.1);
LLVMBuildStore(self.f.builder, to, loc);
self.f.locals.insert(val, loc);
return Ok(());
}
Str => {
// Note: we ref strings ahead of time, either before calling bind_val in a
// MovStr, or as the result of a function call.
// unwrap justified like the above case for maps.
let loc = self.alloca(Ty::Str).unwrap();
self.drop_val(loc, Ty::Str);
LLVMBuildStore(self.f.builder, to, loc);
self.f.locals.insert(val, loc);
return Ok(());
}
_ => {}
}
self.f.locals.insert(val, to);
}
Ok(())
}
fn get_val(&mut self, r: Ref) -> Result<Self::Val> {
match unsafe {
self.get_local_inner(r, /*array_ptr=*/ false)
} {
Some(v) => Ok(v),
None => err!("unbound variable {:?} (must call bind_val on it before)", r),
}
}
fn runtime_val(&mut self) -> Self::Val {
unsafe {
LLVMGetParam(
self.f.val,
self.decls[self.f.id].num_args as libc::c_uint - 1,
)
}
}
fn const_int(&mut self, i: i64) -> Self::Val {
unsafe {
LLVMConstInt(self.get_ty(Ty::Int), i as u64, /*sign_extend=*/ 0)
}
}
fn const_float(&mut self, f: f64) -> Self::Val {
unsafe { LLVMConstReal(self.get_ty(Ty::Float), f) }
}
fn const_str(&mut self, s: &runtime::UniqueStr) -> Self::Val {
// We don't know where we're storing this string literal. If it's in the middle of
// a loop, we could be calling drop on it repeatedly. If the string is boxed, that
// will lead to double-frees. In our current setup, these literals will all be
// either empty, or references to word-aligned arena-allocated strings, so that's
// actually fine.
let as_str = s.clone_str();
assert!(as_str.drop_is_trivial());
let sc = as_str.into_bits();
// There is no way to pass a 128-bit integer to LLVM directly. We have to convert
// it to a string first.
let as_hex = CString::new(format!("{:x}", sc)).unwrap();
let ty = self.tmap.get_ty(Ty::Str);
unsafe {
LLVMConstIntOfString(ty, as_hex.as_ptr(), /*radix=*/ 16)
}
}
fn const_ptr<T>(&mut self, c: *const T) -> Self::Val {
let voidp = self.tmap.runtime_ty;
let int_ty = self.tmap.get_ty(Ty::Int);
unsafe {
let bits = LLVMConstInt(int_ty, c as u64, /*sign_extend=*/ 0);
LLVMBuildIntToPtr(self.f.builder, bits, voidp, c_str!(""))
}
}
fn handles(&mut self) -> &mut Handles {
self.handles
}
fn call_intrinsic(&mut self, func: codegen::Op, args: &mut [Self::Val]) -> Result<Self::Val> {
use codegen::Op::*;
fn to_pred(cmp: codegen::Cmp, is_float: bool) -> Either<Pred, FPred> {
use codegen::Cmp::*;
if is_float {
Either::Right(match cmp {
// LLVM gives you `O` and `U` variants for float comparisons that "fail true"
// or "fail false" if either operand is NaN. `O` is what matches the bytecode
// interpreter, but we may want to switch this around at some point.
Eq => FPred::LLVMRealOEQ,
Lt => FPred::LLVMRealOLT,
Lte => FPred::LLVMRealOLE,
Gt => FPred::LLVMRealOGT,
Gte => FPred::LLVMRealOGE,
})
} else {
Either::Left(match cmp {
Eq => Pred::LLVMIntEQ,
Lt => Pred::LLVMIntSLT,
Lte => Pred::LLVMIntSLE,
Gt => Pred::LLVMIntSGT,
Gte => Pred::LLVMIntSGE,
})
}
}
fn translate_float_func(
ff: builtins::FloatFunc,
) -> Either<*const u8, builtin_functions::Function> {
use builtins::FloatFunc::*;
match ff {
Cos => Either::Right(builtin_functions::Function::Cos),
Sin => Either::Right(builtin_functions::Function::Sin),
Log => Either::Right(builtin_functions::Function::Log),
Log2 => Either::Right(builtin_functions::Function::Log2),
Log10 => Either::Right(builtin_functions::Function::Log10),
Sqrt => Either::Right(builtin_functions::Function::Sqrt),
Exp => Either::Right(builtin_functions::Function::Exp),
Atan => Either::Left(codegen::intrinsics::_frawk_atan as _),
Atan2 => Either::Left(codegen::intrinsics::_frawk_atan2 as _),
}
}
unsafe {
match func {
Cmp { is_float, op } => Ok(self.cmp(to_pred(op, is_float), args[0], args[1])),
Arith { is_float, op } => {
use codegen::Arith::*;
let res = if is_float {
match op {
Mul => LLVMBuildFMul(self.f.builder, args[0], args[1], c_str!("")),
Minus => LLVMBuildFSub(self.f.builder, args[0], args[1], c_str!("")),
Add => LLVMBuildFAdd(self.f.builder, args[0], args[1], c_str!("")),
Mod => LLVMBuildFRem(self.f.builder, args[0], args[1], c_str!("")),
Neg => LLVMBuildFNeg(self.f.builder, args[0], c_str!("")),
}
} else {
match op {
Mul => LLVMBuildMul(self.f.builder, args[0], args[1], c_str!("")),
Minus => LLVMBuildSub(self.f.builder, args[0], args[1], c_str!("")),
Add => LLVMBuildAdd(self.f.builder, args[0], args[1], c_str!("")),
Mod => LLVMBuildSRem(self.f.builder, args[0], args[1], c_str!("")),
Neg => {
let zero = self.const_int(0);
LLVMBuildSub(self.f.builder, zero, args[0], c_str!(""))
}
}
};
Ok(res)
}
Bitwise(bw) => {
use builtins::Bitwise::*;
Ok(match bw {
Complement => LLVMBuildXor(
self.f.builder,
args[0],
LLVMConstInt(self.get_ty(Ty::Int), !0, /*sign_extend=*/ 1),
c_str!(""),
),
And => LLVMBuildAnd(self.f.builder, args[0], args[1], c_str!("")),
Or => LLVMBuildOr(self.f.builder, args[0], args[1], c_str!("")),
LogicalRightShift => {
LLVMBuildLShr(self.f.builder, args[0], args[1], c_str!(""))
}
ArithmeticRightShift => {
LLVMBuildAShr(self.f.builder, args[0], args[1], c_str!(""))
}
LeftShift => LLVMBuildShl(self.f.builder, args[0], args[1], c_str!("")),
Xor => LLVMBuildXor(self.f.builder, args[0], args[1], c_str!("")),
})
}
Math(ff) => Ok(match translate_float_func(ff) {
Either::Left(fname) => self.call(fname, args),
Either::Right(builtin) => self.call_builtin(builtin, args),
}),
Div => Ok(LLVMBuildFDiv(self.f.builder, args[0], args[1], c_str!(""))),
Pow => Ok(self.call_builtin(BuiltinFunc::Pow, args)),
FloatToInt => Ok(LLVMBuildFPToSI(
self.f.builder,
args[0],
self.get_ty(Ty::Int),
c_str!(""),
)),
IntToFloat => Ok(LLVMBuildSIToFP(
self.f.builder,
args[0],
self.get_ty(Ty::Float),
c_str!(""),
)),
Intrinsic(f) => Ok(self.call(f, args)),
}
}
}
fn printf(
&mut self,
output: &Option<(StrReg, FileSpec)>,
fmt: &StrReg,
args: &[Ref],
) -> Result<()> {
unsafe {
// First, extract the types and use that to get a handle on a wrapped printf
// function.
let arg_tys: SmallVec<_> = args.iter().map(|x| x.1).collect();
let printf_fn = self.wrapped_printf((
arg_tys,
if output.is_some() {
PrintfKind::File
} else {
PrintfKind::Stdout
},
));
let mut arg_vs = SmallVec::with_capacity(if output.is_some() {
args.len() + 4
} else {
args.len() + 2
});
arg_vs.push(self.runtime_val());
arg_vs.push(self.get_val(fmt.reflect())?);
for a in args.iter().cloned() {
arg_vs.push(self.get_val(a)?);
}
if let Some((path, append)) = output {
arg_vs.push(self.get_val(path.reflect())?);
let int_ty = self.tmap.get_ty(Ty::Int);
arg_vs.push(LLVMConstInt(int_ty, *append as u64, 0));
}
LLVMBuildCall(
self.f.builder,
printf_fn,
arg_vs.as_mut_ptr(),
arg_vs.len() as libc::c_uint,
c_str!(""),
);
}
Ok(())
}
fn sprintf(&mut self, dst: &StrReg, fmt: &StrReg, args: &[Ref]) -> Result<()> {
unsafe {
let arg_tys: SmallVec<_> = args.iter().map(|x| x.1).collect();
let sprintf_fn = self.wrapped_printf((arg_tys, PrintfKind::Sprintf));
let mut arg_vs = SmallVec::with_capacity(args.len() + 1);
arg_vs.push(self.runtime_val());
arg_vs.push(self.get_val(fmt.reflect())?);
for a in args.iter().cloned() {
arg_vs.push(self.get_val(a)?);
}
let resv = LLVMBuildCall(
self.f.builder,
sprintf_fn,
arg_vs.as_mut_ptr(),
arg_vs.len() as libc::c_uint,
c_str!(""),
);
self.bind_val(dst.reflect(), resv)
}
}
fn print_all(&mut self, output: &Option<(StrReg, FileSpec)>, args: &[StrReg]) -> Result<()> {
unsafe {
let print_fn = self.print_all_fn(args.len(), /*is_stdout=*/ output.is_none())?;
let mut args_v =
SmallVec::with_capacity(args.len() + 1 + if output.is_some() { 2 } else { 0 });
args_v.push(self.runtime_val());
for a in args.iter() {
args_v.push(self.get_val(a.reflect())?);
}
if let Some((out, fspec)) = output {
args_v.push(self.get_val(out.reflect())?);
let int_ty = self.tmap.get_ty(Ty::Int);
args_v.push(LLVMConstInt(int_ty, *fspec as u64, /*sign_extend=*/ 0));
}
LLVMBuildCall(
self.f.builder,
print_fn,
args_v.as_mut_ptr(),
args_v.len() as libc::c_uint,
c_str!(""),
);
}
Ok(())
}
fn mov(&mut self, ty: compile::Ty, dst: NumTy, src: NumTy) -> Result<()> {
unsafe {
let sv = self.get_val((src, ty))?;
if let Ty::Str = ty {
self.call(intrinsic!(ref_str), &mut [sv]);
let loaded = LLVMBuildLoad(self.f.builder, sv, c_str!(""));
self.bind_val((dst, Ty::Str), loaded)
} else {
if ty.is_array() {
self.call(intrinsic!(ref_map), &mut [sv]);
}
self.bind_val((dst, ty), sv)
}
}
}
fn iter_begin(&mut self, dst: Ref, map: Ref) -> Result<()> {
unsafe {
use Ty::*;
let arrv = self.get_val(map)?;
let (len_fn, begin_fn) = match map.1 {
MapIntInt => (intrinsic!(len_intint), intrinsic!(iter_intint)),
MapIntStr => (intrinsic!(len_intstr), intrinsic!(iter_intstr)),
MapIntFloat => (intrinsic!(len_intfloat), intrinsic!(iter_intfloat)),
MapStrInt => (intrinsic!(len_strint), intrinsic!(iter_strint)),
MapStrStr => (intrinsic!(len_strstr), intrinsic!(iter_strstr)),
MapStrFloat => (intrinsic!(len_strfloat), intrinsic!(iter_strfloat)),
_ => return err!("iterating over non-map type: {:?}", map.1),
};
let iter_ptr = self.call(begin_fn, &mut [arrv]);
let cur_index = self.alloca(Ty::Int)?;
let ty = self.tmap.get_ty(Ty::Int);
let zero = LLVMConstInt(ty, 0, /*sign_extend=*/ 1);
LLVMBuildStore(self.f.builder, zero, cur_index);
let len = self.call(len_fn, &mut [arrv]);
let _old = self.f.iters.insert(
dst,
IterState {
iter_ptr,
cur_index,
len,
},
);
debug_assert!(_old.is_none());
Ok(())
}
}
fn iter_hasnext(&mut self, dst: Ref, iter: Ref) -> Result<()> {
unsafe {
let istate = self.get_iter(iter)?;
let cur = LLVMBuildLoad(self.f.builder, istate.cur_index, c_str!(""));
let len = istate.len;
let hasnext = self.cmp(Either::Left(Pred::LLVMIntULT), cur, len);
self.bind_val(dst, hasnext)
}
}
fn iter_getnext(&mut self, dst: Ref, iter: Ref) -> Result<()> {
let (res, res_loc) = unsafe {
let istate = self.get_iter(iter)?;
let cur = LLVMBuildLoad(self.f.builder, istate.cur_index, c_str!(""));
let indices = &mut [cur];
let res_loc = LLVMBuildGEP(
self.f.builder,
istate.iter_ptr,
indices.as_mut_ptr(),
indices.len() as libc::c_uint,
c_str!(""),
);
let res = LLVMBuildLoad(self.f.builder, res_loc, c_str!(""));
let next_ix = LLVMBuildAdd(
self.f.builder,
cur,
LLVMConstInt(self.tmap.get_ty(Ty::Int), 1, /*sign_extend=*/ 1),
c_str!(""),
);
LLVMBuildStore(self.f.builder, next_ix, istate.cur_index);
(res, res_loc)
};
if let Ty::Str = dst.1 {
unsafe { self.call(intrinsic!(ref_str), &mut [res_loc]) };
}
self.bind_val(dst, res)
}
}
impl Drop for Function {
fn drop(&mut self) {
unsafe {
LLVMDisposeBuilder(self.builder);
}
}
}
#[derive(Copy, Clone)]
struct TypeRef {
base: LLVMTypeRef,
ptr: LLVMTypeRef,
}
impl TypeRef {
fn null() -> TypeRef {
TypeRef {
base: ptr::null_mut(),
ptr: ptr::null_mut(),
}
}
}
// Common LLVM types used in code generation.
pub(crate) struct TypeMap {
// Map from compile::Ty => TypeRef
table: [TypeRef; compile::NUM_TYPES],
runtime_ty: LLVMTypeRef,
}
impl TypeMap {
fn new(ctx: LLVMContextRef) -> TypeMap {
unsafe {
TypeMap {
table: [TypeRef::null(); compile::NUM_TYPES],
runtime_ty: LLVMPointerType(LLVMVoidTypeInContext(ctx), 0),
}
}
}
fn init(&mut self, ty: Ty, r: TypeRef) {
self.table[ty as usize] = r;
}
fn get_ty(&self, ty: Ty) -> LLVMTypeRef {
self.table[ty as usize].base
}
fn get_ptr_ty(&self, ty: Ty) -> LLVMTypeRef {
self.table[ty as usize].ptr
}
}
#[derive(Copy, Clone, Hash, Eq, PartialEq)]
enum PrintfKind {
Stdout,
File,
Sprintf,
}
pub(crate) struct Generator<'a, 'b> {
types: &'b mut Typer<'a>,
ctx: LLVMContextRef,
module: LLVMModuleRef,
engine: LLVMExecutionEngineRef,
decls: Vec<FuncInfo>,
funcs: Vec<Function>,
handles: Handles,
type_map: TypeMap,
intrinsics: IntrinsicMap,
printfs: HashMap<(SmallVec<Ty>, PrintfKind), LLVMValueRef>,
prints: HashMap<(usize, /*stdout*/ bool), LLVMValueRef>,
// We pass raw regex pointers in the generated code. These ensure we do not free them
// before the code is run.
cfg: Config,
// Specialized implementation of string destruction.
drop_str: LLVMValueRef,
}
impl<'a, 'b> Drop for Generator<'a, 'b> {
fn drop(&mut self) {
unsafe {
LLVMDisposeModule(self.module);
}
}
}
unsafe fn alloc_local(
builder: LLVMBuilderRef,
ty: Ty,
tmap: &TypeMap,
intrinsics: &IntrinsicMap,
) -> Result<LLVMValueRef> {
use Ty::*;
let val = match ty {
// NB do we really need the NULL here? or could we omit calls
Null | Int => LLVMConstInt(tmap.get_ty(Int), 0, /*sign_extend=*/ 1),
Float => LLVMConstReal(tmap.get_ty(Float), 0.0),
Str => {
let str_ty = tmap.get_ty(Str);
let v = LLVMConstInt(str_ty, 0, /*sign_extend=*/ 0);
let v_loc = LLVMBuildAlloca(builder, str_ty, c_str!(""));
LLVMBuildStore(builder, v, v_loc);
v_loc
}
MapIntInt | MapIntStr | MapIntFloat | MapStrInt | MapStrStr | MapStrFloat => {
let func = match ty {
MapIntInt => intrinsic!(alloc_intint),
MapIntFloat => intrinsic!(alloc_intfloat),
MapIntStr => intrinsic!(alloc_intstr),
MapStrInt => intrinsic!(alloc_strint),
MapStrFloat => intrinsic!(alloc_strfloat),
MapStrStr => intrinsic!(alloc_strstr),
_ => unreachable!(),
};
let map_ty = tmap.get_ty(ty);
let v = LLVMBuildCall(
builder,
intrinsics.get(func),
ptr::null_mut(),
0,
c_str!(""),
);
let v_loc = LLVMBuildAlloca(builder, map_ty, c_str!(""));
LLVMBuildStore(builder, v, v_loc);
v_loc
}
IterInt | IterStr => return err!("we should not be default-allocating any iterators"),
};
Ok(val)
}
// We could just as easily make this a method on Generator, but we need the per-field tracking that
// we get from NLL that is blocked by a method like that.
macro_rules! view_at {
($slf:expr, $func_id:expr, $entry_builder:expr) => {
View {
f: &mut $slf.funcs[$func_id],
tmap: &$slf.type_map,
intrinsics: &mut $slf.intrinsics,
handles: &mut $slf.handles,
decls: &$slf.decls,
printfs: &mut $slf.printfs,
prints: &mut $slf.prints,
ctx: $slf.ctx,
module: $slf.module,
drop_str: $slf.drop_str,
entry_builder: $entry_builder,
}
};
}
impl<'a, 'b> Jit for Generator<'a, 'b> {
fn main_pointers(&mut self) -> Result<Stage<*const u8>> {
unsafe {
let main = self.gen_main()?;
self.verify()?;
self.optimize(main.iter().map(|(_, x)| x).cloned())?;
Ok(main.map(|(name, _)| LLVMGetFunctionAddress(self.engine, name) as *const u8))
}
}
}
impl<'a, 'b> Generator<'a, 'b> {
pub unsafe fn optimize(&mut self, mains: impl Iterator<Item = LLVMValueRef>) -> Result<()> {
// Based on optimize_module in weld, in turn based on similar code in the LLVM opt tool.
use llvm_sys::transforms::pass_manager_builder::*;
let mpm = LLVMCreatePassManager();
let fpm = LLVMCreateFunctionPassManagerForModule(self.module);
let builder = LLVMPassManagerBuilderCreate();
LLVMPassManagerBuilderSetOptLevel(builder, self.cfg.opt_level as u32);
LLVMPassManagerBuilderSetSizeLevel(builder, 0);
match self.cfg.opt_level {
0 => {}
1 => LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 50),
2 => LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 100),
3 => LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 250),
_ => return err!("unrecognized opt level"),
};
LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
LLVMPassManagerBuilderDispose(builder);
for f in self.decls.iter() {
if f.val.is_null() {
// unused functions are given null values.
continue;
}
LLVMRunFunctionPassManager(fpm, f.val);
}
for fv in self.printfs.values() {
LLVMRunFunctionPassManager(fpm, *fv);
}
for main in mains {
LLVMRunFunctionPassManager(fpm, main);
}
LLVMFinalizeFunctionPassManager(fpm);
LLVMRunPassManager(mpm, self.module);
LLVMDisposePassManager(fpm);
LLVMDisposePassManager(mpm);
Ok(())
}
pub unsafe fn init(types: &'b mut Typer<'a>, cfg: Config) -> Result<Generator<'a, 'b>> {
if llvm_sys::support::LLVMLoadLibraryPermanently(ptr::null()) != 0 {
return err!("failed to load in-process library");
}
let ctx = LLVMContextCreate();
let module = LLVMModuleCreateWithNameInContext(c_str!("frawk_main"), ctx);
// JIT-specific initialization.
LLVM_InitializeNativeTarget();
LLVM_InitializeNativeAsmPrinter();
LLVM_InitializeNativeAsmParser();
LLVMLinkInMCJIT();
let mut maybe_engine = MaybeUninit::<LLVMExecutionEngineRef>::uninit();
let mut err: *mut c_char = ptr::null_mut();
if LLVMCreateExecutionEngineForModule(maybe_engine.as_mut_ptr(), module, &mut err) != 0 {
let res = err!(
"failed to create program: {}",
CStr::from_ptr(err).to_str().unwrap()
);
LLVMDisposeMessage(err);
return res;
}
let engine = maybe_engine.assume_init();
let nframes = types.frames.len();
let mut res = Generator {
types,
ctx,
module,
engine,
decls: Vec::with_capacity(nframes),
funcs: Vec::with_capacity(nframes),
type_map: TypeMap::new(ctx),
intrinsics: IntrinsicMap::new(module, ctx),
printfs: Default::default(),
prints: Default::default(),
handles: Default::default(),
cfg,
drop_str: ptr::null_mut(),
};
res.build_map();
res.build_decls();
// Construct a placeholder `View` and use it to register intrinsics.
register_all(&mut view_at!(res, 0, ptr::null_mut()))?;
let drop_slow = res.intrinsics.get(intrinsic!(drop_str_slow));
res.drop_str =
builtin_functions::gen_drop_str(res.ctx, res.module, &res.type_map, drop_slow);
for i in 0..nframes {
res.gen_function(i)?;
}
Ok(res)
}
unsafe fn dump_module_inner(&mut self) -> String {
let c_str = LLVMPrintModuleToString(self.module);
let res = CStr::from_ptr(c_str).to_string_lossy().into_owned();
libc::free(c_str as *mut _);
res
}
pub unsafe fn dump_module(&mut self) -> Result<String> {
let mains = self.gen_main()?;
self.verify()?;
self.optimize(mains.iter().map(|(_, x)| x).cloned())?;
Ok(self.dump_module_inner())
}
// For benchmarking.
#[cfg(all(test, feature = "unstable"))]
pub unsafe fn compile_main(&mut self) -> Result<()> {
let mains = self.gen_main()?;
self.verify()?;
self.optimize(mains.iter().map(|(_, x)| x).cloned())?;
let addr = LLVMGetFunctionAddress(self.engine, c_str!("__frawk_main"));
ptr::read_volatile(&addr);
Ok(())
}
unsafe fn build_map(&mut self) {
let make = |ty| TypeRef {
base: ty,
ptr: LLVMPointerType(ty, 0),
};
let voidptr = LLVMPointerType(LLVMVoidTypeInContext(self.ctx), 0);
self.type_map.init(
Ty::Int,
make(LLVMIntTypeInContext(
self.ctx,
runtime::Int::BITS as libc::c_uint,
)),
);
self.type_map
.init(Ty::Float, make(LLVMDoubleTypeInContext(self.ctx)));
self.type_map
.init(Ty::Str, make(LLVMIntTypeInContext(self.ctx, 128)));
self.type_map.init(Ty::MapIntInt, make(voidptr));
self.type_map.init(Ty::MapIntFloat, make(voidptr));
self.type_map.init(Ty::MapIntStr, make(voidptr));
self.type_map.init(Ty::MapStrInt, make(voidptr));
self.type_map.init(Ty::MapStrFloat, make(voidptr));
self.type_map.init(Ty::MapStrStr, make(voidptr));
// NB: iterators do not have types of their own, and we should never ask for their types.
// See the IterState type and its uses for more info.
self.type_map.init(Ty::IterInt, TypeRef::null());
self.type_map.init(Ty::IterStr, TypeRef::null());
self.type_map
.init(Ty::Null, make(self.type_map.get_ty(Ty::Int)));
}
fn llvm_ty(&self, ty: Ty) -> LLVMTypeRef {
if let Ty::Str = ty {
self.type_map.get_ptr_ty(ty)
} else {
self.type_map.get_ty(ty)
}
}
fn llvm_ptr_ty(&self, ty: Ty) -> LLVMTypeRef {
self.type_map.get_ptr_ty(ty)
}
unsafe fn build_decls(&mut self) {
let global_refs = self.types.get_global_refs();
debug_assert_eq!(global_refs.len(), self.types.func_info.len());
let mut arg_tys = SmallVec::new();
for (i, (info, refs)) in self
.types
.func_info
.iter()
.zip(global_refs.iter())
.enumerate()
{
let is_called = self.types.frames[i].is_called;
let mut globals = HashMap::new();
let name = CString::new(format!("_frawk_udf_{}", i)).unwrap();
// First, we add the listed function parameters.
arg_tys.extend(info.arg_tys.iter().map(|ty| self.llvm_ty(*ty)));
// Then, we add on the referenced globals.
for (reg, ty) in refs.iter().cloned() {
let ix = arg_tys.len();
arg_tys.push(self.llvm_ptr_ty(ty));
// Vals are ignored if we are main.
globals.insert((reg, ty), ix);
}
// Finally, we add a pointer to the runtime; always the last parameter.
arg_tys.push(self.type_map.runtime_ty);
let ty = LLVMFunctionType(
self.type_map.get_ty(info.ret_ty),
arg_tys.as_mut_ptr(),
arg_tys.len() as u32,
/*IsVarArg=*/ 0,
);
let builder = LLVMCreateBuilderInContext(self.ctx);
let val = if is_called {
let val = LLVMAddFunction(self.module, name.as_ptr(), ty);
// We make these private, as we generate a separate main that calls into them. This
// way, function bodies that get inlined into main do not have to show up in
// generated code.
LLVMSetLinkage(val, llvm_sys::LLVMLinkage::LLVMLinkerPrivateLinkage);
val
} else {
ptr::null_mut()
};
let id = self.funcs.len();
self.decls.push(FuncInfo {
val,
globals,
num_args: arg_tys.len(),
});
let args: SmallVec<_> = self.types.frames[i]
.arg_regs
.iter()
.cloned()
.zip(self.types.func_info[i].arg_tys.iter().cloned())
.collect();
self.funcs.push(Function {
val,
builder,
iters: Default::default(),
locals: Default::default(),
skip_drop: Default::default(),
args,
id,
});
arg_tys.clear();
}
}
unsafe fn alloc_local(&self, builder: LLVMBuilderRef, ty: Ty) -> Result<LLVMValueRef> {
alloc_local(builder, ty, &self.type_map, &self.intrinsics)
}
unsafe fn gen_main_function(
&mut self,
main_offset: usize,
name: *const libc::c_char,
) -> Result<(*const libc::c_char, LLVMValueRef)> {
let ty = LLVMFunctionType(
LLVMVoidTypeInContext(self.ctx),
&mut self.type_map.runtime_ty,
1,
/*IsVarArg=*/ 0,
);
let decl = LLVMAddFunction(self.module, name, ty);
let builder = LLVMCreateBuilderInContext(self.ctx);
let bb = LLVMAppendBasicBlockInContext(self.ctx, decl, c_str!(""));
LLVMPositionBuilderAtEnd(builder, bb);
// For now, iterate over each element of the stage and call each component in sequence.
// We need to allocate all of the global variables that our main function uses, and then
// pass them as arguments, along with the runtime.
let main_info = &self.decls[main_offset];
let mut args: SmallVec<_> = smallvec![ptr::null_mut(); main_info.num_args];
let mut to_drop = SmallVec::with_capacity(args.len());
for ((_reg, ty), arg_ix) in main_info.globals.iter() {
let local = self.alloc_local(builder, *ty)?;
let param = if ty.is_array() || matches!(ty, Ty::Str) {
// Already a pointer; we're good to go!
to_drop.push((local, *ty));
local
} else {
let loc = LLVMBuildAlloca(builder, self.llvm_ty(*ty), c_str!(""));
LLVMBuildStore(builder, local, loc);
loc
};
args[*arg_ix] = param;
}
// Pass the runtime last.
args[main_info.num_args - 1] = LLVMGetParam(decl, 0);
LLVMBuildCall(
builder,
main_info.val,
args.as_mut_ptr(),
args.len() as libc::c_uint,
c_str!(""),
);
// now, drop the globals
for (mut local, ty) in to_drop {
if let Ty::Str = ty {
// drop the reference directly
// TODO replace with this line with a call to drop_str
LLVMBuildCall(builder, self.drop_str, &mut local, 1, c_str!(""));
} else {
// issue the load, then call drop.