com.oracle.truffle.api.dsl.Specialization Java Examples

The following examples show how to use com.oracle.truffle.api.dsl.Specialization. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MappedFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Specialization(guards = "cachedReceiver == receiver", limit = "1")
static Object executeCached(@SuppressWarnings("unused") MappedFunction receiver, Object[] arguments,
                @Cached("receiver") MappedFunction cachedReceiver,
                @CachedLibrary("cachedReceiver.function") InteropLibrary functionInterop,
                @CachedLibrary("cachedReceiver.returnValue") InteropLibrary resultInterop,
                @Cached(value = "createInterop(cachedReceiver)") InteropLibrary[] valueInterop)
                throws IllegalStateException, UnsupportedTypeException, ArityException, UnsupportedMessageException {
    Object[] shredded = createShredded(cachedReceiver.shreddedArguments, arguments);
    Object[] values = new Object[receiver.valueCount];
    ArgumentArray wrappedArguments = new ArgumentArray(arguments);
    ArgumentArray wrappedShreddedArguments = new ArgumentArray(shredded);
    ArgumentArray wrappedValueArguments = new ArgumentArray(values);
    Object[] mappedArguments = mapArguments(valueInterop, cachedReceiver, wrappedArguments, wrappedShreddedArguments, wrappedValueArguments);
    Object result = functionInterop.execute(cachedReceiver.function, mappedArguments);
    return processResult(receiver, resultInterop, values, wrappedArguments, wrappedShreddedArguments, wrappedValueArguments, result);
}
 
Example #2
Source File: HashemReadLocalVariableNode.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Specialization(replaces = {"readLong", "readBoolean"})
protected Object readObject(VirtualFrame frame) {
    if (!frame.isObject(getSlot())) {
        /*
         * The FrameSlotKind has been set to Object, so from now on all writes to the local
         * variable will be Object writes. However, now we are in a frame that still has an old
         * non-Object value. This is a slow-path operation: we read the non-Object value, and
         * write it immediately as an Object value so that we do not hit this path again
         * multiple times for the same variable of the same frame.
         */
        CompilerDirectives.transferToInterpreter();
        Object result = frame.getValue(getSlot());
        frame.setObject(getSlot(), result);
        return result;
    }

    return FrameUtil.getObjectSafe(frame, getSlot());
}
 
Example #3
Source File: CallNode.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Specialization
Object doDefault(VirtualFrame frame,
                @CachedLibrary(limit = "2") InteropLibrary interop,
                @CachedContext(GrCUDALanguage.class) GrCUDAContext context) {
    String[] functionName = identifier.getIdentifierName();
    Namespace namespace = context.getRootNamespace();
    Optional<Object> maybeFunction = namespace.lookup(functionName);
    if (!maybeFunction.isPresent() || !(maybeFunction.get() instanceof Function)) {
        CompilerDirectives.transferToInterpreter();
        throw new GrCUDAException("function '" + GrCUDAException.format(functionName) + "' not found", this);
    }
    Function function = (Function) maybeFunction.get();
    Object[] argumentValues = new Object[argumentNodes.length];
    for (int i = 0; i < argumentNodes.length; i++) {
        argumentValues[i] = argumentNodes[i].execute(frame);
    }
    try {
        return interop.execute(function, argumentValues);
    } catch (ArityException | UnsupportedTypeException | UnsupportedMessageException e) {
        CompilerDirectives.transferToInterpreter();
        throw new GrCUDAException(e.getMessage(), this);
    }
}
 
Example #4
Source File: MapFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Specialization(guards = "VALUE.equals(member)")
static MapFunctionBase readMemberValue(MapFunction receiver, String member) {
    return new MapFunctionBase(arguments -> {
        if (arguments.length < 1) {
            throw ArityException.create(1, arguments.length);
        }
        String name = checkString(arguments[0], "name of created value expected");
        if (arguments.length == 1) {
            return receiver.value(name);
        } else {
            Object function = arguments[1];
            Object[] args = Arrays.copyOfRange(arguments, 2, arguments.length);
            return receiver.value(name, function, args);
        }
    });
}
 
Example #5
Source File: MapDeviceArrayFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Specialization(limit = "3")
Object doMap(Object source, Type elementType, CUDARuntime runtime,
                @CachedLibrary("source") InteropLibrary interop,
                @CachedContext(GrCUDALanguage.class) @SuppressWarnings("unused") GrCUDAContext context,
                @Cached(value = "createLoop(source)", uncached = "createUncachedLoop(source, context)") CallTarget loop) {

    if (source instanceof DeviceArray && ((DeviceArray) source).getElementType() == elementType) {
        return source;
    }

    if (!interop.hasArrayElements(source)) {
        CompilerDirectives.transferToInterpreter();
        throw new GrCUDAException("cannot map from non-array to DeviceArray");
    }

    long size;
    try {
        size = interop.getArraySize(source);
    } catch (UnsupportedMessageException e) {
        CompilerDirectives.transferToInterpreter();
        throw new GrCUDAException("cannot read array size");
    }
    DeviceArray result = new DeviceArray(runtime, size, elementType);
    loop.call(size, source, result);
    return result;
}
 
Example #6
Source File: HashemUnboxNode.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Specialization(limit = "LIMIT")
public static Object fromForeign(Object value, @CachedLibrary("value") InteropLibrary interop) {
    try {
        if (interop.fitsInLong(value)) {
            return interop.asLong(value);
        } else if (interop.fitsInFloat(value)) {
            return interop.asFloat(value);
        } else if (interop.isString(value)) {
            return interop.asString(value);
        } else if (interop.isBoolean(value)) {
            return interop.asBoolean(value);
        } else {
            return value;
        }
    } catch (UnsupportedMessageException e) {
        CompilerDirectives.transferToInterpreter();
        throw new AssertionError();
    }
}
 
Example #7
Source File: HashemAdadBekhoonBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Specialization
public Integer adadBekhoon(@CachedContext(HashemLanguage.class) HashemContext context) {
    String input = doRead(context.getInput());
    int result = 0;
    if (input == null) {
        /*
         * We do not have a sophisticated end of file handling, so returning an empty string is
         * a reasonable alternative. Note that the Java null value should never be used, since
         * it can interfere with the specialization logic in generated source code.
         */
        result = 0;
    }
    try {
        return Integer.parseInt(input);
    } catch (NumberFormatException e) {
        throw new HashemException(String.format("%s is not a number!", input), this);
    }
}
 
Example #8
Source File: HashemObjectType.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
/**
 * Polymorphic inline cache for writing a property that already exists (no shape change is
 * necessary).
 */
@Specialization(limit = "CACHE_LIMIT", //
                guards = {
                                "cachedName.equals(name)",
                                "shapeCheck(shape, receiver)",
                                "location != null",
                                "canSet(location, value)"
                }, //
                assumptions = {
                                "shape.getValidAssumption()"
                })
static void writeExistingPropertyCached(DynamicObject receiver, @SuppressWarnings("unused") String name, Object value,
                @SuppressWarnings("unused") @Cached("name") String cachedName,
                @Cached("receiver.getShape()") Shape shape,
                @Cached("lookupLocation(shape, name, value)") Location location) {
    try {
        location.set(receiver, value, shape);

    } catch (IncompatibleLocationException | FinalLocationException ex) {
        /* Our guards ensure that the value can be stored, so this cannot happen. */
        throw new IllegalStateException(ex);
    }
}
 
Example #9
Source File: HashemToMemberNode.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Specialization(limit = "LIMIT")
protected static String fromInterop(Object value, @CachedLibrary("value") InteropLibrary interop) throws UnknownIdentifierException {
    try {
        if (interop.fitsInLong(value)) {
            return longToString(interop.asLong(value));
        } else if (interop.isString(value)) {
            return interop.asString(value);
        } else if (interop.isNumber(value) && value instanceof HashemBigNumber) {
            return bigNumberToString((HashemBigNumber) value);
        } else {
            throw error(value);
        }
    } catch (UnsupportedMessageException e) {
        CompilerDirectives.transferToInterpreter();
        throw new AssertionError();
    }
}
 
Example #10
Source File: HashemObjectType.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@TruffleBoundary
@Specialization(guards = {"!receiver.getShape().isValid()"})
static void updateShape(DynamicObject receiver, String name, Object value) {
    /*
     * Slow path that we do not handle in compiled code. But no need to invalidate compiled
     * code.
     */
    CompilerDirectives.transferToInterpreter();
    receiver.updateShape();
    writeUncached(receiver, name, value);
}
 
Example #11
Source File: HashemWrapPrimitiveBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@TruffleBoundary
@Specialization
public Object doDefault(Object value) {
    if (value instanceof PrimitiveValueWrapper) {
        return value;
    } else {
        return new PrimitiveValueWrapper(value);
    }
}
 
Example #12
Source File: MapFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Specialization(guards = "SIZE.equals(member)")
static MapFunctionBase readMemberSize(MapFunction receiver, String member) {
    return new MapFunctionBase(arguments -> {
        if (arguments.length == 0) {
            throw ArityException.create(1, 0);
        }
        try {
            return receiver.size((MapArgObject) arguments[0], Arrays.copyOfRange(arguments, 1, arguments.length, MapArgObject[].class));
        } catch (ClassCastException | ArrayStoreException e) {
            throw UnsupportedTypeException.create(arguments, "expected argument objects");
        }
    });
}
 
Example #13
Source File: HashemJfarzandBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization
public JsonObject jfarzand(String jsonString, @CachedContext(HashemLanguage.class) HashemContext context) {
    try {
        final HashMap jsonNode = objectMapper.readValue(jsonString, HashMap.class);
        final JsonObject jsonObject = new JsonObject(jsonNode);
        return jsonObject;
    } catch (IOException e) {
        throw new HashemException(String.format("%s is not a valid json!", jsonString), this);
    }
}
 
Example #14
Source File: HashemEqualNode.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization
protected boolean equal(HashemBebin left, HashemBebin right) {
    /*
     * Our function registry maintains one canonical SLFunction object per function name, so we
     * do not need equals().
     */
    return left == right;
}
 
Example #15
Source File: HashemWriteLocalVariableNode.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
/**
 * Specialized method to write a primitive {@code long} value. This is only possible if the
 * local variable also has currently the type {@code long} or was never written before,
 * therefore a Truffle DSL {@link #isLongOrIllegal(VirtualFrame) custom guard} is specified.
 */
@Specialization(guards = "isLongOrIllegal(frame)")
protected long writeLong(VirtualFrame frame, long value) {
    /* Initialize type on first write of the local variable. No-op if kind is already Long. */
    frame.getFrameDescriptor().setFrameSlotKind(getSlot(), FrameSlotKind.Long);

    frame.setLong(getSlot(), value);
    return value;
}
 
Example #16
Source File: HashemBebin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
/**
 * Slow-path code for a call, used when the polymorphic inline cache exceeded its maximum
 * size specified in <code>INLINE_CACHE_SIZE</code>. Such calls are not optimized any
 * further, e.g., no method inlining is performed.
 */
@Specialization(replaces = "doDirect")
protected static Object doIndirect(HashemBebin function, Object[] arguments,
                                   @Cached IndirectCallNode callNode) {
    /*
     *Hashemi has a quite simple call lookup: just ask the function for the current call target,
     * and call it.
     */
    return callNode.call(function.getCallTarget(), arguments);
}
 
Example #17
Source File: HashemWebServerBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization
public HashemWebServer webserver(long port, @CachedContext(HashemLanguage.class) HashemContext context) {
    if (context.getWebServer(port) == null) {
        HashemWebServer hashemWebServer = doBuildServer(port);
        context.addWebServer(port, hashemWebServer);
        return hashemWebServer;
    }
    return context.getWebServer(port);
}
 
Example #18
Source File: HashemReadLocalVariableNode.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization(guards = "frame.isLong(getSlot())")
protected long readLong(VirtualFrame frame) {
    /*
     * When the FrameSlotKind is Long, we know that only primitive long values have ever been
     * written to the local variable. So we do not need to check that the frame really contains
     * a primitive long value.
     */
    return FrameUtil.getLongSafe(frame, getSlot());
}
 
Example #19
Source File: HashemDivNode.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization(rewriteOn = ArithmeticException.class)
protected long div(long left, long right) throws ArithmeticException {
    long result = left / right;
    /*
     * The division overflows if left is Long.MIN_VALUE and right is -1.
     */
    if ((left & right & result) < 0) {
        throw new ArithmeticException("long overflow");
    }
    return result;
}
 
Example #20
Source File: HashemReadPropertyNode.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization(guards = "objects.hasMembers(receiver)", limit = "LIBRARY_LIMIT")
protected Object writeObject(Object receiver, Object name,
                             @CachedLibrary("receiver") InteropLibrary objects,
                             @Cached HashemToMemberNode asMember) {
    try {
        return objects.readMember(receiver, asMember.execute(name));
    } catch (UnsupportedMessageException | UnknownIdentifierException e) {
        // read was not successful. In Hashemi we only have basic support for errors.
        throw HashemUndefinedNameException.undefinedProperty(this, name);
    }
}
 
Example #21
Source File: HashemObjectType.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
/**
 * Polymorphic inline cache for writing a property that does not exist yet (shape change is
 * necessary).
 */
@Specialization(limit = "CACHE_LIMIT", //
                guards = {
                                "cachedName.equals(name)",
                                "receiver.getShape() == oldShape",
                                "oldLocation == null",
                                "canStore(newLocation, value)"
                }, //
                assumptions = {
                                "oldShape.getValidAssumption()",
                                "newShape.getValidAssumption()"
                })
@SuppressWarnings("unused")
static void writeNewPropertyCached(DynamicObject receiver, String name, Object value,
                @Cached("name") Object cachedName,
                @Cached("receiver.getShape()") Shape oldShape,
                @Cached("lookupLocation(oldShape, name, value)") Location oldLocation,
                @Cached("defineProperty(oldShape, name, value)") Shape newShape,
                @Cached("lookupLocation(newShape, name)") Location newLocation) {
    try {
        newLocation.set(receiver, value, oldShape, newShape);

    } catch (IncompatibleLocationException ex) {
        /* Our guards ensure that the value can be stored, so this cannot happen. */
        throw new IllegalStateException(ex);
    }
}
 
Example #22
Source File: HashemObjectType.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
/**
 * Polymorphic inline cache for a limited number of distinct property names and shapes.
 */
@Specialization(limit = "CACHE_LIMIT", //
                guards = {
                                "receiver.getShape() == cachedShape",
                                "cachedName.equals(name)"
                }, //
                assumptions = "cachedShape.getValidAssumption()")
static Object readCached(DynamicObject receiver, @SuppressWarnings("unused") String name,
                @SuppressWarnings("unused") @Cached("name") String cachedName,
                @Cached("receiver.getShape()") Shape cachedShape,
                @Cached("lookupLocation(cachedShape, name)") Location location) {
    return location.get(receiver, cachedShape);
}
 
Example #23
Source File: HashemObjectType.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
/**
 * The generic case is used if the number of shapes accessed overflows the limit of the
 * polymorphic inline cache.
 */
@TruffleBoundary
@Specialization(replaces = {"readCached"}, guards = "receiver.getShape().isValid()")
static Object readUncached(DynamicObject receiver, String name) throws UnknownIdentifierException {
    Object result = receiver.get(name);
    if (result == null) {
        /* Property does not exist. */
        throw UnknownIdentifierException.create(name);
    }
    return result;
}
 
Example #24
Source File: HashemBekhoonBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization
public String bekhoon(@CachedContext(HashemLanguage.class) HashemContext context) {
    String result = doRead(context.getInput());
    if (result == null) {
        /*
         * We do not have a sophisticated end of file handling, so returning an empty string is
         * a reasonable alternative. Note that the Java null value should never be used, since
         * it can interfere with the specialization logic in generated source code.
         */
        result = "";
    }
    return result;
}
 
Example #25
Source File: HashemEvalBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization(guards = {"stringsEqual(cachedId, id)", "stringsEqual(cachedCode, code)"})
public Object evalCached(String id, String code,
                @Cached("id") String cachedId,
                @Cached("code") String cachedCode,
                @CachedContext(HashemLanguage.class) HashemContext context,
                @Cached("create(parse(id, code, context))") DirectCallNode callNode) {
    return callNode.call(new Object[]{});
}
 
Example #26
Source File: HashemDefineFunctionBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@TruffleBoundary
@Specialization
public String defineFunction(String code, @CachedContext(HashemLanguage.class) HashemContext context) {
    // @formatter:off
    Source source = Source.newBuilder(HashemLanguage.ID, code, "[defineFunction]").
        build();
    // @formatter:on
    /* The same parsing code as for parsing the initial source. */
    context.getFunctionRegistry().register(source);

    return code;
}
 
Example #27
Source File: HashemGetSizeBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization(limit = "3")
public Object getSize(Object obj, @CachedLibrary("obj") InteropLibrary arrays) {
    try {
        return arrays.getArraySize(obj);
    } catch (UnsupportedMessageException e) {
        throw new HashemException("Element is not a valid array.", this);
    }
}
 
Example #28
Source File: HashemAddHandlerBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization
public String addHandler(HashemWebServer server,
                         HashemBebin source,
                         @CachedContext(HashemLanguage.class) HashemContext context,
                         @Cached() IndirectCallNode callNode) {
    return doAddHandler(server, source, context, callNode);
}
 
Example #29
Source File: HashemWriteLocalVariableNode.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Specialization(guards = "isBooleanOrIllegal(frame)")
protected boolean writeBoolean(VirtualFrame frame, boolean value) {
    /* Initialize type on first write of the local variable. No-op if kind is already Long. */
    frame.getFrameDescriptor().setFrameSlotKind(getSlot(), FrameSlotKind.Boolean);

    frame.setBoolean(getSlot(), value);
    return value;
}
 
Example #30
Source File: HashemUnboxNode.java    From mr-hashemi with Universal Permissive License v1.0 4 votes vote down vote up
@Specialization
protected static HashemBebin fromFunction(HashemBebin value) {
    return value;
}