Search in sources :

Example 1 with CommonSubExpressionFields

use of com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields in project presto by prestodb.

the class CursorProcessorCompiler method generateMethods.

@Override
public void generateMethods(SqlFunctionProperties sqlFunctionProperties, ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter, List<RowExpression> projections) {
    CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
    List<RowExpression> rowExpressions = ImmutableList.<RowExpression>builder().addAll(projections).add(filter).build();
    Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, rowExpressions, metadata, sqlFunctionProperties, sessionFunctions, "");
    Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields = ImmutableMap.of();
    RowExpressionCompiler compiler = new RowExpressionCompiler(classDefinition, callSiteBinder, cachedInstanceBinder, fieldReferenceCompiler(cseFields), metadata, sqlFunctionProperties, sessionFunctions, compiledLambdaMap);
    if (isOptimizeCommonSubExpressions) {
        Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel = collectCSEByLevel(rowExpressions);
        if (!commonSubExpressionsByLevel.isEmpty()) {
            cseFields = declareCommonSubExpressionFields(classDefinition, commonSubExpressionsByLevel);
            compiler = new RowExpressionCompiler(classDefinition, callSiteBinder, cachedInstanceBinder, fieldReferenceCompiler(cseFields), metadata, sqlFunctionProperties, sessionFunctions, compiledLambdaMap);
            generateCommonSubExpressionMethods(classDefinition, compiler, commonSubExpressionsByLevel, cseFields);
            Map<RowExpression, VariableReferenceExpression> commonSubExpressions = commonSubExpressionsByLevel.values().stream().flatMap(m -> m.entrySet().stream()).collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
            projections = rewriteRowExpressionsWithCSE(projections, commonSubExpressions);
            filter = rewriteRowExpressionsWithCSE(ImmutableList.of(filter), commonSubExpressions).get(0);
        }
    }
    generateProcessMethod(classDefinition, projections.size(), cseFields);
    generateFilterMethod(classDefinition, compiler, filter);
    for (int i = 0; i < projections.size(); i++) {
        String methodName = "project_" + i;
        generateProjectMethod(classDefinition, compiler, methodName, projections.get(i));
    }
    MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC));
    BytecodeBlock constructorBody = constructorDefinition.getBody();
    Variable thisVariable = constructorDefinition.getThis();
    constructorBody.comment("super();").append(thisVariable).invokeConstructor(Object.class);
    initializeCommonSubExpressionFields(cseFields.values(), thisVariable, constructorBody);
    cachedInstanceBinder.generateInitializations(thisVariable, constructorBody);
    constructorBody.ret();
}
Also used : CursorProcessorOutput(com.facebook.presto.operator.project.CursorProcessorOutput) RowExpressionVisitor(com.facebook.presto.spi.relation.RowExpressionVisitor) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) SqlInvokedFunction(com.facebook.presto.spi.function.SqlInvokedFunction) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) PageBuilder(com.facebook.presto.common.PageBuilder) Access.a(com.facebook.presto.bytecode.Access.a) JumpInstruction.jump(com.facebook.presto.bytecode.instruction.JumpInstruction.jump) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) BytecodeUtils.boxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.boxPrimitiveIfNecessary) CommonSubExpressionRewriter.collectCSEByLevel(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.collectCSEByLevel) Map(java.util.Map) CallExpression(com.facebook.presto.spi.relation.CallExpression) SpecialFormExpression(com.facebook.presto.spi.relation.SpecialFormExpression) IfStatement(com.facebook.presto.bytecode.control.IfStatement) Variable(com.facebook.presto.bytecode.Variable) CommonSubExpressionRewriter.rewriteExpressionWithCSE(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.rewriteExpressionWithCSE) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) Parameter(com.facebook.presto.bytecode.Parameter) ImmutableMap(com.google.common.collect.ImmutableMap) SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression) BytecodeExpressions.constantBoolean(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean) String.format(java.lang.String.format) CompiledLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) RecordCursor(com.facebook.presto.spi.RecordCursor) List(java.util.List) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) Scope(com.facebook.presto.bytecode.Scope) Optional(java.util.Optional) InputReferenceExpression(com.facebook.presto.spi.relation.InputReferenceExpression) LabelNode(com.facebook.presto.bytecode.instruction.LabelNode) Parameter.arg(com.facebook.presto.bytecode.Parameter.arg) Logger(com.facebook.airlift.log.Logger) Slice(io.airlift.slice.Slice) DriverYieldSignal(com.facebook.presto.operator.DriverYieldSignal) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) HashMap(java.util.HashMap) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) BytecodeExpressions.constantFalse(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) WhileLoop(com.facebook.presto.bytecode.control.WhileLoop) ImmutableList(com.google.common.collect.ImmutableList) BytecodeExpressions.or(com.facebook.presto.bytecode.expression.BytecodeExpressions.or) LambdaBytecodeGenerator.generateMethodsForLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.generateMethodsForLambda) BytecodeExpressions.constantTrue(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantTrue) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) Type(com.facebook.presto.common.type.Type) RowExpression(com.facebook.presto.spi.relation.RowExpression) PUBLIC(com.facebook.presto.bytecode.Access.PUBLIC) BytecodeExpressions.newInstance(com.facebook.presto.bytecode.expression.BytecodeExpressions.newInstance) Primitives(com.google.common.primitives.Primitives) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) SqlFunctionId(com.facebook.presto.spi.function.SqlFunctionId) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) BytecodeUtils.unboxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.unboxPrimitiveIfNecessary) Metadata(com.facebook.presto.metadata.Metadata) Variable(com.facebook.presto.bytecode.Variable) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) CompiledLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) HashMap(java.util.HashMap) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression)

Example 2 with CommonSubExpressionFields

use of com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields in project presto by prestodb.

the class PageFunctionCompiler method generateCommonSubExpressionMethods.

private List<MethodDefinition> generateCommonSubExpressionMethods(ClassDefinition classDefinition, RowExpressionCompiler compiler, Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel, Map<VariableReferenceExpression, CommonSubExpressionFields> commonSubExpressionFieldsMap) {
    ImmutableList.Builder<MethodDefinition> methods = ImmutableList.builder();
    Parameter properties = arg("properties", SqlFunctionProperties.class);
    Parameter page = arg("page", Page.class);
    Parameter position = arg("position", int.class);
    int startLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::min).get();
    int maxLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::max).get();
    for (int i = startLevel; i <= maxLevel; i++) {
        if (commonSubExpressionsByLevel.containsKey(i)) {
            for (Map.Entry<RowExpression, VariableReferenceExpression> entry : commonSubExpressionsByLevel.get(i).entrySet()) {
                RowExpression cse = entry.getKey();
                Class<?> type = Primitives.wrap(cse.getType().getJavaType());
                VariableReferenceExpression cseVariable = entry.getValue();
                CommonSubExpressionFields cseFields = commonSubExpressionFieldsMap.get(cseVariable);
                MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), "get" + cseVariable.getName(), type(cseFields.getResultType()), ImmutableList.<Parameter>builder().add(properties).add(page).add(position).build());
                method.comment("cse: %s", cse);
                Scope scope = method.getScope();
                BytecodeBlock body = method.getBody();
                Variable thisVariable = method.getThis();
                declareBlockVariables(ImmutableList.of(cse), page, scope, body);
                scope.declareVariable("wasNull", body, constantFalse());
                IfStatement ifStatement = new IfStatement().condition(thisVariable.getField(cseFields.getEvaluatedField())).ifFalse(new BytecodeBlock().append(thisVariable).append(compiler.compile(cse, scope, Optional.empty())).append(boxPrimitiveIfNecessary(scope, type)).putField(cseFields.getResultField()).append(thisVariable.setField(cseFields.getEvaluatedField(), constantBoolean(true))));
                body.append(ifStatement).append(thisVariable).getField(cseFields.getResultField()).retObject();
                methods.add(method);
            }
        }
    }
    return methods.build();
}
Also used : Variable(com.facebook.presto.bytecode.Variable) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) IfStatement(com.facebook.presto.bytecode.control.IfStatement) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) Scope(com.facebook.presto.bytecode.Scope) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Parameter(com.facebook.presto.bytecode.Parameter) Map(java.util.Map) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap) Collections.emptyMap(java.util.Collections.emptyMap)

Example 3 with CommonSubExpressionFields

use of com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields in project presto by prestodb.

the class PageFunctionCompiler method definePageProjectWorkClass.

private ClassDefinition definePageProjectWorkClass(SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, List<RowExpression> projections, CallSiteBinder callSiteBinder, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix) {
    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL), generateProjectionWorkClassName(classNameSuffix), type(Object.class), type(Work.class));
    FieldDefinition blockBuilderFields = classDefinition.declareField(a(PRIVATE), "blockBuilders", type(List.class, BlockBuilder.class));
    FieldDefinition propertiesField = classDefinition.declareField(a(PRIVATE), "properties", SqlFunctionProperties.class);
    FieldDefinition pageField = classDefinition.declareField(a(PRIVATE), "page", Page.class);
    FieldDefinition selectedPositionsField = classDefinition.declareField(a(PRIVATE), "selectedPositions", SelectedPositions.class);
    FieldDefinition nextIndexOrPositionField = classDefinition.declareField(a(PRIVATE), "nextIndexOrPosition", int.class);
    FieldDefinition resultField = classDefinition.declareField(a(PRIVATE), "result", List.class);
    CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
    // process
    generateProcessMethod(classDefinition, blockBuilderFields, projections.size(), propertiesField, pageField, selectedPositionsField, nextIndexOrPositionField, resultField);
    // getResult
    MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "getResult", type(Object.class), ImmutableList.of());
    method.getBody().append(method.getThis().getField(resultField)).ret(Object.class);
    Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, projections, metadata, sqlFunctionProperties, sessionFunctions, "");
    // cse
    Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields = ImmutableMap.of();
    RowExpressionCompiler compiler = new RowExpressionCompiler(classDefinition, callSiteBinder, cachedInstanceBinder, new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields), metadata, sqlFunctionProperties, sessionFunctions, compiledLambdaMap);
    if (isOptimizeCommonSubExpression) {
        Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel = collectCSEByLevel(projections);
        if (!commonSubExpressionsByLevel.isEmpty()) {
            cseFields = declareCommonSubExpressionFields(classDefinition, commonSubExpressionsByLevel);
            compiler = new RowExpressionCompiler(classDefinition, callSiteBinder, cachedInstanceBinder, new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields), metadata, sqlFunctionProperties, sessionFunctions, compiledLambdaMap);
            generateCommonSubExpressionMethods(classDefinition, compiler, commonSubExpressionsByLevel, cseFields);
            Map<RowExpression, VariableReferenceExpression> commonSubExpressions = commonSubExpressionsByLevel.values().stream().flatMap(m -> m.entrySet().stream()).collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
            projections = projections.stream().map(projection -> rewriteExpressionWithCSE(projection, commonSubExpressions)).collect(toImmutableList());
            if (log.isDebugEnabled()) {
                log.debug("Extracted %d common sub-expressions", commonSubExpressions.size());
                commonSubExpressions.entrySet().forEach(entry -> log.debug("\t%s = %s", entry.getValue(), entry.getKey()));
                log.debug("Rewrote %d projections: %s", projections.size(), Joiner.on(", ").join(projections));
            }
        }
    }
    // evaluate
    generateEvaluateMethod(classDefinition, compiler, projections, blockBuilderFields, cseFields);
    // constructor
    Parameter blockBuilders = arg("blockBuilders", type(List.class, BlockBuilder.class));
    Parameter properties = arg("properties", SqlFunctionProperties.class);
    Parameter page = arg("page", Page.class);
    Parameter selectedPositions = arg("selectedPositions", SelectedPositions.class);
    MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC), blockBuilders, properties, page, selectedPositions);
    BytecodeBlock body = constructorDefinition.getBody();
    Variable thisVariable = constructorDefinition.getThis();
    body.comment("super();").append(thisVariable).invokeConstructor(Object.class).append(thisVariable.setField(blockBuilderFields, invokeStatic(ImmutableList.class, "copyOf", ImmutableList.class, blockBuilders.cast(Collection.class)))).append(thisVariable.setField(propertiesField, properties)).append(thisVariable.setField(pageField, page)).append(thisVariable.setField(selectedPositionsField, selectedPositions)).append(thisVariable.setField(nextIndexOrPositionField, selectedPositions.invoke("getOffset", int.class))).append(thisVariable.setField(resultField, constantNull(Block.class)));
    initializeCommonSubExpressionFields(cseFields.values(), thisVariable, body);
    cachedInstanceBinder.generateInitializations(thisVariable, body);
    body.ret();
    return classDefinition;
}
Also used : Page(com.facebook.presto.common.Page) LoadingCache(com.google.common.cache.LoadingCache) PageFieldsToInputParametersRewriter(com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter) PageFilter(com.facebook.presto.operator.project.PageFilter) Expressions.subExpressions(com.facebook.presto.sql.relational.Expressions.subExpressions) SqlInvokedFunction(com.facebook.presto.spi.function.SqlInvokedFunction) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) InputPageProjection(com.facebook.presto.operator.project.InputPageProjection) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) ForLoop(com.facebook.presto.bytecode.control.ForLoop) BytecodeUtils.boxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.boxPrimitiveIfNecessary) CommonSubExpressionRewriter.collectCSEByLevel(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.collectCSEByLevel) Map(java.util.Map) CompilerUtils.makeClassName(com.facebook.presto.util.CompilerUtils.makeClassName) IfStatement(com.facebook.presto.bytecode.control.IfStatement) BytecodeExpressions.add(com.facebook.presto.bytecode.expression.BytecodeExpressions.add) Variable(com.facebook.presto.bytecode.Variable) CommonSubExpressionRewriter.rewriteExpressionWithCSE(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.rewriteExpressionWithCSE) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) Parameter(com.facebook.presto.bytecode.Parameter) SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) PageProjectionWithOutputs(com.facebook.presto.operator.project.PageProjectionWithOutputs) BytecodeExpressions.constantBoolean(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) FINAL(com.facebook.presto.bytecode.Access.FINAL) Scope(com.facebook.presto.bytecode.Scope) BytecodeExpressions.invokeStatic(com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic) Joiner(com.google.common.base.Joiner) MoreObjects.toStringHelper(com.google.common.base.MoreObjects.toStringHelper) PageProjection(com.facebook.presto.operator.project.PageProjection) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) BytecodeExpressions.constantFalse(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse) Supplier(java.util.function.Supplier) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) TreeSet(java.util.TreeSet) Managed(org.weakref.jmx.Managed) LambdaBytecodeGenerator.generateMethodsForLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.generateMethodsForLambda) GeneratedPageProjection(com.facebook.presto.operator.project.GeneratedPageProjection) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) BytecodeExpressions.constantNull(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull) Nullable(javax.annotation.Nullable) Throwables.throwIfInstanceOf(com.google.common.base.Throwables.throwIfInstanceOf) SqlFunctionId(com.facebook.presto.spi.function.SqlFunctionId) Work(com.facebook.presto.operator.Work) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) ParameterizedType(com.facebook.presto.bytecode.ParameterizedType) Metadata(com.facebook.presto.metadata.Metadata) BytecodeExpressions.newArray(com.facebook.presto.bytecode.expression.BytecodeExpressions.newArray) RowExpressionVisitor(com.facebook.presto.spi.relation.RowExpressionVisitor) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) BytecodeUtils.invoke(com.facebook.presto.sql.gen.BytecodeUtils.invoke) Access.a(com.facebook.presto.bytecode.Access.a) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) CommonSubExpressionRewriter.getExpressionsPartitionedByCSE(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.getExpressionsPartitionedByCSE) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) CallExpression(com.facebook.presto.spi.relation.CallExpression) SpecialFormExpression(com.facebook.presto.spi.relation.SpecialFormExpression) ImmutableMap(com.google.common.collect.ImmutableMap) BytecodeExpressions.lessThan(com.facebook.presto.bytecode.expression.BytecodeExpressions.lessThan) Collection(java.util.Collection) SelectedPositions(com.facebook.presto.operator.project.SelectedPositions) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression) CacheLoader(com.google.common.cache.CacheLoader) Objects(java.util.Objects) CompiledLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) List(java.util.List) ConstantPageProjection(com.facebook.presto.operator.project.ConstantPageProjection) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) InputReferenceExpression(com.facebook.presto.spi.relation.InputReferenceExpression) Parameter.arg(com.facebook.presto.bytecode.Parameter.arg) IntStream(java.util.stream.IntStream) BytecodeExpressions.and(com.facebook.presto.bytecode.expression.BytecodeExpressions.and) DeterminismEvaluator(com.facebook.presto.spi.relation.DeterminismEvaluator) Nested(org.weakref.jmx.Nested) Logger(com.facebook.airlift.log.Logger) InputChannels(com.facebook.presto.operator.project.InputChannels) BytecodeExpressions.constantInt(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) RowExpressionDeterminismEvaluator(com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator) PrestoException(com.facebook.presto.spi.PrestoException) BytecodeExpressions.not(com.facebook.presto.bytecode.expression.BytecodeExpressions.not) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters(com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters) Verify.verify(com.google.common.base.Verify.verify) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Objects.requireNonNull(java.util.Objects.requireNonNull) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) PUBLIC(com.facebook.presto.bytecode.Access.PUBLIC) Collections.emptyMap(java.util.Collections.emptyMap) CompilerUtils.defineClass(com.facebook.presto.util.CompilerUtils.defineClass) Reflection.constructorMethodHandle(com.facebook.presto.util.Reflection.constructorMethodHandle) Primitives(com.google.common.primitives.Primitives) CompilerConfig(com.facebook.presto.sql.planner.CompilerConfig) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) BytecodeUtils.unboxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.unboxPrimitiveIfNecessary) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Block(com.facebook.presto.common.block.Block) COMPILER_ERROR(com.facebook.presto.spi.StandardErrorCode.COMPILER_ERROR) Variable(com.facebook.presto.bytecode.Variable) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) CompiledLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) Work(com.facebook.presto.operator.Work) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Parameter(com.facebook.presto.bytecode.Parameter) Map(java.util.Map) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap) Collections.emptyMap(java.util.Collections.emptyMap) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression)

Example 4 with CommonSubExpressionFields

use of com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields in project presto by prestodb.

the class CursorProcessorCompiler method fieldReferenceCompiler.

static RowExpressionVisitor<BytecodeNode, Scope> fieldReferenceCompiler(Map<VariableReferenceExpression, CommonSubExpressionFields> variableMap) {
    return new RowExpressionVisitor<BytecodeNode, Scope>() {

        @Override
        public BytecodeNode visitInputReference(InputReferenceExpression node, Scope scope) {
            int field = node.getField();
            Type type = node.getType();
            Variable wasNullVariable = scope.getVariable("wasNull");
            Variable cursorVariable = scope.getVariable("cursor");
            Class<?> javaType = type.getJavaType();
            if (!javaType.isPrimitive() && javaType != Slice.class) {
                javaType = Object.class;
            }
            IfStatement ifStatement = new IfStatement();
            ifStatement.condition().setDescription(format("cursor.get%s(%d)", type, field)).getVariable(cursorVariable).push(field).invokeInterface(RecordCursor.class, "isNull", boolean.class, int.class);
            ifStatement.ifTrue().putVariable(wasNullVariable, true).pushJavaDefault(javaType);
            ifStatement.ifFalse().getVariable(cursorVariable).push(field).invokeInterface(RecordCursor.class, "get" + Primitives.wrap(javaType).getSimpleName(), javaType, int.class);
            return ifStatement;
        }

        @Override
        public BytecodeNode visitCall(CallExpression call, Scope scope) {
            throw new UnsupportedOperationException("not yet implemented");
        }

        @Override
        public BytecodeNode visitConstant(ConstantExpression literal, Scope scope) {
            throw new UnsupportedOperationException("not yet implemented");
        }

        @Override
        public BytecodeNode visitLambda(LambdaDefinitionExpression lambda, Scope context) {
            throw new UnsupportedOperationException();
        }

        @Override
        public BytecodeNode visitVariableReference(VariableReferenceExpression reference, Scope context) {
            CommonSubExpressionFields fields = variableMap.get(reference);
            return new BytecodeBlock().append(context.getThis().invoke(fields.getMethodName(), fields.getResultType(), context.getVariable("properties"), context.getVariable("cursor"))).append(unboxPrimitiveIfNecessary(context, Primitives.wrap(reference.getType().getJavaType())));
        }

        @Override
        public BytecodeNode visitSpecialForm(SpecialFormExpression specialForm, Scope context) {
            throw new UnsupportedOperationException();
        }
    };
}
Also used : InputReferenceExpression(com.facebook.presto.spi.relation.InputReferenceExpression) Variable(com.facebook.presto.bytecode.Variable) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) IfStatement(com.facebook.presto.bytecode.control.IfStatement) Type(com.facebook.presto.common.type.Type) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) Scope(com.facebook.presto.bytecode.Scope) Slice(io.airlift.slice.Slice) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) RowExpressionVisitor(com.facebook.presto.spi.relation.RowExpressionVisitor) CallExpression(com.facebook.presto.spi.relation.CallExpression) SpecialFormExpression(com.facebook.presto.spi.relation.SpecialFormExpression) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression)

Example 5 with CommonSubExpressionFields

use of com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields in project presto by prestodb.

the class CursorProcessorCompiler method generateCommonSubExpressionMethods.

private List<MethodDefinition> generateCommonSubExpressionMethods(ClassDefinition classDefinition, RowExpressionCompiler compiler, Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel, Map<VariableReferenceExpression, CommonSubExpressionFields> commonSubExpressionFieldsMap) {
    Parameter properties = arg("properties", SqlFunctionProperties.class);
    Parameter cursor = arg("cursor", RecordCursor.class);
    ImmutableList.Builder<MethodDefinition> methods = ImmutableList.builder();
    Map<VariableReferenceExpression, CommonSubExpressionFields> cseMap = new HashMap<>();
    int startLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::min).get();
    int maxLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::max).get();
    for (int i = startLevel; i <= maxLevel; i++) {
        if (commonSubExpressionsByLevel.containsKey(i)) {
            for (Map.Entry<RowExpression, VariableReferenceExpression> entry : commonSubExpressionsByLevel.get(i).entrySet()) {
                RowExpression cse = entry.getKey();
                Class<?> type = Primitives.wrap(cse.getType().getJavaType());
                VariableReferenceExpression cseVariable = entry.getValue();
                CommonSubExpressionFields cseFields = commonSubExpressionFieldsMap.get(cseVariable);
                MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), "get" + cseVariable.getName(), type(cseFields.getResultType()), properties, cursor);
                method.comment("cse: %s", cse);
                Scope scope = method.getScope();
                BytecodeBlock body = method.getBody();
                Variable thisVariable = method.getThis();
                scope.declareVariable("wasNull", body, constantFalse());
                IfStatement ifStatement = new IfStatement().condition(thisVariable.getField(cseFields.getEvaluatedField())).ifFalse(new BytecodeBlock().append(thisVariable).append(compiler.compile(cse, scope, Optional.empty())).append(boxPrimitiveIfNecessary(scope, type)).putField(cseFields.getResultField()).append(thisVariable.setField(cseFields.getEvaluatedField(), constantBoolean(true))));
                body.append(ifStatement).append(thisVariable).getField(cseFields.getResultField()).retObject();
                methods.add(method);
                cseMap.put(cseVariable, cseFields);
            }
        }
    }
    return methods.build();
}
Also used : Variable(com.facebook.presto.bytecode.Variable) HashMap(java.util.HashMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) IfStatement(com.facebook.presto.bytecode.control.IfStatement) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) Scope(com.facebook.presto.bytecode.Scope) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Parameter(com.facebook.presto.bytecode.Parameter) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) HashMap(java.util.HashMap)

Aggregations

BytecodeBlock (com.facebook.presto.bytecode.BytecodeBlock)6 Scope (com.facebook.presto.bytecode.Scope)6 Variable (com.facebook.presto.bytecode.Variable)6 IfStatement (com.facebook.presto.bytecode.control.IfStatement)6 VariableReferenceExpression (com.facebook.presto.spi.relation.VariableReferenceExpression)6 CommonSubExpressionFields (com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields)6 CommonSubExpressionFields.declareCommonSubExpressionFields (com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields)6 CommonSubExpressionFields.initializeCommonSubExpressionFields (com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields)6 MethodDefinition (com.facebook.presto.bytecode.MethodDefinition)5 Parameter (com.facebook.presto.bytecode.Parameter)5 RowExpression (com.facebook.presto.spi.relation.RowExpression)5 ImmutableList (com.google.common.collect.ImmutableList)5 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)5 ImmutableMap (com.google.common.collect.ImmutableMap)5 ImmutableMap.toImmutableMap (com.google.common.collect.ImmutableMap.toImmutableMap)5 Map (java.util.Map)5 CallExpression (com.facebook.presto.spi.relation.CallExpression)4 ConstantExpression (com.facebook.presto.spi.relation.ConstantExpression)4 InputReferenceExpression (com.facebook.presto.spi.relation.InputReferenceExpression)4 LambdaDefinitionExpression (com.facebook.presto.spi.relation.LambdaDefinitionExpression)4