Search in sources :

Example 6 with UnexpectedResultException

use of com.oracle.truffle.api.nodes.UnexpectedResultException in project TrufflePascal by Aspect26.

the class ForNode method executeVoid.

@Override
public void executeVoid(VirtualFrame frame) {
    try {
        ControlInterface controlInterface = null;
        switch(controlSlot.getKind()) {
            case Int:
                controlInterface = this.createIntControlInterface(frame);
                break;
            case Long:
                controlInterface = this.createLongControlInterface(frame);
                break;
            case Byte:
                controlInterface = this.createCharControlInterface(frame);
                break;
            case Object:
                Object controlValue = frame.getObject(controlSlot);
                if (controlValue instanceof EnumValue) {
                    controlInterface = this.createEnumControlInterface(frame);
                    break;
                } else {
                    throw new PascalRuntimeException("Unsupported control variable type");
                }
        }
        this.execute(frame, controlInterface, ascending);
    } catch (FrameSlotTypeException | UnexpectedResultException e) {
        throw new PascalRuntimeException("Something went wrong.");
    }
}
Also used : FrameSlotTypeException(com.oracle.truffle.api.frame.FrameSlotTypeException) UnexpectedResultException(com.oracle.truffle.api.nodes.UnexpectedResultException) EnumValue(cz.cuni.mff.d3s.trupple.language.runtime.customvalues.EnumValue) PascalRuntimeException(cz.cuni.mff.d3s.trupple.language.runtime.exceptions.PascalRuntimeException)

Example 7 with UnexpectedResultException

use of com.oracle.truffle.api.nodes.UnexpectedResultException in project graal by oracle.

the class SpecializationMethodParser method parseSpecialization.

private SpecializationData parseSpecialization(TemplateMethod method) {
    List<SpecializationThrowsData> exceptionData = new ArrayList<>();
    boolean unexpectedResultRewrite = false;
    if (method.getMethod() != null) {
        AnnotationValue rewriteValue = ElementUtils.getAnnotationValue(method.getMarkerAnnotation(), "rewriteOn");
        List<TypeMirror> exceptionTypes = ElementUtils.getAnnotationValueList(TypeMirror.class, method.getMarkerAnnotation(), "rewriteOn");
        List<TypeMirror> rewriteOnTypes = new ArrayList<>();
        for (TypeMirror exceptionType : exceptionTypes) {
            SpecializationThrowsData throwsData = new SpecializationThrowsData(method.getMarkerAnnotation(), rewriteValue, exceptionType);
            if (!ElementUtils.canThrowType(method.getMethod().getThrownTypes(), exceptionType)) {
                method.addError("A rewriteOn checked exception was specified but not thrown in the method's throws clause. The @%s method must specify a throws clause with the exception type '%s'.", Specialization.class.getSimpleName(), ElementUtils.getQualifiedName(exceptionType));
            }
            if (ElementUtils.typeEquals(exceptionType, getContext().getType(UnexpectedResultException.class))) {
                if (ElementUtils.typeEquals(method.getMethod().getReturnType(), getContext().getType(Object.class))) {
                    method.addError("A specialization with return type 'Object' cannot throw UnexpectedResultException.");
                }
                unexpectedResultRewrite = true;
            }
            rewriteOnTypes.add(throwsData.getJavaClass());
            exceptionData.add(throwsData);
        }
        for (TypeMirror typeMirror : method.getMethod().getThrownTypes()) {
            if (!ElementUtils.canThrowType(rewriteOnTypes, typeMirror)) {
                method.addError(rewriteValue, "A checked exception '%s' is thrown but is not specified using the rewriteOn property. " + "Checked exceptions that are not used for rewriting are not handled by the DSL. Use RuntimeExceptions for this purpose instead.", ElementUtils.getQualifiedName(typeMirror));
            }
        }
        Collections.sort(exceptionData, new Comparator<SpecializationThrowsData>() {

            @Override
            public int compare(SpecializationThrowsData o1, SpecializationThrowsData o2) {
                return ElementUtils.compareByTypeHierarchy(o1.getJavaClass(), o2.getJavaClass());
            }
        });
    }
    SpecializationData specialization = new SpecializationData(getNode(), method, SpecializationKind.SPECIALIZED, exceptionData, unexpectedResultRewrite);
    if (method.getMethod() != null) {
        String insertBeforeName = ElementUtils.getAnnotationValue(String.class, method.getMarkerAnnotation(), "insertBefore");
        if (!insertBeforeName.equals("")) {
            specialization.setInsertBeforeName(insertBeforeName);
        }
        List<String> replacesDefs = new ArrayList<>();
        replacesDefs.addAll(ElementUtils.getAnnotationValueList(String.class, specialization.getMarkerAnnotation(), "replaces"));
        // TODO remove if deprecated contains api is removed.
        replacesDefs.addAll(ElementUtils.getAnnotationValueList(String.class, specialization.getMarkerAnnotation(), "contains"));
        Set<String> containsNames = specialization.getReplacesNames();
        containsNames.clear();
        if (replacesDefs != null) {
            for (String include : replacesDefs) {
                if (!containsNames.contains(include)) {
                    specialization.getReplacesNames().add(include);
                } else {
                    AnnotationValue value = ElementUtils.getAnnotationValue(specialization.getMarkerAnnotation(), "replaces");
                    if (value == null) {
                        // TODO remove if deprecated api was removed.
                        value = ElementUtils.getAnnotationValue(specialization.getMarkerAnnotation(), "contains");
                    }
                    specialization.addError(value, "Duplicate replace declaration '%s'.", include);
                }
            }
        }
    }
    return specialization;
}
Also used : ArrayList(java.util.ArrayList) SpecializationData(com.oracle.truffle.dsl.processor.model.SpecializationData) Specialization(com.oracle.truffle.api.dsl.Specialization) UnexpectedResultException(com.oracle.truffle.api.nodes.UnexpectedResultException) TypeMirror(javax.lang.model.type.TypeMirror) SpecializationThrowsData(com.oracle.truffle.dsl.processor.model.SpecializationThrowsData) AnnotationValue(javax.lang.model.element.AnnotationValue)

Example 8 with UnexpectedResultException

use of com.oracle.truffle.api.nodes.UnexpectedResultException in project graal by oracle.

the class InstrumentableProcessor method generateWrapper.

@SuppressWarnings("deprecation")
private CodeTypeElement generateWrapper(ProcessorContext context, Element e, boolean topLevelClass) {
    if (!e.getKind().isClass()) {
        return null;
    }
    if (e.getModifiers().contains(Modifier.PRIVATE)) {
        emitError(e, "Class must not be private to generate a wrapper.");
        return null;
    }
    if (e.getModifiers().contains(Modifier.FINAL)) {
        emitError(e, "Class must not be final to generate a wrapper.");
        return null;
    }
    if (e.getEnclosingElement().getKind() != ElementKind.PACKAGE && !e.getModifiers().contains(Modifier.STATIC)) {
        emitError(e, "Inner class must be static to generate a wrapper.");
        return null;
    }
    TypeElement sourceType = (TypeElement) e;
    ExecutableElement constructor = null;
    List<ExecutableElement> constructors = ElementFilter.constructorsIn(e.getEnclosedElements());
    if (constructors.isEmpty()) {
        // add default constructor
        constructors.add(new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), null, e.getSimpleName().toString()));
    }
    // try visible default constructor
    for (ListIterator<ExecutableElement> iterator = constructors.listIterator(); iterator.hasNext(); ) {
        ExecutableElement c = iterator.next();
        Modifier modifier = ElementUtils.getVisibility(c.getModifiers());
        if (modifier == Modifier.PRIVATE) {
            iterator.remove();
            continue;
        }
        if (c.getParameters().isEmpty()) {
            constructor = c;
            break;
        }
    }
    // try copy constructor
    if (constructor == null) {
        for (ExecutableElement c : constructors) {
            VariableElement firstParameter = c.getParameters().iterator().next();
            if (ElementUtils.typeEquals(firstParameter.asType(), sourceType.asType())) {
                constructor = c;
                break;
            }
        }
    }
    // try source section constructor
    if (constructor == null) {
        for (ExecutableElement c : constructors) {
            VariableElement firstParameter = c.getParameters().iterator().next();
            if (ElementUtils.typeEquals(firstParameter.asType(), context.getType(SourceSection.class))) {
                constructor = c;
                break;
            }
        }
    }
    if (constructor == null) {
        emitError(sourceType, "No suiteable constructor found for wrapper factory generation. At least one default or copy constructor must be visible.");
        return null;
    }
    PackageElement pack = context.getEnvironment().getElementUtils().getPackageOf(sourceType);
    Set<Modifier> typeModifiers;
    String wrapperClassName = createWrapperClassName(sourceType);
    if (topLevelClass) {
        typeModifiers = ElementUtils.modifiers(Modifier.FINAL);
    } else {
        typeModifiers = ElementUtils.modifiers(Modifier.PRIVATE, Modifier.FINAL);
        // add some suffix to avoid name clashes
        wrapperClassName += "0";
    }
    CodeTypeElement wrapperType = new CodeTypeElement(typeModifiers, ElementKind.CLASS, pack, wrapperClassName);
    TypeMirror resolvedSuperType = sourceType.asType();
    wrapperType.setSuperClass(resolvedSuperType);
    if (topLevelClass) {
        wrapperType.getImplements().add(context.getType(InstrumentableNode.WrapperNode.class));
    } else {
        wrapperType.getImplements().add(context.getType(com.oracle.truffle.api.instrumentation.InstrumentableFactory.WrapperNode.class));
    }
    addGeneratedBy(context, wrapperType, sourceType);
    wrapperType.add(createNodeChild(context, sourceType.asType(), FIELD_DELEGATE));
    wrapperType.add(createNodeChild(context, context.getType(ProbeNode.class), FIELD_PROBE));
    Set<Modifier> constructorModifiers;
    if (topLevelClass) {
        // package protected
        constructorModifiers = ElementUtils.modifiers();
    } else {
        constructorModifiers = ElementUtils.modifiers(Modifier.PRIVATE);
    }
    CodeExecutableElement wrappedConstructor = GeneratorUtils.createConstructorUsingFields(constructorModifiers, wrapperType, constructor);
    wrapperType.add(wrappedConstructor);
    // generate getters
    for (VariableElement field : wrapperType.getFields()) {
        CodeExecutableElement getter = new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), field.asType(), "get" + ElementUtils.firstLetterUpperCase(field.getSimpleName().toString()));
        getter.createBuilder().startReturn().string(field.getSimpleName().toString()).end();
        wrapperType.add(getter);
    }
    if (isOverrideableOrUndeclared(sourceType, METHOD_GET_NODE_COST)) {
        TypeMirror returnType = context.getType(NodeCost.class);
        CodeExecutableElement getInstrumentationTags = new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), returnType, METHOD_GET_NODE_COST);
        getInstrumentationTags.createBuilder().startReturn().staticReference(returnType, "NONE").end();
        wrapperType.add(getInstrumentationTags);
    }
    List<ExecutableElement> wrappedMethods = new ArrayList<>();
    List<ExecutableElement> wrappedExecuteMethods = new ArrayList<>();
    List<? extends Element> elementList = context.getEnvironment().getElementUtils().getAllMembers(sourceType);
    for (ExecutableElement method : ElementFilter.methodsIn(elementList)) {
        Set<Modifier> modifiers = method.getModifiers();
        if (modifiers.contains(Modifier.FINAL)) {
            continue;
        }
        Modifier visibility = ElementUtils.getVisibility(modifiers);
        if (visibility == Modifier.PRIVATE) {
            continue;
        }
        String methodName = method.getSimpleName().toString();
        if (methodName.startsWith(EXECUTE_METHOD_PREFIX)) {
            VariableElement firstParam = method.getParameters().isEmpty() ? null : method.getParameters().get(0);
            if (topLevelClass && (firstParam == null || !ElementUtils.isAssignable(firstParam.asType(), context.getType(VirtualFrame.class)))) {
                emitError(e, String.format("Wrapped execute method %s must have VirtualFrame as first parameter.", method.getSimpleName().toString()));
                return null;
            }
            wrappedExecuteMethods.add(method);
        } else {
            if (// 
            modifiers.contains(Modifier.ABSTRACT) && !methodName.equals("getSourceSection") && !methodName.equals(METHOD_GET_NODE_COST)) {
                wrappedMethods.add(method);
            }
        }
    }
    if (wrappedExecuteMethods.isEmpty()) {
        emitError(sourceType, String.format("No methods starting with name execute found to wrap."));
        return null;
    }
    Collections.sort(wrappedExecuteMethods, new Comparator<ExecutableElement>() {

        public int compare(ExecutableElement o1, ExecutableElement o2) {
            return ElementUtils.compareMethod(o1, o2);
        }
    });
    for (ExecutableElement executeMethod : wrappedExecuteMethods) {
        CodeExecutableElement wrappedExecute = CodeExecutableElement.clone(processingEnv, executeMethod);
        wrappedExecute.getModifiers().remove(Modifier.ABSTRACT);
        wrappedExecute.getAnnotationMirrors().clear();
        String frameParameterName = "null";
        for (VariableElement parameter : wrappedExecute.getParameters()) {
            if (ElementUtils.typeEquals(context.getType(VirtualFrame.class), parameter.asType())) {
                frameParameterName = parameter.getSimpleName().toString();
                break;
            }
        }
        CodeTreeBuilder builder = wrappedExecute.createBuilder();
        TypeMirror returnTypeMirror = executeMethod.getReturnType();
        boolean returnVoid = ElementUtils.isVoid(returnTypeMirror);
        String returnName;
        if (!returnVoid) {
            returnName = "returnValue";
            builder.declaration(returnTypeMirror, returnName, (CodeTree) null);
        } else {
            returnName = "null";
        }
        builder.startFor().startGroup().string(";;").end().end().startBlock();
        builder.declaration("boolean", VAR_RETURN_CALLED, "false");
        builder.startTryBlock();
        builder.startStatement().startCall(FIELD_PROBE, METHOD_ON_ENTER).string(frameParameterName).end().end();
        CodeTreeBuilder callDelegate = builder.create();
        callDelegate.startCall(FIELD_DELEGATE, executeMethod.getSimpleName().toString());
        for (VariableElement parameter : wrappedExecute.getParameters()) {
            callDelegate.string(parameter.getSimpleName().toString());
        }
        callDelegate.end();
        if (returnVoid) {
            builder.statement(callDelegate.build());
        } else {
            builder.startStatement().string(returnName).string(" = ").tree(callDelegate.build()).end();
        }
        builder.startStatement().string(VAR_RETURN_CALLED).string(" = true").end();
        builder.startStatement().startCall(FIELD_PROBE, METHOD_ON_RETURN_VALUE).string(frameParameterName).string(returnName).end().end();
        builder.statement("break");
        if (wrappedExecute.getThrownTypes().contains(context.getType(UnexpectedResultException.class))) {
            builder.end().startCatchBlock(context.getType(UnexpectedResultException.class), "e");
            builder.startStatement().string(VAR_RETURN_CALLED).string(" = true").end();
            builder.startStatement().startCall(FIELD_PROBE, METHOD_ON_RETURN_VALUE).string(frameParameterName).string("e.getResult()").end().end();
            builder.startThrow().string("e").end();
        }
        builder.end().startCatchBlock(context.getType(Throwable.class), "t");
        CodeTreeBuilder callExOrUnwind = builder.create();
        callExOrUnwind.startCall(FIELD_PROBE, METHOD_ON_RETURN_EXCEPTIONAL_OR_UNWIND).string(frameParameterName).string("t").string(VAR_RETURN_CALLED).end();
        builder.declaration("Object", "result", callExOrUnwind.build());
        builder.startIf().string("result == ").string(CONSTANT_REENTER).end();
        builder.startBlock();
        builder.statement("continue");
        builder.end().startElseIf();
        if (returnVoid) {
            builder.string("result != null").end();
            builder.startBlock();
            builder.statement("break");
        } else {
            boolean objectReturnType = "java.lang.Object".equals(ElementUtils.getQualifiedName(returnTypeMirror)) && returnTypeMirror.getKind() != TypeKind.ARRAY;
            boolean throwsUnexpectedResult = wrappedExecute.getThrownTypes().contains(context.getType(UnexpectedResultException.class));
            if (objectReturnType || !throwsUnexpectedResult) {
                builder.string("result != null").end();
                builder.startBlock();
                builder.startStatement().string(returnName).string(" = ");
                if (!objectReturnType) {
                    builder.string("(").string(ElementUtils.getSimpleName(returnTypeMirror)).string(") ");
                }
                builder.string("result").end();
                builder.statement("break");
            } else {
                // can throw UnexpectedResultException
                builder.string("result").instanceOf(boxed(returnTypeMirror, context.getEnvironment().getTypeUtils())).end();
                builder.startBlock();
                builder.startStatement().string(returnName).string(" = ");
                builder.string("(").string(ElementUtils.getSimpleName(returnTypeMirror)).string(") ");
                builder.string("result").end();
                builder.statement("break");
                builder.end();
                builder.startElseIf().string("result != null").end();
                builder.startBlock();
                builder.startThrow().string("new UnexpectedResultException(result)").end();
            }
        }
        builder.end();
        builder.startThrow().string("t").end();
        builder.end(2);
        if (!returnVoid) {
            builder.startReturn().string(returnName).end();
        }
        wrapperType.add(wrappedExecute);
    }
    for (ExecutableElement delegateMethod : wrappedMethods) {
        CodeExecutableElement generatedMethod = CodeExecutableElement.clone(processingEnv, delegateMethod);
        generatedMethod.getModifiers().remove(Modifier.ABSTRACT);
        CodeTreeBuilder callDelegate = generatedMethod.createBuilder();
        if (ElementUtils.isVoid(delegateMethod.getReturnType())) {
            callDelegate.startStatement();
        } else {
            callDelegate.startReturn();
        }
        callDelegate.startCall("this." + FIELD_DELEGATE, generatedMethod.getSimpleName().toString());
        for (VariableElement parameter : generatedMethod.getParameters()) {
            callDelegate.string(parameter.getSimpleName().toString());
        }
        callDelegate.end().end();
        wrapperType.add(generatedMethod);
    }
    return wrapperType;
}
Also used : CodeExecutableElement(com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement) CodeExecutableElement(com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) CodeVariableElement(com.oracle.truffle.dsl.processor.java.model.CodeVariableElement) UnexpectedResultException(com.oracle.truffle.api.nodes.UnexpectedResultException) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) CodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) SourceSection(com.oracle.truffle.api.source.SourceSection) Modifier(javax.lang.model.element.Modifier) TypeElement(javax.lang.model.element.TypeElement) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) PackageElement(javax.lang.model.element.PackageElement) CodeTreeBuilder(com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder)

Example 9 with UnexpectedResultException

use of com.oracle.truffle.api.nodes.UnexpectedResultException in project sulong by graalvm.

the class LLVMComplexDiv method executeGeneric.

@Override
public Object executeGeneric(VirtualFrame frame) {
    try {
        double a = aNode.executeDouble(frame);
        double b = bNode.executeDouble(frame);
        double c = cNode.executeDouble(frame);
        double d = dNode.executeDouble(frame);
        double denom = c * c + d * d;
        double zReal = (a * c + b * d) / denom;
        double zImag = (b * c - a * d) / denom;
        LLVMAddress allocatedMemory = alloc.executeLLVMAddress(frame);
        getMemory().putDouble(allocatedMemory, zReal);
        getMemory().putDouble(allocatedMemory.getVal() + LLVMExpressionNode.DOUBLE_SIZE_IN_BYTES, zImag);
        return allocatedMemory;
    } catch (UnexpectedResultException e) {
        CompilerDirectives.transferToInterpreter();
        throw new IllegalStateException(e);
    }
}
Also used : UnexpectedResultException(com.oracle.truffle.api.nodes.UnexpectedResultException) LLVMAddress(com.oracle.truffle.llvm.runtime.LLVMAddress)

Example 10 with UnexpectedResultException

use of com.oracle.truffle.api.nodes.UnexpectedResultException in project sulong by graalvm.

the class LLVMStructArrayLiteralNode method writeDouble.

@Specialization
@ExplodeLoop
protected LLVMAddress writeDouble(VirtualFrame frame, LLVMAddress addr) {
    long currentPtr = addr.getVal();
    for (int i = 0; i < values.length; i++) {
        try {
            LLVMAddress currentValue = values[i].executeLLVMAddress(frame);
            memMove.executeWithTarget(LLVMAddress.fromLong(currentPtr), currentValue, stride);
            currentPtr += stride;
        } catch (UnexpectedResultException e) {
            CompilerDirectives.transferToInterpreter();
            throw new IllegalStateException(e);
        }
    }
    return addr;
}
Also used : UnexpectedResultException(com.oracle.truffle.api.nodes.UnexpectedResultException) LLVMAddress(com.oracle.truffle.llvm.runtime.LLVMAddress) Specialization(com.oracle.truffle.api.dsl.Specialization) ExplodeLoop(com.oracle.truffle.api.nodes.ExplodeLoop)

Aggregations

UnexpectedResultException (com.oracle.truffle.api.nodes.UnexpectedResultException)10 Specialization (com.oracle.truffle.api.dsl.Specialization)6 ExplodeLoop (com.oracle.truffle.api.nodes.ExplodeLoop)5 LLVMAddress (com.oracle.truffle.llvm.runtime.LLVMAddress)3 LLVMFunctionDescriptor (com.oracle.truffle.llvm.runtime.LLVMFunctionDescriptor)2 LLVMTruffleObject (com.oracle.truffle.llvm.runtime.LLVMTruffleObject)2 LLVM80BitFloat (com.oracle.truffle.llvm.runtime.floating.LLVM80BitFloat)2 ArrayList (java.util.ArrayList)2 TypeMirror (javax.lang.model.type.TypeMirror)2 FrameSlotTypeException (com.oracle.truffle.api.frame.FrameSlotTypeException)1 VirtualFrame (com.oracle.truffle.api.frame.VirtualFrame)1 SourceSection (com.oracle.truffle.api.source.SourceSection)1 CodeExecutableElement (com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement)1 CodeTreeBuilder (com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder)1 CodeTypeElement (com.oracle.truffle.dsl.processor.java.model.CodeTypeElement)1 CodeTypeMirror (com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror)1 CodeVariableElement (com.oracle.truffle.dsl.processor.java.model.CodeVariableElement)1 SpecializationData (com.oracle.truffle.dsl.processor.model.SpecializationData)1 SpecializationThrowsData (com.oracle.truffle.dsl.processor.model.SpecializationThrowsData)1 EnumValue (cz.cuni.mff.d3s.trupple.language.runtime.customvalues.EnumValue)1