Search in sources :

Example 11 with CodeTree

use of com.oracle.truffle.dsl.processor.java.model.CodeTree in project graal by oracle.

the class FlatNodeGenFactory method visitSpecializationGroup.

private CodeTree visitSpecializationGroup(CodeTreeBuilder parent, SpecializationGroup group, ExecutableTypeData forType, FrameState frameState, List<SpecializationData> allowedSpecializations, NodeExecutionMode mode) {
    CodeTreeBuilder builder = parent.create();
    boolean hasFallthrough = false;
    boolean hasImplicitCast = false;
    List<IfTriple> cachedTriples = new ArrayList<>();
    for (TypeGuard guard : group.getTypeGuards()) {
        IfTriple triple = createTypeCheckOrCast(frameState, group, guard, mode, false, true);
        if (triple != null) {
            cachedTriples.add(triple);
        }
        hasImplicitCast = hasImplicitCast || node.getTypeSystem().hasImplicitSourceTypes(guard.getType());
        if (!mode.isGuardFallback()) {
            triple = createTypeCheckOrCast(frameState, group, guard, mode, true, true);
            if (triple != null) {
                cachedTriples.add(triple);
            }
        }
    }
    SpecializationData specialization = group.getSpecialization();
    SpecializationData[] specializations = group.collectSpecializations().toArray(new SpecializationData[0]);
    List<GuardExpression> guardExpressions = new ArrayList<>(group.getGuards());
    // out of the loop.
    if (specialization != null && specialization.hasMultipleInstances()) {
        List<GuardExpression> unboundGuards = new ArrayList<>();
        for (GuardExpression guard : guardExpressions) {
            if (!specialization.isGuardBoundWithCache(guard)) {
                unboundGuards.add(guard);
            } else {
                // we need to stop as we need to ensure guard execution order
                break;
            }
        }
        cachedTriples.addAll(createMethodGuardCheck(frameState, group, unboundGuards, mode));
        guardExpressions.removeAll(unboundGuards);
    }
    boolean useSpecializationClass = specialization != null && useSpecializationClass(specialization);
    if (mode.isFastPath()) {
        int ifCount = 0;
        final boolean stateGuaranteed = group.isLast() && allowedSpecializations != null && allowedSpecializations.size() == 1 && group.getAllSpecializations().size() == allowedSpecializations.size();
        if ((!group.isEmpty() || specialization != null)) {
            CodeTree stateCheck = state.createContains(frameState, specializations);
            CodeTree stateGuard = null;
            CodeTree assertCheck = null;
            if (stateGuaranteed) {
                assertCheck = CodeTreeBuilder.createBuilder().startAssert().tree(stateCheck).end().build();
            } else {
                stateGuard = stateCheck;
            }
            cachedTriples.add(0, new IfTriple(null, stateGuard, assertCheck));
        }
        ifCount += IfTriple.materialize(builder, IfTriple.optimize(cachedTriples), false);
        // reset current triples
        cachedTriples = new ArrayList<>();
        String specializationLocalName = null;
        if (useSpecializationClass) {
            specializationLocalName = createSpecializationLocalName(specialization);
            builder.tree(loadSpecializationClass(frameState, specialization));
            if (specialization.getMaximumNumberOfInstances() > 1) {
                builder.startWhile();
            } else {
                builder.startIf();
            }
            builder.string(specializationLocalName, " != null");
            builder.end();
            builder.startBlock();
            ifCount++;
        }
        if (specialization != null) {
            if (!specialization.getAssumptionExpressions().isEmpty()) {
                builder.tree(createFastPathAssumptionCheck(builder, specialization, forType, frameState));
            }
        }
        cachedTriples = createMethodGuardCheck(frameState, group, guardExpressions, mode);
        int innerIfCount = IfTriple.materialize(builder, IfTriple.optimize(cachedTriples), false);
        SpecializationGroup prev = null;
        for (SpecializationGroup child : group.getChildren()) {
            if (prev != null && !prev.hasFallthrough()) {
                break;
            }
            builder.tree(visitSpecializationGroup(builder, child, forType, frameState.copy(), allowedSpecializations, mode));
        }
        if (specialization != null && (prev == null || prev.hasFallthrough())) {
            builder.tree(createFastPathExecute(builder, forType, specialization, frameState));
        }
        builder.end(innerIfCount);
        hasFallthrough |= innerIfCount > 0;
        if (useSpecializationClass && specialization.getMaximumNumberOfInstances() > 1) {
            String name = createSpecializationLocalName(specialization);
            builder.startStatement().string(name, " = ", name, ".next_").end();
        }
        builder.end(ifCount);
        hasFallthrough |= ifCount > 0;
    } else if (mode.isSlowPath()) {
        if (specialization != null && mayBeExcluded(specialization)) {
            CodeTree excludeCheck = exclude.createNotContains(frameState, specializations);
            cachedTriples.add(0, new IfTriple(null, excludeCheck, null));
        }
        int outerIfCount = 0;
        if (specialization == null) {
            cachedTriples.addAll(createMethodGuardCheck(frameState, group, guardExpressions, mode));
            outerIfCount += IfTriple.materialize(builder, IfTriple.optimize(cachedTriples), false);
            SpecializationGroup prev = null;
            for (SpecializationGroup child : group.getChildren()) {
                if (prev != null && !prev.hasFallthrough()) {
                    break;
                }
                builder.tree(visitSpecializationGroup(builder, child, forType, frameState.copy(), allowedSpecializations, mode));
                prev = child;
            }
        } else {
            outerIfCount += IfTriple.materialize(builder, IfTriple.optimize(cachedTriples), false);
            String countName = specialization != null ? "count" + specialization.getIndex() + "_" : null;
            boolean needsDuplicationCheck = specialization.isGuardBindsCache() || specialization.hasMultipleInstances();
            boolean useDuplicateFlag = specialization.isGuardBindsCache() && !specialization.hasMultipleInstances();
            String duplicateFoundName = specialization.getId() + "_duplicateFound_";
            int innerIfCount = 0;
            String specializationLocalName = createSpecializationLocalName(specialization);
            if (needsDuplicationCheck) {
                builder.tree(createDuplicationCheck(builder, frameState, group, guardExpressions, useDuplicateFlag, countName, duplicateFoundName, specializationLocalName));
                builder.startIf();
                if (useDuplicateFlag) {
                    // we reuse the specialization class local name instead of a duplicate found
                    // name
                    builder.string("!", duplicateFoundName);
                } else {
                    builder.string(createSpecializationLocalName(specialization), " == null");
                }
                builder.end().startBlock();
                innerIfCount++;
            }
            List<IfTriple> innerTripples = createMethodGuardCheck(frameState, group, guardExpressions, mode);
            List<AssumptionExpression> assumptions = specialization.getAssumptionExpressions();
            if (!assumptions.isEmpty()) {
                for (AssumptionExpression assumption : assumptions) {
                    innerTripples.addAll(createAssumptionSlowPathTriples(frameState, group, assumption));
                }
            }
            if (specialization.hasMultipleInstances()) {
                DSLExpression limit = specialization.getLimitExpression();
                innerTripples.addAll(initializeCaches(frameState, group, specialization.getBoundCaches(limit), NodeExecutionMode.SLOW_PATH, true, false));
                CodeTree limitExpression = DSLExpressionGenerator.write(limit, null, castBoundTypes(bindExpressionValues(frameState, limit, specialization)));
                CodeTree limitCondition = CodeTreeBuilder.createBuilder().string(countName).string(" < ").tree(limitExpression).build();
                innerTripples.add(new IfTriple(null, limitCondition, null));
                // assert that specialization is not initialized
                // otherwise we have been inserting invalid instances
                assertSpecializationClassNotInitialized(frameState, specialization);
            } else if (needsDuplicationCheck) {
                innerTripples.add(new IfTriple(null, state.createNotContains(frameState, new Object[] { specialization }), null));
            }
            innerIfCount += IfTriple.materialize(builder, IfTriple.optimize(innerTripples), false);
            builder.tree(createSpecialize(builder, frameState, group, specialization));
            if (needsDuplicationCheck) {
                hasFallthrough = true;
                if (useDuplicateFlag) {
                    builder.startStatement().string(duplicateFoundName, " = true").end();
                }
                builder.end(innerIfCount);
                // need to ensure that we update the implicit cast specializations on duplicates
                CodeTree updateImplicitCast = createUpdateImplicitCastState(builder, frameState, specialization);
                if (updateImplicitCast != null) {
                    builder.startElseBlock();
                    builder.tree(createUpdateImplicitCastState(builder, frameState, specialization));
                    builder.tree(state.createSet(frameState, new Object[] { specialization }, true, true));
                    builder.end();
                }
                builder.startIf();
                if (useDuplicateFlag) {
                    builder.string(duplicateFoundName);
                } else {
                    builder.string(createSpecializationLocalName(specialization), " != null");
                }
                builder.end().startBlock();
                builder.tree(createExecute(builder, frameState, executeAndSpecializeType, specialization, mode));
                builder.end();
            } else {
                builder.tree(createExecute(builder, frameState, executeAndSpecializeType, specialization, mode));
                builder.end(innerIfCount);
                hasFallthrough |= innerIfCount > 0;
            }
        }
        builder.end(outerIfCount);
        hasFallthrough |= outerIfCount > 0;
    } else if (mode.isGuardFallback()) {
        int ifCount = 0;
        if (specialization != null && specialization.getMaximumNumberOfInstances() > 1) {
            throw new AssertionError("unsupported path. should be caught by parser..");
        }
        int innerIfCount = 0;
        cachedTriples.addAll(createMethodGuardCheck(frameState, group, guardExpressions, mode));
        cachedTriples.addAll(createAssumptionCheckTriples(frameState, specialization));
        cachedTriples = IfTriple.optimize(cachedTriples);
        if (specialization != null && !hasImplicitCast) {
            IfTriple singleCondition = null;
            if (cachedTriples.size() == 1) {
                singleCondition = cachedTriples.get(0);
            }
            if (singleCondition != null) {
                int index = cachedTriples.indexOf(singleCondition);
                CodeTree stateCheck = state.createNotContains(frameState, specializations);
                cachedTriples.set(index, new IfTriple(singleCondition.prepare, combineTrees(" && ", stateCheck, singleCondition.condition), singleCondition.statements));
                fallbackNeedsState = true;
            }
        }
        innerIfCount += IfTriple.materialize(builder, cachedTriples, false);
        SpecializationGroup prev = null;
        for (SpecializationGroup child : group.getChildren()) {
            if (prev != null && !prev.hasFallthrough()) {
                break;
            }
            builder.tree(visitSpecializationGroup(builder, child, forType, frameState.copy(), allowedSpecializations, mode));
            prev = child;
        }
        if (specialization != null) {
            builder.returnFalse();
        }
        builder.end(innerIfCount);
        builder.end(ifCount);
        hasFallthrough |= ifCount > 0 || innerIfCount > 0;
    } else {
        throw new AssertionError("unexpected path");
    }
    group.setFallthrough(hasFallthrough);
    return builder.build();
}
Also used : GuardExpression(com.oracle.truffle.dsl.processor.model.GuardExpression) ArrayList(java.util.ArrayList) SpecializationData(com.oracle.truffle.dsl.processor.model.SpecializationData) SpecializationGroup(com.oracle.truffle.dsl.processor.parser.SpecializationGroup) DSLExpression(com.oracle.truffle.dsl.processor.expression.DSLExpression) CodeTree(com.oracle.truffle.dsl.processor.java.model.CodeTree) List(java.util.List) ArrayList(java.util.ArrayList) CodeTreeBuilder(com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder) TypeGuard(com.oracle.truffle.dsl.processor.parser.SpecializationGroup.TypeGuard) AssumptionExpression(com.oracle.truffle.dsl.processor.model.AssumptionExpression)

Example 12 with CodeTree

use of com.oracle.truffle.dsl.processor.java.model.CodeTree in project graal by oracle.

the class FlatNodeGenFactory method createGetCostMethod.

private Element createGetCostMethod() {
    TypeMirror returnType = getType(NodeCost.class);
    CodeExecutableElement executable = new CodeExecutableElement(modifiers(PUBLIC), returnType, "getCost");
    executable.getAnnotationMirrors().add(new CodeAnnotationMirror(context.getDeclaredType(Override.class)));
    CodeTreeBuilder builder = executable.createBuilder();
    FrameState frameState = FrameState.load(this);
    builder.tree(state.createLoad(frameState));
    if (node.needsRewrites(context)) {
        builder.startIf().tree(state.createIs(frameState, new Object[0], reachableSpecializationsArray)).end();
        builder.startBlock();
        builder.startReturn().staticReference(getType(NodeCost.class), "UNINITIALIZED").end();
        builder.end();
        if (reachableSpecializations.size() == 1 && !reachableSpecializations.iterator().next().hasMultipleInstances()) {
            builder.startElseBlock();
            builder.startReturn().staticReference(getType(NodeCost.class), "MONOMORPHIC").end();
            builder.end();
        } else {
            builder.startElseIf();
            builder.tree(state.createIsOneBitOf(frameState, reachableSpecializationsArray));
            builder.end();
            builder.startBlock();
            List<CodeTree> additionalChecks = new ArrayList<>();
            for (SpecializationData specialization : reachableSpecializations) {
                if (useSpecializationClass(specialization) && specialization.getMaximumNumberOfInstances() > 1) {
                    String typeName = createSpecializationTypeName(specialization);
                    String fieldName = createSpecializationFieldName(specialization);
                    String localName = createSpecializationLocalName(specialization);
                    builder.declaration(typeName, localName, "this." + fieldName);
                    CodeTree check = builder.create().startParantheses().string(localName, " == null || ", localName, ".next_ == null").end().build();
                    additionalChecks.add(check);
                }
            }
            if (!additionalChecks.isEmpty()) {
                builder.startIf().tree(combineTrees(" && ", additionalChecks.toArray(new CodeTree[0]))).end().startBlock();
            }
            builder.startReturn().staticReference(getType(NodeCost.class), "MONOMORPHIC").end();
            if (!additionalChecks.isEmpty()) {
                builder.end();
            }
            builder.end();
            builder.startReturn().staticReference(getType(NodeCost.class), "POLYMORPHIC").end();
        }
    } else {
        builder.startReturn().staticReference(getType(NodeCost.class), "MONOMORPHIC").end();
    }
    return executable;
}
Also used : CodeAnnotationMirror(com.oracle.truffle.dsl.processor.java.model.CodeAnnotationMirror) CodeExecutableElement(com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement) DeclaredCodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.DeclaredCodeTypeMirror) ArrayCodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.ArrayCodeTypeMirror) GeneratedTypeMirror(com.oracle.truffle.dsl.processor.java.model.GeneratedTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) CodeTree(com.oracle.truffle.dsl.processor.java.model.CodeTree) ArrayList(java.util.ArrayList) SpecializationData(com.oracle.truffle.dsl.processor.model.SpecializationData) CodeTreeBuilder(com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder)

Example 13 with CodeTree

use of com.oracle.truffle.dsl.processor.java.model.CodeTree in project graal by oracle.

the class FlatNodeGenFactory method createExecuteChildImplicitCast.

private ChildExecutionResult createExecuteChildImplicitCast(CodeTreeBuilder parent, FrameState originalFrameState, FrameState frameState, NodeExecutionData execution, LocalVariable target) {
    CodeTreeBuilder builder = parent.create();
    List<TypeMirror> originalSourceTypes = typeSystem.lookupSourceTypes(target.getTypeMirror());
    List<TypeMirror> sourceTypes = resolveOptimizedImplicitSourceTypes(execution, target.getTypeMirror());
    TypeGuard typeGuard = new TypeGuard(target.getTypeMirror(), execution.getIndex());
    boolean throwsUnexpected = false;
    boolean elseIf = false;
    for (TypeMirror sourceType : sourceTypes) {
        ExecutableTypeData executableType = resolveTargetExecutable(execution, sourceType);
        elseIf = builder.startIf(elseIf);
        throwsUnexpected |= executableType.hasUnexpectedValue(context);
        builder.startGroup();
        builder.tree(state.createContainsOnly(frameState, originalSourceTypes.indexOf(sourceType), 1, new Object[] { typeGuard }, new Object[] { typeGuard }));
        builder.string(" && ");
        builder.tree(state.createIsNotAny(frameState, reachableSpecializationsArray));
        builder.end();
        builder.end();
        builder.startBlock();
        CodeTree value = callChildExecuteMethod(execution, executableType, frameState);
        value = expect(executableType.getReturnType(), sourceType, value);
        throwsUnexpected |= needsCastTo(executableType.getReturnType(), sourceType);
        ImplicitCastData cast = typeSystem.lookupCast(sourceType, target.getTypeMirror());
        if (cast != null) {
            // we need to store the original value to restore it in
            // case of a deopt
            String localName = createSourceTypeLocalName(target, sourceType);
            builder.startStatement().string(localName).string(" = ").tree(value).end();
            value = callMethod(null, cast.getMethod(), CodeTreeBuilder.singleString(localName));
        }
        builder.startStatement().string(target.getName()).string(" = ").tree(value).end();
        builder.end();
    }
    if (elseIf) {
        builder.startElseBlock();
    }
    LocalVariable genericValue = target.makeGeneric(context).nextName();
    builder.tree(createAssignExecuteChild(originalFrameState, frameState, builder, execution, node.getGenericExecutableType(null), genericValue));
    builder.startStatement().string(target.getName()).string(" = ");
    CodeTree implicitState = state.createExtractInteger(frameState, typeGuard);
    builder.tree(TypeSystemCodeGenerator.implicitExpectFlat(typeSystem, target.getTypeMirror(), genericValue.createReference(), implicitState));
    builder.end();
    if (!sourceTypes.isEmpty()) {
        builder.end();
    }
    return new ChildExecutionResult(builder.build(), throwsUnexpected);
}
Also used : ImplicitCastData(com.oracle.truffle.dsl.processor.model.ImplicitCastData) ExecutableTypeData(com.oracle.truffle.dsl.processor.model.ExecutableTypeData) DeclaredCodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.DeclaredCodeTypeMirror) ArrayCodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.ArrayCodeTypeMirror) GeneratedTypeMirror(com.oracle.truffle.dsl.processor.java.model.GeneratedTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) CodeTree(com.oracle.truffle.dsl.processor.java.model.CodeTree) ElementUtils.isObject(com.oracle.truffle.dsl.processor.java.ElementUtils.isObject) CodeTreeBuilder(com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder) TypeGuard(com.oracle.truffle.dsl.processor.parser.SpecializationGroup.TypeGuard)

Example 14 with CodeTree

use of com.oracle.truffle.dsl.processor.java.model.CodeTree in project graal by oracle.

the class FlatNodeGenFactory method createAssumptionSlowPathTriples.

private List<IfTriple> createAssumptionSlowPathTriples(FrameState frameState, SpecializationGroup group, AssumptionExpression assumption) throws AssertionError {
    List<IfTriple> triples = new ArrayList<>();
    LocalVariable var = frameState.get(assumption.getId());
    CodeTree declaration = null;
    if (var == null) {
        triples.addAll(initializeCaches(frameState, group, group.getSpecialization().getBoundCaches(assumption.getExpression()), NodeExecutionMode.SLOW_PATH, true, false));
        CodeTree assumptionExpressions = DSLExpressionGenerator.write(assumption.getExpression(), null, castBoundTypes(bindExpressionValues(frameState, assumption.getExpression(), group.getSpecialization())));
        String name = createAssumptionFieldName(group.getSpecialization(), assumption);
        var = new LocalVariable(assumption.getExpression().getResolvedType(), name.substring(0, name.length() - 1), null);
        frameState.set(assumption.getId(), var);
        declaration = var.createDeclaration(assumptionExpressions);
    }
    triples.add(new IfTriple(declaration, createAssumptionGuard(assumption, var.createReference()), null));
    return triples;
}
Also used : CodeTree(com.oracle.truffle.dsl.processor.java.model.CodeTree) ArrayList(java.util.ArrayList)

Example 15 with CodeTree

use of com.oracle.truffle.dsl.processor.java.model.CodeTree in project graal by oracle.

the class FlatNodeGenFactory method bindExpressionValues.

private Map<Variable, LocalVariable> bindExpressionValues(FrameState frameState, DSLExpression expression, SpecializationData specialization) throws AssertionError {
    Map<Variable, LocalVariable> bindings = new HashMap<>();
    Set<Variable> boundVariables = expression.findBoundVariables();
    if (specialization == null && !boundVariables.isEmpty()) {
        throw new AssertionError("Cannot bind guard variable in non-specialization group. yet.");
    }
    // resolve bindings for local context
    for (Variable variable : boundVariables) {
        Parameter resolvedParameter = specialization.findByVariable(variable.getResolvedVariable());
        if (resolvedParameter != null) {
            LocalVariable localVariable;
            if (resolvedParameter.getSpecification().isCached()) {
                // bind cached variable
                String cachedMemberName = createFieldName(specialization, resolvedParameter);
                localVariable = frameState.get(cachedMemberName);
                CodeTree ref;
                if (localVariable == null) {
                    ref = createCacheReference(frameState, specialization, resolvedParameter);
                } else {
                    ref = localVariable.createReference();
                }
                bindings.put(variable, new LocalVariable(resolvedParameter.getType(), cachedMemberName, ref));
            } else {
                // bind local variable
                if (resolvedParameter.getSpecification().isSignature()) {
                    NodeExecutionData execution = resolvedParameter.getSpecification().getExecution();
                    localVariable = frameState.getValue(execution);
                } else {
                    localVariable = frameState.get(resolvedParameter.getLocalName());
                }
                if (localVariable != null) {
                    bindings.put(variable, localVariable);
                }
            }
        }
    }
    return bindings;
}
Also used : Variable(com.oracle.truffle.dsl.processor.expression.DSLExpression.Variable) NodeExecutionData(com.oracle.truffle.dsl.processor.model.NodeExecutionData) HashMap(java.util.HashMap) CodeTree(com.oracle.truffle.dsl.processor.java.model.CodeTree) Parameter(com.oracle.truffle.dsl.processor.model.Parameter)

Aggregations

CodeTree (com.oracle.truffle.dsl.processor.java.model.CodeTree)34 CodeTreeBuilder (com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder)21 ArrayCodeTypeMirror (com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.ArrayCodeTypeMirror)14 GeneratedTypeMirror (com.oracle.truffle.dsl.processor.java.model.GeneratedTypeMirror)14 TypeMirror (javax.lang.model.type.TypeMirror)14 DeclaredCodeTypeMirror (com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.DeclaredCodeTypeMirror)13 ArrayList (java.util.ArrayList)13 CodeExecutableElement (com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement)6 SpecializationData (com.oracle.truffle.dsl.processor.model.SpecializationData)6 CodeVariableElement (com.oracle.truffle.dsl.processor.java.model.CodeVariableElement)5 NodeExecutionData (com.oracle.truffle.dsl.processor.model.NodeExecutionData)5 VariableElement (javax.lang.model.element.VariableElement)5 Parameter (com.oracle.truffle.dsl.processor.model.Parameter)4 Variable (com.oracle.truffle.dsl.processor.expression.DSLExpression.Variable)3 ElementUtils.isObject (com.oracle.truffle.dsl.processor.java.ElementUtils.isObject)3 SpecializationGroup (com.oracle.truffle.dsl.processor.parser.SpecializationGroup)3 TypeGuard (com.oracle.truffle.dsl.processor.parser.SpecializationGroup.TypeGuard)3 ExecutableElement (javax.lang.model.element.ExecutableElement)3 DSLExpression (com.oracle.truffle.dsl.processor.expression.DSLExpression)2 CodeTypeElement (com.oracle.truffle.dsl.processor.java.model.CodeTypeElement)2