/
AccumulatorCompiler.java
810 lines (721 loc) · 37 KB
/
AccumulatorCompiler.java
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
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.aggregation;
import com.facebook.presto.byteCode.Block;
import com.facebook.presto.byteCode.ByteCodeNode;
import com.facebook.presto.byteCode.ClassDefinition;
import com.facebook.presto.byteCode.CompilerContext;
import com.facebook.presto.byteCode.DynamicClassLoader;
import com.facebook.presto.byteCode.FieldDefinition;
import com.facebook.presto.byteCode.MethodDefinition;
import com.facebook.presto.byteCode.NamedParameterDefinition;
import com.facebook.presto.byteCode.Variable;
import com.facebook.presto.byteCode.control.ForLoop;
import com.facebook.presto.byteCode.control.IfStatement;
import com.facebook.presto.operator.GroupByIdBlock;
import com.facebook.presto.operator.aggregation.state.AccumulatorStateFactory;
import com.facebook.presto.operator.aggregation.state.AccumulatorStateSerializer;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.gen.CallSiteBinder;
import com.facebook.presto.sql.gen.CompilerOperations;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import javax.annotation.Nullable;
import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import static com.facebook.presto.byteCode.Access.FINAL;
import static com.facebook.presto.byteCode.Access.PRIVATE;
import static com.facebook.presto.byteCode.Access.PUBLIC;
import static com.facebook.presto.byteCode.Access.a;
import static com.facebook.presto.byteCode.NamedParameterDefinition.arg;
import static com.facebook.presto.byteCode.OpCode.NOP;
import static com.facebook.presto.byteCode.ParameterizedType.type;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.NULLABLE_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.countInputChannels;
import static com.facebook.presto.sql.gen.ByteCodeUtils.invoke;
import static com.facebook.presto.sql.gen.CompilerUtils.defineClass;
import static com.facebook.presto.sql.gen.CompilerUtils.makeClassName;
import static com.facebook.presto.sql.gen.SqlTypeByteCodeExpression.constantType;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
public class AccumulatorCompiler
{
public GenericAccumulatorFactoryBinder generateAccumulatorFactoryBinder(AggregationMetadata metadata, DynamicClassLoader classLoader)
{
Class<? extends Accumulator> accumulatorClass = generateAccumulatorClass(
Accumulator.class,
metadata,
classLoader);
Class<? extends GroupedAccumulator> groupedAccumulatorClass = generateAccumulatorClass(
GroupedAccumulator.class,
metadata,
classLoader);
return new GenericAccumulatorFactoryBinder(
metadata.getStateSerializer(),
metadata.getStateFactory(),
accumulatorClass,
groupedAccumulatorClass,
metadata.isApproximate());
}
private static <T> Class<? extends T> generateAccumulatorClass(
Class<T> accumulatorInterface,
AggregationMetadata metadata,
DynamicClassLoader classLoader)
{
boolean grouped = accumulatorInterface == GroupedAccumulator.class;
boolean approximate = metadata.isApproximate();
ClassDefinition definition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName(metadata.getName() + accumulatorInterface.getSimpleName()),
type(Object.class),
type(accumulatorInterface));
CallSiteBinder callSiteBinder = new CallSiteBinder();
AccumulatorStateSerializer<?> stateSerializer = metadata.getStateSerializer();
AccumulatorStateFactory<?> stateFactory = metadata.getStateFactory();
FieldDefinition stateSerializerField = definition.declareField(a(PRIVATE, FINAL), "stateSerializer", AccumulatorStateSerializer.class);
FieldDefinition stateFactoryField = definition.declareField(a(PRIVATE, FINAL), "stateFactory", AccumulatorStateFactory.class);
FieldDefinition inputChannelsField = definition.declareField(a(PRIVATE, FINAL), "inputChannels", type(List.class, Integer.class));
FieldDefinition maskChannelField = definition.declareField(a(PRIVATE, FINAL), "maskChannel", type(Optional.class, Integer.class));
FieldDefinition sampleWeightChannelField = null;
FieldDefinition confidenceField = null;
if (approximate) {
sampleWeightChannelField = definition.declareField(a(PRIVATE, FINAL), "sampleWeightChannel", type(Optional.class, Integer.class));
confidenceField = definition.declareField(a(PRIVATE, FINAL), "confidence", double.class);
}
FieldDefinition stateField = definition.declareField(a(PRIVATE, FINAL), "state", grouped ? stateFactory.getGroupedStateClass() : stateFactory.getSingleStateClass());
// Generate constructor
generateConstructor(
definition,
stateSerializerField,
stateFactoryField,
inputChannelsField,
maskChannelField,
sampleWeightChannelField,
confidenceField,
stateField,
grouped);
// Generate methods
generateAddInput(definition, stateField, inputChannelsField, maskChannelField, sampleWeightChannelField, metadata.getInputMetadata(), metadata.getInputFunction(), callSiteBinder, grouped);
generateGetEstimatedSize(definition, stateField);
generateGetIntermediateType(definition, callSiteBinder, stateSerializer.getSerializedType());
generateGetFinalType(definition, callSiteBinder, metadata.getOutputType());
if (metadata.getIntermediateInputFunction() == null) {
generateAddIntermediateAsCombine(definition, stateField, stateSerializerField, stateFactoryField, metadata.getCombineFunction(), stateFactory.getSingleStateClass(), callSiteBinder, grouped);
}
else {
generateAddIntermediateAsIntermediateInput(definition, stateField, metadata.getIntermediateInputMetadata(), metadata.getIntermediateInputFunction(), callSiteBinder, grouped);
}
if (grouped) {
generateGroupedEvaluateIntermediate(definition, stateSerializerField, stateField);
}
else {
generateEvaluateIntermediate(definition, stateSerializerField, stateField);
}
if (grouped) {
generateGroupedEvaluateFinal(definition, confidenceField, stateSerializerField, stateField, metadata.getOutputFunction(), metadata.isApproximate(), callSiteBinder);
}
else {
generateEvaluateFinal(definition, confidenceField, stateSerializerField, stateField, metadata.getOutputFunction(), metadata.isApproximate(), callSiteBinder);
}
return defineClass(definition, accumulatorInterface, callSiteBinder.getBindings(), classLoader);
}
private static MethodDefinition generateGetIntermediateType(ClassDefinition definition, CallSiteBinder callSiteBinder, Type type)
{
MethodDefinition methodDefinition = definition.declareMethod(a(PUBLIC), "getIntermediateType", type(Type.class));
methodDefinition.getBody()
.append(constantType(new CompilerContext(), callSiteBinder, type))
.retObject();
return methodDefinition;
}
private static MethodDefinition generateGetFinalType(ClassDefinition definition, CallSiteBinder callSiteBinder, Type type)
{
MethodDefinition methodDefinition = definition.declareMethod(a(PUBLIC), "getFinalType", type(Type.class));
methodDefinition.getBody()
.append(constantType(new CompilerContext(), callSiteBinder, type))
.retObject();
return methodDefinition;
}
private static void generateGetEstimatedSize(ClassDefinition definition, FieldDefinition stateField)
{
definition.declareMethod(a(PUBLIC), "getEstimatedSize", type(long.class))
.getBody()
.pushThis()
.getField(stateField)
.invokeVirtual(stateField.getType(), "getEstimatedSize", type(long.class))
.retLong();
}
private static void generateAddInput(
ClassDefinition definition,
FieldDefinition stateField,
FieldDefinition inputChannelsField,
FieldDefinition maskChannelField,
@Nullable FieldDefinition sampleWeightChannelField,
List<ParameterMetadata> parameterMetadatas,
MethodHandle inputFunction,
CallSiteBinder callSiteBinder,
boolean grouped)
{
CompilerContext context = new CompilerContext();
ImmutableList.Builder<NamedParameterDefinition> parameters = ImmutableList.builder();
if (grouped) {
parameters.add(arg("groupIdsBlock", GroupByIdBlock.class));
}
parameters.add(arg("page", Page.class));
Block body = definition.declareMethod(context, a(PUBLIC), "addInput", type(void.class), parameters.build())
.getBody();
if (grouped) {
generateEnsureCapacity(stateField, body);
}
List<Variable> parameterVariables = new ArrayList<>();
for (int i = 0; i < countInputChannels(parameterMetadatas); i++) {
parameterVariables.add(context.declareVariable(com.facebook.presto.spi.block.Block.class, "block" + i));
}
Variable masksBlock = context.declareVariable(com.facebook.presto.spi.block.Block.class, "masksBlock");
Variable sampleWeightsBlock = null;
if (sampleWeightChannelField != null) {
sampleWeightsBlock = context.declareVariable(com.facebook.presto.spi.block.Block.class, "sampleWeightsBlock");
}
body.comment("masksBlock = maskChannel.map(page.blockGetter()).orElse(null);")
.pushThis()
.getField(maskChannelField)
.getVariable("page")
.invokeStatic(type(AggregationUtils.class), "pageBlockGetter", type(Function.class, Integer.class, com.facebook.presto.spi.block.Block.class), type(Page.class))
.invokeVirtual(Optional.class, "map", Optional.class, Function.class)
.pushNull()
.invokeVirtual(Optional.class, "orElse", Object.class, Object.class)
.checkCast(com.facebook.presto.spi.block.Block.class)
.putVariable(masksBlock);
if (sampleWeightChannelField != null) {
body.comment("sampleWeightsBlock = sampleWeightChannel.map(page.blockGetter()).get();")
.pushThis()
.getField(sampleWeightChannelField)
.getVariable("page")
.invokeStatic(type(AggregationUtils.class), "pageBlockGetter", type(Function.class, Integer.class, com.facebook.presto.spi.block.Block.class), type(Page.class))
.invokeVirtual(Optional.class, "map", Optional.class, Function.class)
.invokeVirtual(Optional.class, "get", Object.class)
.checkCast(com.facebook.presto.spi.block.Block.class)
.putVariable(sampleWeightsBlock);
}
// Get all parameter blocks
for (int i = 0; i < countInputChannels(parameterMetadatas); i++) {
body.comment("%s = page.getBlock(inputChannels.get(%d));", parameterVariables.get(i).getName(), i)
.getVariable("page")
.pushThis()
.getField(inputChannelsField)
.push(i)
.invokeInterface(List.class, "get", Object.class, int.class)
.checkCast(Integer.class)
.invokeVirtual(Integer.class, "intValue", int.class)
.invokeVirtual(Page.class, "getBlock", com.facebook.presto.spi.block.Block.class, int.class)
.putVariable(parameterVariables.get(i));
}
Block block = generateInputForLoop(stateField, parameterMetadatas, inputFunction, context, parameterVariables, masksBlock, sampleWeightsBlock, callSiteBinder, grouped);
body.append(block)
.ret();
}
private static Block generateInputForLoop(
FieldDefinition stateField,
List<ParameterMetadata> parameterMetadatas,
MethodHandle inputFunction,
CompilerContext context,
List<Variable> parameterVariables,
Variable masksBlock,
@Nullable Variable sampleWeightsBlock,
CallSiteBinder callSiteBinder,
boolean grouped)
{
// For-loop over rows
Variable positionVariable = context.declareVariable(int.class, "position");
Variable sampleWeightVariable = null;
if (sampleWeightsBlock != null) {
sampleWeightVariable = context.declareVariable(long.class, "sampleWeight");
}
Variable rowsVariable = context.declareVariable(int.class, "rows");
Block block = new Block(context)
.getVariable("page")
.invokeVirtual(Page.class, "getPositionCount", int.class)
.putVariable(rowsVariable)
.initializeVariable(positionVariable);
if (sampleWeightVariable != null) {
block.initializeVariable(sampleWeightVariable);
}
ByteCodeNode loopBody = generateInvokeInputFunction(context, stateField, positionVariable, sampleWeightVariable, parameterVariables, parameterMetadatas, inputFunction, callSiteBinder, grouped);
// Wrap with null checks
List<Boolean> nullable = new ArrayList<>();
for (ParameterMetadata metadata : parameterMetadatas) {
if (metadata.getParameterType() == INPUT_CHANNEL) {
nullable.add(false);
}
else if (metadata.getParameterType() == NULLABLE_INPUT_CHANNEL) {
nullable.add(true);
}
}
checkState(nullable.size() == parameterVariables.size(), "Number of parameters does not match");
for (int i = 0; i < parameterVariables.size(); i++) {
if (!nullable.get(i)) {
Variable variableDefinition = parameterVariables.get(i);
loopBody = new IfStatement("if(!%s.isNull(position))", variableDefinition.getName())
.condition(new Block(context)
.getVariable(variableDefinition)
.getVariable(positionVariable)
.invokeInterface(com.facebook.presto.spi.block.Block.class, "isNull", boolean.class, int.class))
.ifFalse(loopBody);
}
}
// Check that sample weight is > 0 (also checks the mask)
if (sampleWeightVariable != null) {
loopBody = generateComputeSampleWeightAndCheckGreaterThanZero(context, loopBody, sampleWeightVariable, masksBlock, sampleWeightsBlock, positionVariable);
}
// Otherwise just check the mask
else {
loopBody = new IfStatement("if(testMask(%s, position))", masksBlock.getName())
.condition(new Block(context)
.getVariable(masksBlock)
.getVariable(positionVariable)
.invokeStatic(CompilerOperations.class, "testMask", boolean.class, com.facebook.presto.spi.block.Block.class, int.class))
.ifTrue(loopBody);
}
block.append(new ForLoop()
.initialize(new Block(context).putVariable(positionVariable, 0))
.condition(new Block(context)
.getVariable(positionVariable)
.getVariable(rowsVariable)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class))
.update(new Block(context).incrementVariable(positionVariable, (byte) 1))
.body(loopBody));
return block;
}
private static ByteCodeNode generateComputeSampleWeightAndCheckGreaterThanZero(CompilerContext context, ByteCodeNode body, Variable sampleWeight, Variable masks, Variable sampleWeights, Variable position)
{
Block block = new Block(context)
.comment("sampleWeight = computeSampleWeight(masks, sampleWeights, position);")
.getVariable(masks)
.getVariable(sampleWeights)
.getVariable(position)
.invokeStatic(ApproximateUtils.class, "computeSampleWeight", long.class, com.facebook.presto.spi.block.Block.class, com.facebook.presto.spi.block.Block.class, int.class)
.putVariable(sampleWeight);
block.append(new IfStatement("if(sampleWeight > 0)")
.condition(new Block(context)
.getVariable(sampleWeight)
.invokeStatic(CompilerOperations.class, "longGreaterThanZero", boolean.class, long.class))
.ifTrue(body)
.ifFalse(NOP));
return block;
}
private static Block generateInvokeInputFunction(
CompilerContext context,
FieldDefinition stateField,
Variable position,
@Nullable Variable sampleWeight,
List<Variable> parameterVariables,
List<ParameterMetadata> parameterMetadatas,
MethodHandle inputFunction,
CallSiteBinder callSiteBinder,
boolean grouped)
{
Block block = new Block(context);
if (grouped) {
generateSetGroupIdFromGroupIdsBlock(stateField, position, block);
}
block.comment("Call input function with unpacked Block arguments");
Class<?>[] parameters = inputFunction.type().parameterArray();
int inputChannel = 0;
for (int i = 0; i < parameters.length; i++) {
ParameterMetadata parameterMetadata = parameterMetadatas.get(i);
switch (parameterMetadata.getParameterType()) {
case STATE:
block.pushThis().getField(stateField);
break;
case BLOCK_INDEX:
block.getVariable(position);
break;
case SAMPLE_WEIGHT:
checkNotNull(sampleWeight, "sampleWeight is null");
block.getVariable(sampleWeight);
break;
case NULLABLE_INPUT_CHANNEL:
block.getVariable(parameterVariables.get(inputChannel));
inputChannel++;
break;
case INPUT_CHANNEL:
Block getBlockByteCode = new Block(context)
.getVariable(parameterVariables.get(inputChannel));
pushStackType(block, parameterMetadata.getSqlType(), getBlockByteCode, parameters[i], callSiteBinder);
inputChannel++;
break;
default:
throw new IllegalArgumentException("Unsupported parameter type: " + parameterMetadata.getParameterType());
}
}
block.append(invoke(context, callSiteBinder.bind(inputFunction), "input"));
return block;
}
// Assumes that there is a variable named 'position' in the block, which is the current index
private static void pushStackType(Block block, Type sqlType, Block getBlockByteCode, Class<?> parameter, CallSiteBinder callSiteBinder)
{
if (parameter == com.facebook.presto.spi.block.Block.class) {
block.append(getBlockByteCode);
}
else if (parameter == long.class) {
block.comment("%s.getLong(block, position)", sqlType.getTypeSignature())
.append(constantType(new CompilerContext(), callSiteBinder, sqlType))
.append(getBlockByteCode)
.getVariable("position")
.invokeInterface(Type.class, "getLong", long.class, com.facebook.presto.spi.block.Block.class, int.class);
}
else if (parameter == double.class) {
block.comment("%s.getDouble(block, position)", sqlType.getTypeSignature())
.append(constantType(new CompilerContext(), callSiteBinder, sqlType))
.append(getBlockByteCode)
.getVariable("position")
.invokeInterface(Type.class, "getDouble", double.class, com.facebook.presto.spi.block.Block.class, int.class);
}
else if (parameter == boolean.class) {
block.comment("%s.getBoolean(block, position)", sqlType.getTypeSignature())
.append(constantType(new CompilerContext(), callSiteBinder, sqlType))
.append(getBlockByteCode)
.getVariable("position")
.invokeInterface(Type.class, "getBoolean", boolean.class, com.facebook.presto.spi.block.Block.class, int.class);
}
else if (parameter == Slice.class) {
block.comment("%s.getBoolean(block, position)", sqlType.getTypeSignature())
.append(constantType(new CompilerContext(), callSiteBinder, sqlType))
.append(getBlockByteCode)
.getVariable("position")
.invokeInterface(Type.class, "getSlice", Slice.class, com.facebook.presto.spi.block.Block.class, int.class);
}
else {
throw new IllegalArgumentException("Unsupported parameter type: " + parameter.getSimpleName());
}
}
private static void generateAddIntermediateAsCombine(
ClassDefinition definition,
FieldDefinition stateField,
FieldDefinition stateSerializerField,
FieldDefinition stateFactoryField,
MethodHandle combineFunction,
Class<?> singleStateClass,
CallSiteBinder callSiteBinder,
boolean grouped)
{
CompilerContext context = new CompilerContext();
Block body = declareAddIntermediate(definition, grouped, context);
Variable scratchStateVariable = context.declareVariable(singleStateClass, "scratchState");
Variable positionVariable = context.declareVariable(int.class, "position");
body.comment("scratchState = stateFactory.createSingleState();")
.pushThis()
.getField(stateFactoryField)
.invokeInterface(AccumulatorStateFactory.class, "createSingleState", Object.class)
.checkCast(scratchStateVariable.getType())
.putVariable(scratchStateVariable);
if (grouped) {
generateEnsureCapacity(stateField, body);
}
Block loopBody = new Block(context);
if (grouped) {
generateSetGroupIdFromGroupIdsBlock(stateField, positionVariable, loopBody);
}
loopBody.comment("stateSerializer.deserialize(block, position, scratchState)")
.pushThis()
.getField(stateSerializerField)
.getVariable("block")
.getVariable(positionVariable)
.getVariable(scratchStateVariable)
.invokeInterface(AccumulatorStateSerializer.class, "deserialize", void.class, com.facebook.presto.spi.block.Block.class, int.class, Object.class);
loopBody.comment("combine(state, scratchState)")
.pushThis()
.getField(stateField)
.getVariable("scratchState")
.append(invoke(context, callSiteBinder.bind(combineFunction), "combine"));
body.append(generateBlockNonNullPositionForLoop(context, positionVariable, loopBody))
.ret();
}
private static void generateSetGroupIdFromGroupIdsBlock(FieldDefinition stateField, Variable positionVariable, Block block)
{
block.comment("state.setGroupId(groupIdsBlock.getGroupId(position))")
.pushThis()
.getField(stateField)
.getVariable("groupIdsBlock")
.getVariable(positionVariable)
.invokeVirtual(GroupByIdBlock.class, "getGroupId", long.class, int.class)
.invokeVirtual(stateField.getType(), "setGroupId", type(void.class), type(long.class));
}
private static void generateEnsureCapacity(FieldDefinition stateField, Block block)
{
block.comment("state.ensureCapacity(groupIdsBlock.getGroupCount())")
.pushThis()
.getField(stateField)
.getVariable("groupIdsBlock")
.invokeVirtual(GroupByIdBlock.class, "getGroupCount", long.class)
.invokeVirtual(stateField.getType(), "ensureCapacity", type(void.class), type(long.class));
}
private static Block declareAddIntermediate(ClassDefinition definition, boolean grouped, CompilerContext context)
{
ImmutableList.Builder<NamedParameterDefinition> parameters = ImmutableList.builder();
if (grouped) {
parameters.add(arg("groupIdsBlock", GroupByIdBlock.class));
}
parameters.add(arg("block", com.facebook.presto.spi.block.Block.class));
return definition.declareMethod(
context,
a(PUBLIC),
"addIntermediate",
type(void.class),
parameters.build())
.getBody();
}
private static void generateAddIntermediateAsIntermediateInput(
ClassDefinition definition,
FieldDefinition stateField,
List<ParameterMetadata> parameterMetadatas,
MethodHandle intermediateInputFunction,
CallSiteBinder callSiteBinder,
boolean grouped)
{
CompilerContext context = new CompilerContext();
Block body = declareAddIntermediate(definition, grouped, context);
if (grouped) {
generateEnsureCapacity(stateField, body);
}
Variable positionVariable = context.declareVariable(int.class, "position");
Block loopBody = generateInvokeInputFunction(context, stateField, positionVariable, null, ImmutableList.of(context.getVariable("block")), parameterMetadatas, intermediateInputFunction, callSiteBinder, grouped);
body.append(generateBlockNonNullPositionForLoop(context, positionVariable, loopBody))
.ret();
}
// Generates a for-loop with a local variable named "position" defined, with the current position in the block,
// loopBody will only be executed for non-null positions in the Block
private static Block generateBlockNonNullPositionForLoop(CompilerContext context, Variable positionVariable, Block loopBody)
{
Variable rowsVariable = context.declareVariable(int.class, "rows");
Block block = new Block(context)
.getVariable("block")
.invokeInterface(com.facebook.presto.spi.block.Block.class, "getPositionCount", int.class)
.putVariable(rowsVariable);
IfStatement ifStatement = new IfStatement("if(!block.isNull(position))")
.condition(new Block(context)
.getVariable("block")
.getVariable(positionVariable)
.invokeInterface(com.facebook.presto.spi.block.Block.class, "isNull", boolean.class, int.class))
.ifFalse(loopBody);
block.append(new ForLoop()
.initialize(new Block(context).putVariable(positionVariable, 0))
.condition(new Block(context)
.getVariable(positionVariable)
.getVariable(rowsVariable)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class))
.update(new Block(context).incrementVariable(positionVariable, (byte) 1))
.body(ifStatement));
return block;
}
private static void generateGroupedEvaluateIntermediate(ClassDefinition definition, FieldDefinition stateSerializerField, FieldDefinition stateField)
{
definition.declareMethod(
a(PUBLIC),
"evaluateIntermediate",
type(void.class),
arg("groupId", int.class),
arg("out", BlockBuilder.class))
.getBody()
.comment("state.setGroupId(groupId)")
.pushThis()
.getField(stateField)
.getVariable("groupId")
.intToLong()
.invokeVirtual(stateField.getType(), "setGroupId", type(void.class), type(long.class))
.comment("stateSerializer.serialize(state, out)")
.pushThis()
.getField(stateSerializerField)
.pushThis()
.getField(stateField)
.getVariable("out")
.invokeInterface(AccumulatorStateSerializer.class, "serialize", void.class, Object.class, BlockBuilder.class)
.ret();
}
private static void generateEvaluateIntermediate(ClassDefinition definition, FieldDefinition stateSerializerField, FieldDefinition stateField)
{
CompilerContext context = new CompilerContext();
definition.declareMethod(
context,
a(PUBLIC),
"evaluateIntermediate",
type(void.class),
arg("out", BlockBuilder.class))
.getBody()
.comment("stateSerializer.serialize(state, out)")
.pushThis()
.getField(stateSerializerField)
.pushThis()
.getField(stateField)
.getVariable("out")
.invokeInterface(AccumulatorStateSerializer.class, "serialize", void.class, Object.class, BlockBuilder.class)
.ret();
}
private static void generateGroupedEvaluateFinal(
ClassDefinition definition,
FieldDefinition confidenceField,
FieldDefinition stateSerializerField,
FieldDefinition stateField,
@Nullable MethodHandle outputFunction,
boolean approximate,
CallSiteBinder callSiteBinder)
{
CompilerContext context = new CompilerContext();
Block body = definition.declareMethod(
a(PUBLIC),
"evaluateFinal",
type(void.class),
arg("groupId", int.class),
arg("out", BlockBuilder.class))
.getBody()
.comment("state.setGroupId(groupId)")
.pushThis()
.getField(stateField)
.getVariable("groupId")
.intToLong()
.invokeVirtual(stateField.getType(), "setGroupId", type(void.class), type(long.class));
if (outputFunction != null) {
body.comment("output(state, out)")
.pushThis()
.getField(stateField);
if (approximate) {
checkNotNull(confidenceField, "confidenceField is null");
body.pushThis().getField(confidenceField);
}
body.getVariable("out")
.append(invoke(context, callSiteBinder.bind(outputFunction), "output"));
}
else {
checkArgument(!approximate, "Approximate aggregations must specify an output function");
body.comment("stateSerializer.serialize(state, out)")
.pushThis()
.getField(stateSerializerField)
.pushThis()
.getField(stateField)
.getVariable("out")
.invokeInterface(AccumulatorStateSerializer.class, "serialize", void.class, Object.class, BlockBuilder.class);
}
body.ret();
}
private static void generateEvaluateFinal(
ClassDefinition definition,
FieldDefinition confidenceField,
FieldDefinition stateSerializerField,
FieldDefinition stateField,
@Nullable
MethodHandle outputFunction,
boolean approximate,
CallSiteBinder callSiteBinder)
{
CompilerContext context = new CompilerContext();
Block body = definition.declareMethod(
a(PUBLIC),
"evaluateFinal",
type(void.class),
arg("out", BlockBuilder.class))
.getBody();
if (outputFunction != null) {
body.comment("output(state, out)")
.pushThis()
.getField(stateField);
if (approximate) {
checkNotNull(confidenceField, "confidenceField is null");
body.pushThis().getField(confidenceField);
}
body.getVariable("out")
.append(invoke(context, callSiteBinder.bind(outputFunction), "output"));
}
else {
checkArgument(!approximate, "Approximate aggregations must specify an output function");
body.comment("stateSerializer.serialize(state, out)")
.pushThis()
.getField(stateSerializerField)
.pushThis()
.getField(stateField)
.getVariable("out")
.invokeInterface(AccumulatorStateSerializer.class, "serialize", void.class, Object.class, BlockBuilder.class);
}
body.ret();
}
private static void generateConstructor(
ClassDefinition definition,
FieldDefinition stateSerializerField,
FieldDefinition stateFactoryField,
FieldDefinition inputChannelsField,
FieldDefinition maskChannelField,
@Nullable FieldDefinition sampleWeightChannelField,
@Nullable FieldDefinition confidenceField,
FieldDefinition stateField,
boolean grouped)
{
Block body = definition.declareConstructor(
a(PUBLIC),
arg("stateSerializer", AccumulatorStateSerializer.class),
arg("stateFactory", AccumulatorStateFactory.class),
arg("inputChannels", type(List.class, Integer.class)),
arg("maskChannel", type(Optional.class, Integer.class)),
arg("sampleWeightChannel", type(Optional.class, Integer.class)),
arg("confidence", double.class))
.getBody()
.comment("super();")
.pushThis()
.invokeConstructor(Object.class);
generateCastCheckNotNullAndAssign(body, stateSerializerField, "stateSerializer");
generateCastCheckNotNullAndAssign(body, stateFactoryField, "stateFactory");
generateCastCheckNotNullAndAssign(body, inputChannelsField, "inputChannels");
generateCastCheckNotNullAndAssign(body, maskChannelField, "maskChannel");
if (sampleWeightChannelField != null) {
generateCastCheckNotNullAndAssign(body, sampleWeightChannelField, "sampleWeightChannel");
}
String createState;
if (grouped) {
createState = "createGroupedState";
}
else {
createState = "createSingleState";
}
if (confidenceField != null) {
body.comment("this.confidence = confidence")
.pushThis()
.getVariable("confidence")
.putField(confidenceField);
}
body.comment("this.state = stateFactory.%s()", createState)
.pushThis()
.getVariable("stateFactory")
.invokeInterface(AccumulatorStateFactory.class, createState, Object.class)
.checkCast(stateField.getType())
.putField(stateField)
.ret();
}
private static void generateCastCheckNotNullAndAssign(Block block, FieldDefinition field, String variableName)
{
block.comment("this.%s = checkNotNull(%s, \"%s is null\"", field.getName(), variableName, variableName)
.pushThis()
.getVariable(variableName)
.checkCast(field.getType())
.push(variableName + " is null")
.invokeStatic(Preconditions.class, "checkNotNull", Object.class, Object.class, Object.class)
.checkCast(field.getType())
.putField(field);
}
}