Java Code Examples for com.oracle.truffle.api.CompilerDirectives#transferToInterpreter()

The following examples show how to use com.oracle.truffle.api.CompilerDirectives#transferToInterpreter() . 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: 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 2
Source File: Device.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ExportMessage
Object readMember(String memberName,
                @Shared("memberName") @Cached("createIdentityProfile()") ValueProfile memberProfile) throws UnknownIdentifierException {
    if (!isMemberReadable(memberName, memberProfile)) {
        CompilerDirectives.transferToInterpreter();
        throw UnknownIdentifierException.create(memberName);
    }
    if (ID.equals(memberName)) {
        return deviceId;
    }
    if (PROPERTIES.equals(memberName)) {
        return properties;
    }
    if (IS_CURRENT.equals(memberName)) {
        return new IsCurrentFunction(deviceId, runtime);
    }
    if (SET_CURRENT.equals(memberName)) {
        return new SetCurrentFunction(deviceId, runtime);
    }
    CompilerDirectives.transferToInterpreter();
    throw UnknownIdentifierException.create(memberName);
}
 
Example 3
Source File: MultiDimDeviceArray.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ExportMessage
Object readMember(String member,
                @Shared("member") @Cached("createIdentityProfile()") ValueProfile memberProfile) throws UnknownIdentifierException {
    if (!isMemberReadable(member, memberProfile)) {
        CompilerDirectives.transferToInterpreter();
        throw UnknownIdentifierException.create(member);
    }
    if (POINTER.equals(memberProfile.profile(member))) {
        return getPointer();
    }
    if (IS_MEMORY_FREED.equals(memberProfile.profile(member))) {
        return arrayFreed;
    }
    if (FREE.equals(memberProfile.profile(member))) {
        return new MultiDimDeviceArrayFreeFunction();
    }
    CompilerDirectives.transferToInterpreter();
    throw new GrCUDAInternalException("trying to read unknown member '" + member + "'");
}
 
Example 4
Source File: Kernel.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ExportMessage
Object execute(Object[] arguments,
                @CachedLibrary(limit = "3") InteropLibrary gridSizeAccess,
                @CachedLibrary(limit = "3") InteropLibrary gridSizeElementAccess,
                @CachedLibrary(limit = "3") InteropLibrary blockSizeAccess,
                @CachedLibrary(limit = "3") InteropLibrary blockSizeElementAccess,
                @CachedLibrary(limit = "3") InteropLibrary sharedMemoryAccess) throws UnsupportedTypeException, ArityException {
    int dynamicSharedMemoryBytes;
    if (arguments.length == 2) {
        dynamicSharedMemoryBytes = 0;
    } else if (arguments.length == 3) {
        // dynamic shared memory specified
        dynamicSharedMemoryBytes = extractNumber(arguments[2], "dynamicSharedMemory", sharedMemoryAccess);
    } else {
        CompilerDirectives.transferToInterpreter();
        throw ArityException.create(2, arguments.length);
    }

    Dim3 gridSize = extractDim3(arguments[0], "gridSize", gridSizeAccess, gridSizeElementAccess);
    Dim3 blockSize = extractDim3(arguments[1], "blockSize", blockSizeAccess, blockSizeElementAccess);
    KernelConfig config = new KernelConfig(gridSize, blockSize, dynamicSharedMemoryBytes);

    return new ConfiguredKernel(this, config);
}
 
Example 5
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 6
Source File: TensorRTRegistry.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Object call(Object[] arguments) throws ArityException, UnsupportedTypeException, UnsupportedMessageException {
    checkArgumentLength(arguments, 3);
    int engineHandle = expectInt(arguments[0]);
    int batchSize = expectInt(arguments[1]);

    // extract pointers from buffers array argument
    Object bufferArg = arguments[2];
    if (!INTEROP.hasArrayElements(bufferArg)) {
        throw UnsupportedMessageException.create();
    }
    int numBuffers = (int) INTEROP.getArraySize(bufferArg);
    try (UnsafeHelper.PointerArray pointerArray = UnsafeHelper.createPointerArray(numBuffers)) {
        if (nfiFunction == null) {
            // load function symbol lazily
            CompilerDirectives.transferToInterpreterAndInvalidate();
            nfiFunction = factory.makeFunction(context.getCUDARuntime(), libraryPath, DEFAULT_LIBRARY_HINT);
        }
        for (int i = 0; i < numBuffers; ++i) {
            try {
                Object buffer = INTEROP.readArrayElement(bufferArg, i);
                if (!(buffer instanceof DeviceArray) && !(buffer instanceof GPUPointer)) {
                    UnsupportedTypeException.create(new Object[]{buffer});
                }
                pointerArray.setValueAt(i, INTEROP.asPointer(buffer));
            } catch (InvalidArrayIndexException e) {
                InvalidArrayIndexException.create(i);
            }
        }
        long stream = 0;
        long eventConsumed = 0;
        Object result = INTEROP.execute(nfiFunction, engineHandle, batchSize, pointerArray.getAddress(), stream, eventConsumed);
        if (!INTEROP.fitsInInt(result)) {
            CompilerDirectives.transferToInterpreter();
            throw new RuntimeException("result of 'enqueue' is not an int");
        }
        return INTEROP.asInt(result) == 1;
    }
}
 
Example 7
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 8
Source File: TensorRTRegistry.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@TruffleBoundary
public Object call(Object[] arguments) {
    try {
        if (nfiFunction == null) {
            // load function symbol lazily
            CompilerDirectives.transferToInterpreterAndInvalidate();
            nfiFunction = factory.makeFunction(context.getCUDARuntime(), libraryPath, DEFAULT_LIBRARY_HINT);
        }
        return INTEROP.execute(nfiFunction, arguments);
    } catch (InteropException e) {
        CompilerDirectives.transferToInterpreter();
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: DeviceArray.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExportMessage
public void writeArrayElement(long index, Object value,
                @CachedLibrary(limit = "3") InteropLibrary valueLibrary,
                @Shared("elementType") @Cached("createIdentityProfile()") ValueProfile elementTypeProfile) throws UnsupportedTypeException, InvalidArrayIndexException {
    if (arrayFreed) {
        CompilerDirectives.transferToInterpreter();
        throw new GrCUDAException(ACCESSED_FREED_MEMORY_MESSAGE);
    }
    if ((index < 0) || (index >= numElements)) {
        CompilerDirectives.transferToInterpreter();
        throw InvalidArrayIndexException.create(index);
    }
    try {
        switch (elementTypeProfile.profile(elementType)) {

            case CHAR:
                nativeView.setByte(index, valueLibrary.asByte(value));
                break;
            case SINT16:
                nativeView.setShort(index, valueLibrary.asShort(value));
                break;
            case SINT32:
                nativeView.setInt(index, valueLibrary.asInt(value));
                break;
            case SINT64:
                nativeView.setLong(index, valueLibrary.asLong(value));
                break;
            case FLOAT:
                // going via "double" to allow floats to be initialized with doubles
                nativeView.setFloat(index, (float) valueLibrary.asDouble(value));
                break;
            case DOUBLE:
                nativeView.setDouble(index, valueLibrary.asDouble(value));
                break;
        }
    } catch (UnsupportedMessageException e) {
        CompilerDirectives.transferToInterpreter();
        throw UnsupportedTypeException.create(new Object[]{value}, "value cannot be coerced to " + elementType);
    }
}
 
Example 10
Source File: StoragePrimitives.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Specialization(replaces = "newWithArgDirect", guards = "isInstantiable(receiver, size)")
protected static final AbstractSqueakObjectWithHash newWithArg(final ClassObject receiver, final long size,
                @Cached final SqueakObjectNewNode newNode,
                @CachedContext(SqueakLanguage.class) final SqueakImageContext image) {
    try {
        return newNode.execute(image, receiver, (int) size);
    } catch (final OutOfMemoryError e) {
        CompilerDirectives.transferToInterpreter();
        throw PrimitiveFailed.INSUFFICIENT_OBJECT_MEMORY;
    }
}
 
Example 11
Source File: MappedFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExportMessage
Object execute(Object[] arguments,
                @CachedLibrary("this.parent") InteropLibrary parentInterop) throws UnsupportedTypeException, ArityException, UnsupportedMessageException {
    if (arguments.length != 3) {
        CompilerDirectives.transferToInterpreter();
        throw ArityException.create(3, arguments.length);
    }
    return new ShreddedObject(parentInterop.execute(parent, arguments));
}
 
Example 12
Source File: DeviceArray.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExportMessage
public Object readArrayElement(long index) throws InvalidArrayIndexException {
    if ((index < 0) || (index >= values.length)) {
        CompilerDirectives.transferToInterpreter();
        throw InvalidArrayIndexException.create(index);
    }
    return values[(int) index];
}
 
Example 13
Source File: StoragePrimitives.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Specialization(replaces = "newDirect")
protected static final AbstractSqueakObjectWithHash newIndirect(final ClassObject receiver,
                @Cached final SqueakObjectNewNode newNode,
                @CachedContext(SqueakLanguage.class) final SqueakImageContext image) {
    try {
        return newNode.execute(image, receiver);
    } catch (final OutOfMemoryError e) {
        CompilerDirectives.transferToInterpreter();
        throw PrimitiveFailed.INSUFFICIENT_OBJECT_MEMORY;
    }
}
 
Example 14
Source File: MultiDimDeviceArrayView.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExportMessage
Object readArrayElement(long index,
                @Shared("elementType") @Cached("createIdentityProfile()") ValueProfile elementTypeProfile) throws InvalidArrayIndexException {
    if ((index < 0) || (index >= mdDeviceArray.getElementsInDimension(thisDimension))) {
        CompilerDirectives.transferToInterpreter();
        throw InvalidArrayIndexException.create(index);
    }
    if ((thisDimension + 1) == mdDeviceArray.getNumberDimensions()) {
        long flatIndex = offset + index * stride;
        switch (elementTypeProfile.profile(mdDeviceArray.getElementType())) {
            case CHAR:
                return mdDeviceArray.getNativeView().getByte(flatIndex);
            case SINT16:
                return mdDeviceArray.getNativeView().getShort(flatIndex);
            case SINT32:
                return mdDeviceArray.getNativeView().getInt(flatIndex);
            case SINT64:
                return mdDeviceArray.getNativeView().getLong(flatIndex);
            case FLOAT:
                return mdDeviceArray.getNativeView().getFloat(flatIndex);
            case DOUBLE:
                return mdDeviceArray.getNativeView().getDouble(flatIndex);
        }
        return null;
    } else {
        long off = offset + index * stride;
        long newStride = mdDeviceArray.getStrideInDimension(thisDimension + 1);
        return new MultiDimDeviceArrayView(mdDeviceArray, thisDimension + 1, off, newStride);
    }
}
 
Example 15
Source File: TypedMapDeviceArrayFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExportMessage
public Object execute(Object[] arguments,
                @Cached MapArrayNode mapNode) throws ArityException {
    if (arguments.length != 1) {
        CompilerDirectives.transferToInterpreter();
        throw ArityException.create(1, arguments.length);
    }
    return mapNode.execute(arguments[0], elementType, runtime);
}
 
Example 16
Source File: DeviceArray.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExportMessage
public long getArraySize() {
    if (arrayFreed) {
        CompilerDirectives.transferToInterpreter();
        throw new GrCUDAException(ACCESSED_FREED_MEMORY_MESSAGE);
    }
    return numElements;
}
 
Example 17
Source File: DispatchSendFromStackNode.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Override
public Object executeSend(final VirtualFrame frame, final NativeObject selector, final Object lookupResult, final Object receiver, final ClassObject rcvrClass) {
    CompilerDirectives.transferToInterpreter();
    throw new SqueakError(this, MiscUtils.format("%s>>#%s detected in headless mode. Aborting...", rcvrClass.getSqueakClassName(), selector.asStringUnsafe()));
}
 
Example 18
Source File: BindFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
@TruffleBoundary
/**
 * Bind to host function symbol from shared library.
 *
 * This call resolves the symbol immediately and not lazily after the first invocation. The
 * <code>bind</code> call supports two different overloaded forms.
 *
 * 1. The legacy form with 3-arguments:
 * <code>bind(libFileName, symbolName, nfiSignatureString)<code>
 *    where <code>symbolName</code> is the name of the symbol as it appears and the shared
 * library (possibly mangled) and <code>nfiSignatureString</code> is like
 * <code>(uint64, pointer, pointer, float): sint32</code>.
 *
 *
 * 2. The NIDL version with 2-arguments: <code>bind(libFileName, nidlSignatureString)</code>
 * where <code>nidlSignatureString</code> is like
 * <code>functionName(param1: uint64, param2: in pointer float, param3: out pointer float, param4: float): sint32</code>.
 * If the host function symbol is C++ mangled, prefix the keyword <code>cxx</code>, i.e.,
 * <code>cxx functionName(...)</code>.
 *
 * @param arguments string of length 2 or 3 containing the arguments for function
 *            <code>bind</code>.
 * @param HostFunction object
 */
public HostFunction call(Object[] arguments) throws UnsupportedTypeException, ArityException {
    if ((arguments.length != 2) && (arguments.length != 3)) {
        throw new GrCUDAException("bind function requires two or three arguments");
    }
    String libraryFile = expectString(arguments[0], "argument 1 of bind must be string (library filename)");
    String signature = (arguments.length == 2) ? expectString(arguments[1], "argument 2 of bind must be string (NIDL signature)").trim()
                    : expectString(arguments[2], "argument 3 of bind must be string (signature)").trim();
    String symbolName = (arguments.length == 3) ? expectString(arguments[1], "argument 2 of bind must be string (symbol name)").trim() : "";

    FunctionBinding binding = parseSignature(symbolName + signature);
    binding.setLibraryFileName(libraryFile);
    HostFunction hf = new HostFunction(binding, GrCUDALanguage.getCurrentLanguage().getContextReference().get().getCUDARuntime());
    try {
        hf.resolveSymbol();
    } catch (UnknownIdentifierException e) {
        CompilerDirectives.transferToInterpreter();
        throw new GrCUDAException(binding.getSymbolName() + " not found in " + libraryFile);
    }
    return hf;
}
 
Example 19
Source File: DispatchSendFromStackNode.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Override
public Object executeSend(final VirtualFrame frame, final NativeObject selector, final Object lookupResult, final Object receiver, final ClassObject rcvrClass) {
    CompilerDirectives.transferToInterpreter();
    // TODO: make this better
    throw new SqueakSyntaxError((PointersObject) FrameStackPopNNode.create(argumentCount).execute(frame)[0]);
}
 
Example 20
Source File: PrimitiveExceptions.java    From trufflesqueak with MIT License 4 votes vote down vote up
public static PrimitiveFailed andTransferToInterpreter(final int reason) {
    CompilerDirectives.transferToInterpreter();
    throw new PrimitiveFailed(reason);
}