-
Notifications
You must be signed in to change notification settings - Fork 238
/
Emit.scala
2827 lines (2327 loc) · 115 KB
/
Emit.scala
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
package is.hail.expr.ir
import is.hail.annotations._
import is.hail.asm4s._
import is.hail.backend.{BackendContext, ExecuteContext, HailTaskContext}
import is.hail.expr.ir.agg.{AggStateSig, ArrayAggStateSig, GroupedStateSig}
import is.hail.expr.ir.analyses.{ComputeMethodSplits, ControlFlowPreventsSplit, ParentPointers}
import is.hail.expr.ir.lowering.TableStageDependency
import is.hail.expr.ir.ndarrays.EmitNDArray
import is.hail.expr.ir.streams.{EmitStream, StreamProducer, StreamUtils}
import is.hail.io.fs.FS
import is.hail.io.{BufferSpec, InputBuffer, OutputBuffer, TypedCodecSpec}
import is.hail.linalg.{BLAS, LAPACK, LinalgCodeUtils}
import is.hail.types.physical._
import is.hail.types.physical.stypes._
import is.hail.types.physical.stypes.concrete._
import is.hail.types.physical.stypes.interfaces._
import is.hail.types.physical.stypes.primitives._
import is.hail.types.virtual._
import is.hail.types.{TypeWithRequiredness, VirtualTypeWithReq, tcoerce}
import is.hail.utils._
import is.hail.variant.ReferenceGenome
import java.io._
import scala.collection.mutable
import scala.language.{existentials, postfixOps}
// class for holding all information computed ahead-of-time that we need in the emitter
object EmitContext {
def analyze(ctx: ExecuteContext, ir: IR, pTypeEnv: Env[PType] = Env.empty): EmitContext = {
ctx.timer.time("EmitContext.analyze") {
val usesAndDefs = ComputeUsesAndDefs(ir, errorIfFreeVariables = false)
val requiredness = Requiredness.apply(ir, usesAndDefs, null, pTypeEnv)
val inLoopCriticalPath = ControlFlowPreventsSplit(ir, ParentPointers(ir), usesAndDefs)
val methodSplits = ComputeMethodSplits(ctx, ir, inLoopCriticalPath)
new EmitContext(ctx, requiredness, usesAndDefs, methodSplits, inLoopCriticalPath, Memo.empty[Unit])
}
}
}
class EmitContext(
val executeContext: ExecuteContext,
val req: RequirednessAnalysis,
val usesAndDefs: UsesAndDefs,
val methodSplits: Memo[Unit],
val inLoopCriticalPath: Memo[Unit],
val tryingToSplit: Memo[Unit]
)
case class EmitEnv(bindings: Env[EmitValue], inputValues: IndexedSeq[EmitValue]) {
def bind(name: String, v: EmitValue): EmitEnv = copy(bindings = bindings.bind(name, v))
def bind(newBindings: (String, EmitValue)*): EmitEnv = copy(bindings = bindings.bindIterable(newBindings))
}
object Emit {
def apply[C](ctx: EmitContext, ir: IR, fb: EmitFunctionBuilder[C], rti: TypeInfo[_], nParams: Int, aggs: Option[Array[AggStateSig]] = None): Option[SingleCodeType] = {
TypeCheck(ctx.executeContext, ir)
val mb = fb.apply_method
val container = aggs.map { a =>
val c = fb.addAggStates(a)
AggContainer(a, c, () => ())
}
val emitter = new Emit[C](ctx, fb.ecb)
val region = mb.getCodeParam[Region](1)
val returnTypeOption: Option[SingleCodeType] = if (ir.typ == TVoid) {
fb.apply_method.voidWithBuilder { cb =>
val env = EmitEnv(Env.empty, (0 until nParams).map(i => mb.storeEmitParamAsField(cb, i + 2))) // this, region, ...
emitter.emitVoid(cb, ir, region, env, container, None)
}
None
} else {
var sct: SingleCodeType = null
fb.emitWithBuilder { cb =>
val env = EmitEnv(Env.empty, (0 until nParams).map(i => mb.storeEmitParamAsField(cb, i + 2))) // this, region, ...
val sc = emitter.emitI(ir, cb, region, env, container, None).handle(cb, {
cb._throw[RuntimeException](
Code.newInstance[RuntimeException, String]("cannot return empty"))
})
val scp = SingleCodeSCode.fromSCode(cb, sc, region)
assert(scp.typ.ti == rti, s"type info mismatch: expect $rti, got ${ scp.typ.ti }")
sct = scp.typ
scp.code
}
Some(sct)
}
returnTypeOption
}
}
object AggContainer {
// FIXME remove this when EmitStream also has a codebuilder
def fromVars(aggs: Array[AggStateSig], mb: EmitMethodBuilder[_], region: Settable[Region], off: Settable[Long]): (AggContainer, EmitCodeBuilder => Unit, EmitCodeBuilder => Unit) = {
val (setup, aggState) = EmitCodeBuilder.scoped(mb) { cb =>
val states = agg.StateTuple(aggs.map(a => agg.AggStateSig.getState(a, cb.emb.ecb)))
val aggState = new agg.TupleAggregatorState(mb.ecb, states, region, off)
cb += (region := Region.stagedCreate(Region.REGULAR, cb.emb.ecb.pool()))
cb += region.load().setNumParents(aggs.length)
cb += (off := region.load().allocate(aggState.storageType.alignment, aggState.storageType.byteSize))
states.createStates(cb)
aggState
}
val cleanup = { cb: EmitCodeBuilder =>
aggState.store(cb)
cb += region.load().invalidate()
cb.assign(region, Code._null[Region])
}
(AggContainer(aggs, aggState, () => ()), (cb: EmitCodeBuilder) => cb += setup, cleanup)
}
def fromMethodBuilder[C](aggs: Array[AggStateSig], mb: EmitMethodBuilder[C], varPrefix: String): (AggContainer, EmitCodeBuilder => Unit, EmitCodeBuilder => Unit) =
fromVars(aggs, mb, mb.genFieldThisRef[Region](s"${ varPrefix }_top_region"), mb.genFieldThisRef[Long](s"${ varPrefix }_off"))
def fromBuilder[C](cb: EmitCodeBuilder, aggs: Array[AggStateSig], varPrefix: String): AggContainer = {
val off = cb.newField[Long](s"${ varPrefix }_off")
val region = cb.newField[Region](s"${ varPrefix }_top_region", Region.stagedCreate(Region.REGULAR, cb.emb.ecb.pool()))
val states = agg.StateTuple(aggs.map(a => agg.AggStateSig.getState(a, cb.emb.ecb)))
val aggState = new agg.TupleAggregatorState(cb.emb.ecb, states, region, off)
cb += region.load().setNumParents(aggs.length)
cb.assign(off, region.load().allocate(aggState.storageType.alignment, aggState.storageType.byteSize))
states.createStates(cb)
AggContainer(aggs, aggState, { () =>
aggState.store(cb)
cb += region.load().invalidate()
cb.assign(region, Code._null[Region])
})
}
}
case class AggContainer(aggs: Array[AggStateSig], container: agg.TupleAggregatorState, cleanup: () => Unit) {
def nested(i: Int, init: Boolean): Option[AggContainer] = {
aggs(i).n.map { nested =>
val c = aggs(i) match {
case _: GroupedStateSig =>
val state = container.states(i).asInstanceOf[agg.DictState]
if (init) state.initContainer else state.keyed.container
case _: ArrayAggStateSig =>
val state = container.states(i).asInstanceOf[agg.ArrayElementState]
if (init) state.initContainer else state.container
}
AggContainer(nested.toArray, c, () => ())
}
}
}
object EmitRegion {
def default(mb: EmitMethodBuilder[_]): EmitRegion = EmitRegion(mb, mb.getCodeParam[Region](1))
}
case class EmitRegion(mb: EmitMethodBuilder[_], region: Value[Region]) {
def baseRegion: Value[Region] = mb.getCodeParam[Region](1)
}
object EmitValue {
def apply(missing: Option[Value[Boolean]], v: SValue): EmitValue =
new EmitValue(
missing.filterNot(m => Code.constBoolValue(m).contains(false)),
v)
def present(v: SValue): EmitValue = EmitValue(None, v)
def missing(t: SType): EmitValue = EmitValue(Some(const(true)), t.defaultValue)
}
class EmitValue protected(missing: Option[Value[Boolean]], val v: SValue) {
def m: Value[Boolean] = missing.getOrElse(const(false))
def required: Boolean = missing.isEmpty
def setOptional: EmitValue = new EmitValue(Some(missing.getOrElse(false)), v)
lazy val emitType: EmitType = EmitType(v.st, required)
def valueTuple(): IndexedSeq[Value[_]] = missing match {
case Some(m) => v.valueTuple :+ m
case None => v.valueTuple
}
def load: EmitCode = {
val ec = EmitCode(Code._empty, m, v)
assert(ec.required == required)
ec
}
def loadI(cb: EmitCodeBuilder): IEmitCode = load.toI(cb)
def get(cb: EmitCodeBuilder): SValue = {
missing.foreach { m =>
cb.ifx(m, cb._fatal(s"Can't convert missing ${ v.st } to PValue"))
}
v
}
def map(cb: EmitCodeBuilder)(f: SValue => SValue): EmitValue = missing match {
case None => new EmitValue(None, f(v))
case Some(m) =>
var newV: SValue = null
cb.ifx(!m, { newV = f(v) })
new EmitValue(missing, newV)
}
}
/**
* Notes on IEmitCode;
* 1. It is the responsibility of the producers of IEmitCode to emit the relevant
* jumps for the Lmissing and Lpresent labels (cb.goto or similar)
* 2. It is the responsibility of consumers to define these labels and to
* prevent the SCode from being used on any code path taken as a result of
* jumping to Lmissing.
*/
object IEmitCode {
def apply[A](cb: EmitCodeBuilder, m: Code[Boolean], value: => A): IEmitCodeGen[A] = {
Code.constBoolValue(m) match {
case Some(false) => present(cb, value)
case _ =>
val Lmissing = CodeLabel()
val Lpresent = CodeLabel()
cb.ifx(m, cb.goto(Lmissing))
val res: A = value
cb.goto(Lpresent)
IEmitCodeGen(Lmissing, Lpresent, res, false)
}
}
def apply[A](Lmissing: CodeLabel, Lpresent: CodeLabel, value: A, required: Boolean): IEmitCodeGen[A] =
IEmitCodeGen(Lmissing, Lpresent, value, required)
def present[A](cb: EmitCodeBuilder, value: => A): IEmitCodeGen[A] = {
val Lpresent = CodeLabel()
val res: A = value
cb.goto(Lpresent)
IEmitCodeGen(CodeLabel(), Lpresent, res, true)
}
def missing[A](cb: EmitCodeBuilder, defaultValue: A): IEmitCodeGen[A] = {
val Lmissing = CodeLabel()
cb.goto(Lmissing)
IEmitCodeGen(Lmissing, CodeLabel(), defaultValue, false)
}
def multiMapEmitCodes(cb: EmitCodeBuilder, seq: IndexedSeq[EmitCode])(f: IndexedSeq[SValue] => SValue): IEmitCode =
multiMap(cb, seq.map(ec => cb => ec.toI(cb)))(f)
def multiMap(cb: EmitCodeBuilder,
seq: IndexedSeq[EmitCodeBuilder => IEmitCode]
)(f: IndexedSeq[SValue] => SValue
): IEmitCode = {
val Lmissing = CodeLabel()
val Lpresent = CodeLabel()
var required = true
val pcs = seq.map { elem =>
val iec = elem(cb)
required = required & iec.required
cb.define(iec.Lmissing)
cb.goto(Lmissing)
cb.define(iec.Lpresent)
iec.value
}
val pc = f(pcs)
cb.goto(Lpresent)
IEmitCodeGen(Lmissing, Lpresent, pc, required)
}
def multiFlatMap(cb: EmitCodeBuilder,
seq: IndexedSeq[EmitCodeBuilder => IEmitCode]
)(f: IndexedSeq[SValue] => IEmitCode
): IEmitCode =
multiFlatMap[EmitCodeBuilder => IEmitCode, SValue, SValue](seq, x => x(cb), cb)(f)
def multiFlatMap[A, B, C](seq: IndexedSeq[A], toIec: A => IEmitCodeGen[B], cb: EmitCodeBuilder)
(f: IndexedSeq[B] => IEmitCodeGen[C]): IEmitCodeGen[C] = {
val Lmissing = CodeLabel()
var required: Boolean = true
val pcs = seq.map { elem =>
val iec = toIec(elem)
required = required && iec.required
cb.define(iec.Lmissing)
cb.goto(Lmissing)
cb.define(iec.Lpresent)
iec.value
}
val iec = f(pcs)
required = required && iec.required
cb.define(iec.Lmissing)
cb.goto(Lmissing)
IEmitCodeGen(Lmissing, iec.Lpresent, iec.value, required)
}
}
object IEmitCodeGen {
implicit class IEmitCode(val iec: IEmitCodeGen[SValue]) extends AnyVal {
def pc: SValue = iec.value
def st: SType = pc.st
def memoize(cb: EmitCodeBuilder, name: String): EmitValue =
cb.memoize(iec, name)
def memoizeField(cb: EmitCodeBuilder, name: String): EmitValue =
cb.memoizeField(iec, name)
}
}
case class IEmitCodeGen[+A](Lmissing: CodeLabel, Lpresent: CodeLabel, value: A, required: Boolean) {
lazy val emitType: EmitType = {
value match {
case pc: SValue => EmitType(pc.st, required)
case _ => throw new UnsupportedOperationException(s"emitType on $value")
}
}
def setOptional: IEmitCodeGen[A] = copy(required = false)
def map[B](cb: EmitCodeBuilder)(f: (A) => B): IEmitCodeGen[B] = {
val Lpresent2 = CodeLabel()
cb.define(Lpresent)
val value2 = f(value)
cb.goto(Lpresent2)
IEmitCodeGen(Lmissing, Lpresent2, value2, required)
}
def mapMissing(cb: EmitCodeBuilder)(ifMissing: => Unit): IEmitCodeGen[A] = {
val Lmissing2 = CodeLabel()
cb.define(Lmissing)
ifMissing
cb.goto(Lmissing2)
IEmitCodeGen(Lmissing2, Lpresent, value, required)
}
def flatMap[B](cb: EmitCodeBuilder)(f: (A) => IEmitCodeGen[B]): IEmitCodeGen[B] = {
cb.define(Lpresent)
val ec2 = f(value)
cb.define(ec2.Lmissing)
cb.goto(Lmissing)
IEmitCodeGen(Lmissing, ec2.Lpresent, ec2.value, required && ec2.required)
}
def handle(cb: EmitCodeBuilder, ifMissing: => Unit): A = {
cb.define(Lmissing)
ifMissing
cb.define(Lpresent)
value
}
def get(cb: EmitCodeBuilder, errorMsg: Code[String]=s"expected non-missing", errorID: Code[Int] = const(ErrorIDs.NO_ERROR)): A =
handle(cb, cb._fatalWithError(errorID, errorMsg))
def consume(cb: EmitCodeBuilder, ifMissing: => Unit, ifPresent: (A) => Unit): Unit = {
val Lafter = CodeLabel()
cb.define(Lmissing)
ifMissing
if (cb.isOpenEnded) cb.goto(Lafter)
cb.define(Lpresent)
ifPresent(value)
cb.define(Lafter)
}
def consumeSCode(cb: EmitCodeBuilder, ifMissing: => SValue, ifPresent: (A) => SValue): SValue = {
val Lafter = CodeLabel()
cb.define(Lmissing)
val missingValue = ifMissing
val st = missingValue.st
val ret = cb.emb.newPLocal(st)
cb.assign(ret, missingValue)
cb.goto(Lafter)
cb.define(Lpresent)
val presentValue = ifPresent(value)
assert(presentValue.st == st)
cb.assign(ret, presentValue)
cb.define(Lafter)
ret
}
def consumeI(cb: EmitCodeBuilder, ifMissing: => IEmitCode, ifPresent: A => IEmitCode): IEmitCode = {
val Lmissing2 = CodeLabel()
val Lpresent2 = CodeLabel()
cb.define(Lmissing)
val missingI = ifMissing
val st = missingI.st
val ret = cb.emb.newPLocal(st)
missingI.consume(cb, cb.goto(Lmissing2), v => { cb.assign(ret, v); cb.goto(Lpresent2) })
cb.define(Lpresent)
val presentI = ifPresent(value)
presentI.consume(cb, cb.goto(Lmissing2), v => { cb.assign(ret, v); cb.goto(Lpresent2) })
IEmitCode(Lmissing2, Lpresent2, ret, required = missingI.required && presentI.required)
}
def consumeCode[B: TypeInfo](cb: EmitCodeBuilder, ifMissing: => Value[B], ifPresent: (A) => Value[B]): Value[B] = {
val ret = cb.emb.newLocal[B]("iec_consumeCode")
consume(cb, cb.assign(ret, ifMissing), a => cb.assign(ret, ifPresent(a)))
ret
}
}
object EmitCode {
def apply(setup: Code[Unit], m: Code[Boolean], pv: SValue): EmitCode = {
Code.constBoolValue(m) match {
case Some(false) =>
val Lpresent = CodeLabel()
new EmitCode(new CodeLabel(Code(setup, Lpresent.goto).start), IEmitCode(CodeLabel(), Lpresent, pv, required = true))
case _ =>
val mCC = Code(setup, m).toCCode
val iec = IEmitCode(new CodeLabel(mCC.Ltrue), new CodeLabel(mCC.Lfalse), pv, required = false)
val result = new EmitCode(new CodeLabel(mCC.entry), iec)
result
}
}
def unapply(ec: EmitCode): Option[(Code[Boolean], SValue)] =
Some((ec.m, ec.pv))
def apply(setup: Code[Unit], ec: EmitCode): EmitCode = {
val Lstart = CodeLabel()
Code(Lstart, setup, ec.start.goto)
new EmitCode(Lstart, ec.iec)
}
def present(mb: EmitMethodBuilder[_], sv: SValue): EmitCode =
EmitCode.fromI(mb)(cb => IEmitCode.present(cb, sv))
def missing(mb: EmitMethodBuilder[_], pt: SType): EmitCode =
EmitCode.fromI(mb)(cb => IEmitCode.missing(cb, pt.defaultValue))
def fromI(mb: EmitMethodBuilder[_])(f: (EmitCodeBuilder) => IEmitCode): EmitCode = {
val cb = EmitCodeBuilder(mb)
val iec = f(cb)
val setup = cb.result()
new EmitCode(new CodeLabel(setup.start), iec)
}
}
class EmitCode(private val start: CodeLabel, private val iec: IEmitCode) {
def required: Boolean = iec.required
def setOptional: EmitCode = new EmitCode(start, iec.setOptional)
lazy val emitType: EmitType = iec.emitType
def emitParamType: SCodeEmitParamType = emitType.paramType
def st: SType = iec.value.st
def pv: SValue = iec.value
val m: Code[Boolean] = new CCode(start.L, iec.Lmissing.L, iec.Lpresent.L)
def toI(cb: EmitCodeBuilder): IEmitCode = {
cb.goto(start)
iec
}
def castTo(mb: EmitMethodBuilder[_], region: Value[Region], destType: SType, deepCopy: Boolean = false): EmitCode = {
EmitCode.fromI(mb)(cb => toI(cb).map(cb)(_.castTo(cb, region, destType)))
}
def missingIf(mb: EmitMethodBuilder[_], cond: Code[Boolean]): EmitCode =
EmitCode.fromI(mb) { cb =>
val Ltrue = CodeLabel()
val Lfalse = CodeLabel()
cb.ifx(cond, cb.goto(Ltrue), cb.goto(Lfalse))
cb.define(Lfalse)
val eci = toI(cb)
cb.define(Ltrue)
cb.goto(eci.Lmissing)
eci
}
def memoize(cb: EmitCodeBuilder, name: String): EmitValue = {
val v = cb.emb.newEmitLocal(emitType)
cb.assign(v, this)
v
}
def asVoid(): Code[Unit] = {
require(pv.st == SVoid)
Code.toUnit(m)
}
}
object EmitSettable {
def present(vs: SSettable): EmitSettable = new EmitSettable(None, vs)
}
class EmitSettable(
missing: Option[Settable[Boolean]], // required if None
vs: SSettable
) extends EmitValue(missing, vs) {
def settableTuple(): IndexedSeq[Settable[_]] = {
missing match {
case Some(m) => vs.settableTuple() :+ m
case None => vs.settableTuple()
}
}
def store(cb: EmitCodeBuilder, ec: EmitCode): Unit = {
store(cb, ec.toI(cb))
}
def store(cb: EmitCodeBuilder, iec: IEmitCode): Unit =
if (required)
cb.assign(vs, iec.get(cb, s"Required EmitSettable cannot be missing ${ vs.st }"))
else
iec.consume(cb, {
cb.assign(missing.get, true)
}, { value =>
cb.assign(missing.get, false)
cb.assign(vs, value)
})
}
class RichIndexedSeqEmitSettable(is: IndexedSeq[EmitSettable]) {
def load(): IndexedSeq[EmitCode] = is.map(_.load)
}
object LoopRef {
def apply(cb: EmitCodeBuilder, L: CodeLabel, args: IndexedSeq[(String, EmitType)], pool: Value[RegionPool], resultType: EmitType): LoopRef = {
val (loopArgs, tmpLoopArgs) = args.zipWithIndex.map { case ((name, et), i) =>
(cb.emb.newEmitField(s"$name$i", et), cb.emb.newEmitField(s"tmp$name$i", et))
}.unzip
val r1: Settable[Region] = cb.newLocal[Region]("loop_ref_r1")
cb.assign(r1, Region.stagedCreate(Region.REGULAR, pool))
val r2: Settable[Region] = cb.newLocal[Region]("loop_ref_r2")
cb.assign(r2, Region.stagedCreate(Region.REGULAR, pool))
new LoopRef(L, args.map(_._2), loopArgs, tmpLoopArgs, r1, r2, resultType)
}
}
class LoopRef(
val L: CodeLabel,
val loopTypes: IndexedSeq[EmitType],
val loopArgs: IndexedSeq[EmitSettable],
val tmpLoopArgs: IndexedSeq[EmitSettable],
val r1: Settable[Region],
val r2: Settable[Region],
val resultType: EmitType)
abstract class EstimableEmitter[C] {
def emit(mb: EmitMethodBuilder[C]): Code[Unit]
def estimatedSize: Int
}
class Emit[C](
val ctx: EmitContext,
val cb: EmitClassBuilder[C]) {
emitSelf =>
val methods: mutable.Map[(String, Seq[Type], Seq[SType], SType), EmitMethodBuilder[C]] = mutable.Map()
def emitVoidInSeparateMethod(context: String, cb: EmitCodeBuilder, ir: IR, region: Value[Region], env: EmitEnv, container: Option[AggContainer], loopEnv: Option[Env[LoopRef]]): Unit = {
assert(!ctx.inLoopCriticalPath.contains(ir))
val mb = cb.emb.genEmitMethod(context, FastIndexedSeq[ParamType](), UnitInfo)
val r = cb.newField[Region]("emitVoidSeparate_region", region)
mb.voidWithBuilder { cb =>
ctx.tryingToSplit.bind(ir, ())
emitVoid(cb, ir, r, env, container, loopEnv)
}
cb.invokeVoid(mb)
}
def emitSplitMethod(context: String, cb: EmitCodeBuilder, ir: IR, region: Value[Region], env: EmitEnv, container: Option[AggContainer], loopEnv: Option[Env[LoopRef]]): (EmitSettable, EmitMethodBuilder[_]) = {
val mb = cb.emb.genEmitMethod(context, FastIndexedSeq[ParamType](), UnitInfo)
val r = cb.newField[Region]("emitInSeparate_region", region)
var ev: EmitSettable = null
mb.voidWithBuilder { cb =>
ctx.tryingToSplit.bind(ir, ())
val result = emitI(ir, cb, r, env, container, loopEnv)
ev = cb.emb.ecb.newEmitField(s"${context}_result", result.emitType)
cb.assign(ev, result)
}
(ev, mb)
}
def emitInSeparateMethod(context: String, cb: EmitCodeBuilder, ir: IR, region: Value[Region], env: EmitEnv, container: Option[AggContainer], loopEnv: Option[Env[LoopRef]]): IEmitCode = {
if (ir.typ == TVoid) {
emitVoidInSeparateMethod(context, cb, ir, region, env, container, loopEnv)
return IEmitCode.present(cb, SVoidValue)
}
assert(!ctx.inLoopCriticalPath.contains(ir))
val (ev, mb) = emitSplitMethod(context, cb, ir, region, env, container, loopEnv)
cb.invokeVoid(mb)
ev.toI(cb)
}
private[ir] def emitVoid(cb: EmitCodeBuilder, ir: IR, region: Value[Region], env: EmitEnv, container: Option[AggContainer], loopEnv: Option[Env[LoopRef]]): Unit = {
if (ctx.methodSplits.contains(ir) && !ctx.tryingToSplit.contains(ir)) {
emitVoidInSeparateMethod(s"split_${ir.getClass.getSimpleName}", cb, ir, region, env, container, loopEnv)
return
}
val mb: EmitMethodBuilder[C] = cb.emb.asInstanceOf[EmitMethodBuilder[C]]
def emit(ir: IR, mb: EmitMethodBuilder[C] = mb, region: Value[Region] = region, env: EmitEnv = env, container: Option[AggContainer] = container, loopEnv: Option[Env[LoopRef]] = loopEnv): EmitCode =
this.emit(ir, mb, region, env, container, loopEnv)
def emitStream(ir: IR, outerRegion: Value[Region], mb: EmitMethodBuilder[C] = mb): EmitCode =
EmitCode.fromI(mb)(cb => EmitStream.produce(this, ir, cb, outerRegion, env, container))
def emitVoid(ir: IR, cb: EmitCodeBuilder = cb, region: Value[Region] = region, env: EmitEnv = env, container: Option[AggContainer] = container, loopEnv: Option[Env[LoopRef]] = loopEnv): Unit =
this.emitVoid(cb, ir, region, env, container, loopEnv)
def emitI(ir: IR, region: Value[Region] = region, env: EmitEnv = env, container: Option[AggContainer] = container, loopEnv: Option[Env[LoopRef]] = loopEnv): IEmitCode =
this.emitI(ir, cb, region, env, container, loopEnv)
(ir: @unchecked) match {
case Literal(TVoid, ()) =>
Code._empty
case Void() =>
Code._empty
case x@Begin(xs) =>
if (!ctx.inLoopCriticalPath.contains(x) && xs.forall(x => !ctx.inLoopCriticalPath.contains(x))) {
xs.grouped(16).zipWithIndex.foreach { case (group, idx) =>
val mb = cb.emb.genEmitMethod(s"begin_group_$idx", FastIndexedSeq[ParamType](classInfo[Region]), UnitInfo)
mb.voidWithBuilder { cb =>
group.foreach(x => emitVoid(x, cb, mb.getCodeParam[Region](1), env, container, loopEnv))
}
cb.invokeVoid(mb, region)
}
} else
xs.foreach(x => emitVoid(x))
case If(cond, cnsq, altr) =>
assert(cnsq.typ == TVoid && altr.typ == TVoid)
emitI(cond).consume(cb, {}, m => cb.ifx(m.asBoolean.value, emitVoid(cnsq), emitVoid(altr)))
case Let(name, value, body) =>
val xVal = if (value.typ.isInstanceOf[TStream]) emitStream(value, region) else emit(value)
cb.withScopedMaybeStreamValue(xVal, s"let_$name") { ev =>
emitVoid(body, env = env.bind(name, ev))
}
case StreamFor(a, valueName, body) =>
emitStream(a, region).toI(cb).consume(cb,
{},
{ case stream: SStreamValue =>
val producer = stream.getProducer(mb)
producer.memoryManagedConsume(region, cb) { cb =>
cb.withScopedMaybeStreamValue(producer.element, s"streamfor_$valueName") { ev =>
emitVoid(body, region = producer.elementRegion, env = env.bind(valueName -> ev))
}
}
})
case x@InitOp(i, args, sig) =>
val AggContainer(aggs, sc, _) = container.get
assert(aggs(i) == sig.state)
val rvAgg = agg.Extract.getAgg(sig)
val argVars = args
.map { a => emit(a, container = container.flatMap(_.nested(i, init = true))) }
.toArray
sc.newState(cb, i)
rvAgg.initOp(cb, sc.states(i), argVars)
case x@SeqOp(i, args, sig) =>
val AggContainer(aggs, sc, _) = container.get
assert(sig.state == aggs(i))
val rvAgg = agg.Extract.getAgg(sig)
val argVars = args
.map { a => emit(a, container = container.flatMap(_.nested(i, init = false))) }
.toArray
rvAgg.seqOp(cb, sc.states(i), argVars)
case x@CombOp(i1, i2, sig) =>
val AggContainer(aggs, sc, _) = container.get
assert(sig.state == aggs(i1) && sig.state == aggs(i2))
val rvAgg = agg.Extract.getAgg(sig)
rvAgg.combOp(ctx.executeContext, cb, sc.states(i1), sc.states(i2))
case x@SerializeAggs(start, sIdx, spec, sigs) =>
val AggContainer(_, sc, _) = container.get
val ob = mb.genFieldThisRef[OutputBuffer]()
val baos = mb.genFieldThisRef[ByteArrayOutputStream]()
cb.assign(baos, Code.newInstance[ByteArrayOutputStream]())
cb.assign(ob, spec.buildCodeOutputBuffer(baos))
Array.range(start, start + sigs.length)
.foreach { idx =>
sc.states(idx).serialize(spec)(cb, ob)
}
cb += ob.invoke[Unit]("flush")
cb += ob.invoke[Unit]("close")
cb += mb.setSerializedAgg(sIdx, baos.invoke[Array[Byte]]("toByteArray"))
case DeserializeAggs(start, sIdx, spec, sigs) =>
val AggContainer(_, sc, _) = container.get
val ib = mb.genFieldThisRef[InputBuffer]()
val ns = sigs.length
val deserializers = sc.states.states
.slice(start, start + ns)
.map(sc => sc.deserialize(BufferSpec.defaultUncompressed))
Array.range(start, start + ns).foreach(i => sc.newState(cb, i))
cb.assign(ib, spec.buildCodeInputBuffer(
Code.newInstance[ByteArrayInputStream, Array[Byte]](
mb.getSerializedAgg(sIdx))))
cb += mb.freeSerializedAgg(sIdx)
(0 until ns).foreach { j =>
deserializers(j)(cb, ib)
}
cb.assign(ib, Code._null[InputBuffer])
case Die(m, typ, errorId) =>
val cm = emitI(m)
val msg = cm.consumeCode(cb, "<exception message missing>", _.asString.loadString(cb))
cb._throw(Code.newInstance[HailException, String, Int](msg, errorId))
case WriteMetadata(annotations, writer) =>
writer.writeMetadata(emitI(annotations), cb, region)
case CombOpValue(i, value, aggSig) =>
val AggContainer(_, sc, _) = container.get
val rvAgg = agg.Extract.getAgg(aggSig)
val tempState = AggStateSig.getState(aggSig.state, mb.ecb)
val aggStateOffset = mb.genFieldThisRef[Long](s"combOpValue_${ i }_state");
val v = emitI(value)
v.consume(cb,
cb._fatal("cannot combOp a missing value"),
{ case serializedValue: SBinaryValue =>
cb.assign(aggStateOffset, region.allocate(tempState.storageType.alignment, tempState.storageType.byteSize))
tempState.createState(cb)
tempState.newState(cb)
tempState.deserializeFromBytes(cb, serializedValue)
rvAgg.combOp(ctx.executeContext, cb, sc.states(i), tempState)
}
)
case InitFromSerializedValue(i, value, sig) =>
val AggContainer(aggs, sc, _) = container.get
assert(aggs(i) == sig)
val v = emitI(value)
v.consume(cb,
cb._fatal("cannot initialize aggs from a missing value"),
{ case serializedValue: SBinaryValue =>
sc.states(i).createState(cb)
sc.newState(cb, i)
sc.states(i).deserializeFromBytes(cb, serializedValue)
}
)
}
}
private[ir] def emitI(ir: IR, cb: EmitCodeBuilder, env: EmitEnv, container: Option[AggContainer]): IEmitCode = {
val region = cb.emb.getCodeParam[Region](1)
emitI(ir, cb, region, env, container, None)
}
private[ir] def emitI(ir: IR, cb: EmitCodeBuilder, region: Value[Region], env: EmitEnv,
container: Option[AggContainer], loopEnv: Option[Env[LoopRef]]
): IEmitCode = {
if (ctx.methodSplits.contains(ir) && !ctx.tryingToSplit.contains(ir)) {
return emitInSeparateMethod(s"split_${ir.getClass.getSimpleName}", cb, ir, region, env, container, loopEnv)
}
val mb: EmitMethodBuilder[C] = cb.emb.asInstanceOf[EmitMethodBuilder[C]]
def emitI(ir: IR, region: Value[Region] = region, env: EmitEnv = env, container: Option[AggContainer] = container, loopEnv: Option[Env[LoopRef]] = loopEnv): IEmitCode =
this.emitI(ir, cb, region, env, container, loopEnv)
def emitInNewBuilder(cb: EmitCodeBuilder, ir: IR, region: Value[Region] = region, env: EmitEnv = env, container: Option[AggContainer] = container, loopEnv: Option[Env[LoopRef]] = loopEnv): IEmitCode =
this.emitI(ir, cb, region, env, container, loopEnv)
def emitStream(ir: IR, cb: EmitCodeBuilder, outerRegion: Value[Region]): IEmitCode =
EmitStream.produce(this, ir, cb, outerRegion, env, container)
def emitVoid(ir: IR, env: EmitEnv = env, container: Option[AggContainer] = container, loopEnv: Option[Env[LoopRef]] = loopEnv): Unit =
this.emitVoid(cb, ir: IR, region, env, container, loopEnv)
def emitFallback(ir: IR, env: EmitEnv = env, container: Option[AggContainer] = container, loopEnv: Option[Env[LoopRef]] = loopEnv): IEmitCode =
this.emit(ir, mb, region, env, container, loopEnv, fallingBackFromEmitI = true).toI(cb)
def emitDeforestedNDArrayI(ir: IR): IEmitCode = EmitNDArray(this, ir, cb, region, env, container, loopEnv)
def emitNDArrayColumnMajorStrides(ir: IR): IEmitCode = {
emitI(ir).map(cb) { case pNDValue: SNDArrayValue =>
LinalgCodeUtils.checkColMajorAndCopyIfNeeded(pNDValue, cb, region)
}
}
// Returns an IEmitCode along with a Boolean that is true if the returned value is column major. If false it's row
// major instead.
def emitNDArrayStandardStriding(ir: IR): IEmitCodeGen[(SNDArrayValue, Value[Boolean])] = {
emitI(ir).map(cb) { case pNDValue: SNDArrayValue =>
LinalgCodeUtils.checkStandardStriding(pNDValue, cb, region)
}
}
def typeWithReqx(node: IR): VirtualTypeWithReq = VirtualTypeWithReq(node.typ, ctx.req.lookup(node).asInstanceOf[TypeWithRequiredness])
def typeWithReq: VirtualTypeWithReq = typeWithReqx(ir)
if (ir.typ == TVoid) {
emitVoid(ir)
return IEmitCode.present(cb, SVoidValue)
}
def presentPC(pc: SValue): IEmitCode = IEmitCode.present(cb, pc)
val result: IEmitCode = (ir: @unchecked) match {
case In(i, expectedPType) =>
val ev = env.inputValues(i)
ev.toI(cb)
case I32(x) =>
presentPC(primitive(const(x)))
case I64(x) =>
presentPC(primitive(const(x)))
case F32(x) =>
presentPC(primitive(const(x)))
case F64(x) =>
presentPC(primitive(const(x)))
case s@Str(x) =>
presentPC(mb.addLiteral(x, typeWithReq))
case x@UUID4(_) =>
val pt = PCanonicalString()
presentPC(pt.loadCheapSCode(cb, pt.
allocateAndStoreString(cb, region, Code.invokeScalaObject0[String](
Class.forName("is.hail.expr.ir.package$"), "uuid4"))))
case x@Literal(t, v) =>
presentPC(mb.addLiteral(v, typeWithReq))
case x@EncodedLiteral(codec, value) =>
presentPC(mb.addEncodedLiteral(x))
case True() =>
presentPC(primitive(const(true)))
case False() =>
presentPC(primitive(const(false)))
case Consume(value) =>
emitI(value).map(cb) { pc =>
// Ignore pc, just return a 1
primitive(const(1L))
}
case Cast(v, typ) =>
val iec = emitI(v)
val cast = Casts.get(v.typ, typ)
iec.map(cb)(pc => cast(cb, pc))
case CastRename(v, _typ) =>
emitI(v)
.map(cb)(pc => pc.st.castRename(_typ).fromValues(pc.valueTuple))
case NA(typ) =>
IEmitCode.missing(cb, SUnreachable.fromVirtualType(typ).defaultValue)
case IsNA(v) =>
val m = emitI(v).consumeCode(cb, true, _ => false)
presentPC(primitive(m))
case Coalesce(values) =>
val emittedValues = values.map(v => EmitCode.fromI(cb.emb)(cb => emitInNewBuilder(cb, v)))
val unifiedType = SType.chooseCompatibleType(typeWithReq, emittedValues.map(_.st): _*)
val coalescedValue = mb.newPLocal("coalesce_value", unifiedType)
val Ldefined = CodeLabel()
val Lmissing = CodeLabel()
emittedValues.foreach { value =>
value.toI(cb).consume(cb,
{}, // fall through to next check
{ sc =>
cb.assign(coalescedValue, sc.castTo(cb, region, unifiedType))
cb.goto(Ldefined)
})
}
cb.goto(Lmissing)
IEmitCode(Lmissing, Ldefined, coalescedValue, emittedValues.exists(_.required))
case If(cond, cnsq, altr) =>
assert(cnsq.typ == altr.typ)
emitI(cond).flatMap(cb) { case condValue: SBooleanValue =>
val codeCnsq = EmitCode.fromI(cb.emb)(cb => emitInNewBuilder(cb, cnsq))
val codeAltr = EmitCode.fromI(cb.emb)(cb => emitInNewBuilder(cb, altr))
val outType = SType.chooseCompatibleType(typeWithReq, codeCnsq.st, codeAltr.st)
val Lmissing = CodeLabel()
val Ldefined = CodeLabel()
val out = mb.newPLocal(outType)
cb.ifx(condValue.value, {
codeCnsq.toI(cb).consume(cb,
{
cb.goto(Lmissing)
}, { sc =>
cb.assign(out, sc.castTo(cb, region, outType))
})
}, {
codeAltr.toI(cb).consume(cb,
{
cb.goto(Lmissing)
}, { sc =>
cb.assign(out, sc.castTo(cb, region, outType))
})
})
cb.goto(Ldefined)
IEmitCode(Lmissing, Ldefined, out, codeCnsq.required && codeAltr.required)
}
case x@MakeStruct(fields) =>
presentPC(SStackStruct.constructFromArgs(cb, region, x.typ.asInstanceOf[TBaseStruct],
fields.map { case (_, x) =>
EmitCode.fromI(cb.emb)(cb => emitInNewBuilder(cb, x))
}: _*
))
case x@MakeTuple(fields) =>
presentPC(SStackStruct.constructFromArgs(cb, region, x.typ.asInstanceOf[TBaseStruct],
fields.map { case (_, x) =>
EmitCode.fromI(cb.emb)(cb => emitInNewBuilder(cb, x))
}: _*
))
case SelectFields(oldStruct, fields) =>
emitI(oldStruct).map(cb) { _.asBaseStruct.subset(fields: _*) }
case x@InsertFields(old, fields, _) =>
if (fields.isEmpty)
emitI(old)
else {
emitI(old).map(cb) { case old: SBaseStructValue =>
val newFields = fields.map { case (name, x) =>
(name, cb.memoize(EmitCode.fromI(cb.emb)(cb => emitInNewBuilder(cb, x)), "InsertFields"))
}
old.insert(cb, region, x.typ, newFields: _*)
}
}
case ApplyBinaryPrimOp(op, l, r) =>
emitI(l).flatMap(cb) { pcL =>
emitI(r).map(cb)(pcR => BinaryOp.emit(cb, op, pcL, pcR))
}
case ApplyUnaryPrimOp(op, x) =>
emitI(x).map(cb)(pc => UnaryOp.emit(cb, op, pc))
case ApplyComparisonOp(op, l, r) =>
if (op.strict) {
emitI(l).flatMap(cb) { l =>
emitI(r).map(cb) { r =>
val f = op.codeOrdering(cb.emb.ecb, l.st, r.st)
primitive(ir.typ, f(cb, EmitValue.present(l), EmitValue.present(r)))
}
}
} else {
val lc = emitI(l).memoize(cb, "l")
val rc = emitI(r).memoize(cb, "r")
val f = op.codeOrdering(cb.emb.ecb, lc.st, rc.st)
presentPC(primitive(ir.typ, f(cb, lc, rc)))
}
case x@MakeArray(args, _) =>
val emittedArgs = args.map(a => EmitCode.fromI(mb)(cb => emitInNewBuilder(cb, a)))
val pType = typeWithReq.canonicalPType.asInstanceOf[PCanonicalArray]
val (pushElement, finish) = pType.constructFromFunctions(cb, region, args.size, deepCopy = false)
for (arg <- emittedArgs) {
pushElement(cb, arg.toI(cb))
}
presentPC(finish(cb))