use of com.oracle.graal.pointsto.meta.HostedProviders in project graal by oracle.
the class NativeImageGenerator method registerGraphBuilderPlugins.
public static void registerGraphBuilderPlugins(FeatureHandler featureHandler, RuntimeConfiguration runtimeConfig, HostedProviders providers, AnalysisMetaAccess aMetaAccess, AnalysisUniverse aUniverse, HostedMetaAccess hMetaAccess, HostedUniverse hUniverse, NativeLibraries nativeLibs, ImageClassLoader loader, boolean analysis, boolean hosted) {
assert !analysis || hosted : "analysis must always be hosted";
GraphBuilderConfiguration.Plugins plugins = new GraphBuilderConfiguration.Plugins(new SubstitutionInvocationPlugins());
WordOperationPlugin wordOperationPlugin = new WordOperationPlugin(providers.getSnippetReflection(), providers.getWordTypes());
SubstrateReplacements replacements = (SubstrateReplacements) providers.getReplacements();
plugins.appendInlineInvokePlugin(replacements);
plugins.appendNodePlugin(new IntrinsifyMethodHandlesInvocationPlugin(providers, aUniverse, hUniverse));
plugins.appendNodePlugin(new DeletedFieldsPlugin());
plugins.appendNodePlugin(new InjectedAccessorsPlugin());
plugins.appendNodePlugin(new ConstantFoldLoadFieldPlugin());
plugins.appendNodePlugin(new CInterfaceInvocationPlugin(providers.getMetaAccess(), providers.getSnippetReflection(), providers.getWordTypes(), nativeLibs));
plugins.appendNodePlugin(new LocalizationFeature.CharsetNodePlugin());
plugins.appendInlineInvokePlugin(wordOperationPlugin);
plugins.appendTypePlugin(wordOperationPlugin);
plugins.appendTypePlugin(new TrustedInterfaceTypePlugin());
plugins.appendNodePlugin(wordOperationPlugin);
plugins.appendNodePlugin(new ImplicitExceptionsPlugin(providers.getMetaAccess(), providers.getForeignCalls()));
featureHandler.forEachGraalFeature(feature -> feature.registerNodePlugins(analysis ? aMetaAccess : hMetaAccess, plugins, analysis, hosted));
HostedSnippetReflectionProvider hostedSnippetReflection = new HostedSnippetReflectionProvider((SVMHost) aUniverse.getHostVM());
NodeIntrinsificationProvider nodeIntrinsificationProvider = new NodeIntrinsificationProvider(providers.getMetaAccess(), hostedSnippetReflection, providers.getForeignCalls(), providers.getLowerer(), providers.getWordTypes());
for (Class<? extends NodeIntrinsicPluginFactory> factoryClass : loader.findSubclasses(NodeIntrinsicPluginFactory.class)) {
if (!Modifier.isAbstract(factoryClass.getModifiers()) && !factoryClass.getName().contains("hotspot")) {
NodeIntrinsicPluginFactory factory;
try {
factory = factoryClass.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
throw VMError.shouldNotReachHere(ex);
}
factory.registerPlugins(plugins.getInvocationPlugins(), nodeIntrinsificationProvider);
}
}
BytecodeProvider replacementBytecodeProvider = replacements.getDefaultReplacementBytecodeProvider();
StandardGraphBuilderPlugins.registerInvocationPlugins(providers.getMetaAccess(), providers.getSnippetReflection(), plugins.getInvocationPlugins(), replacementBytecodeProvider, !hosted);
AMD64GraphBuilderPlugins.register(plugins, replacementBytecodeProvider, (AMD64) ConfigurationValues.getTarget().arch, true);
/*
* When the context is hosted, i.e., ahead-of-time compilation, and after the analysis we
* need the hosted meta access.
*/
MetaAccessProvider pluginsMetaAccess = hosted && !analysis ? hMetaAccess : aMetaAccess;
assert pluginsMetaAccess != null;
SubstrateGraphBuilderPlugins.registerInvocationPlugins(pluginsMetaAccess, providers.getConstantReflection(), hostedSnippetReflection, plugins.getInvocationPlugins(), replacementBytecodeProvider, analysis);
featureHandler.forEachGraalFeature(feature -> feature.registerInvocationPlugins(providers, hostedSnippetReflection, plugins.getInvocationPlugins(), hosted));
providers.setGraphBuilderPlugins(plugins);
replacements.setGraphBuilderPlugins(plugins);
if (runtimeConfig != null && runtimeConfig.getProviders() instanceof HostedProviders) {
((HostedProviders) runtimeConfig.getProviders()).setGraphBuilderPlugins(plugins);
for (Backend backend : runtimeConfig.getBackends()) {
((HostedProviders) backend.getProviders()).setGraphBuilderPlugins(plugins);
}
}
}
use of com.oracle.graal.pointsto.meta.HostedProviders in project graal by oracle.
the class CEntryPointCallStubMethod method adaptParameterTypes.
private EnumInfo[] adaptParameterTypes(HostedProviders providers, NativeLibraries nativeLibraries, HostedGraphKit kit, JavaType[] parameterTypes, JavaType[] parameterLoadTypes, Purpose purpose) {
EnumInfo[] parameterEnumInfos = null;
for (int i = 0; i < parameterTypes.length; i++) {
if (!parameterTypes[i].getJavaKind().isPrimitive() && !providers.getWordTypes().isWord(parameterTypes[i])) {
ElementInfo typeInfo = nativeLibraries.findElementInfo(parameterTypes[i]);
if (typeInfo instanceof EnumInfo) {
UserError.guarantee(typeInfo.getChildren().stream().anyMatch(EnumLookupInfo.class::isInstance), "Enum class " + parameterTypes[i].toJavaName() + " needs a method that is annotated with @" + CEnumLookup.class + " because it is used as a parameter of an entry point method: " + targetMethod.format("%H.%n(%p)"));
if (parameterEnumInfos == null) {
parameterEnumInfos = new EnumInfo[parameterTypes.length];
}
parameterEnumInfos[i] = (EnumInfo) typeInfo;
parameterLoadTypes[i] = providers.getMetaAccess().lookupJavaType(cEnumParameterKind.toJavaClass());
final int parameterIndex = i;
FrameState initialState = kit.getGraph().start().stateAfter();
Iterator<ValueNode> matchingNodes = initialState.values().filter(node -> ((ParameterNode) node).index() == parameterIndex).iterator();
ValueNode parameterNode = matchingNodes.next();
assert !matchingNodes.hasNext() && parameterNode.usages().filter(n -> n != initialState).isEmpty();
parameterNode.setStamp(StampFactory.forKind(cEnumParameterKind));
} else if (purpose != Purpose.ANALYSIS) {
// for analysis test cases: abort only during compilation
throw UserError.abort("Entry point method parameter types are restricted to primitive types, word types and enumerations (@" + CEnum.class.getSimpleName() + "): " + targetMethod.format("%H.%n(%p)"));
}
}
}
return parameterEnumInfos;
}
use of com.oracle.graal.pointsto.meta.HostedProviders in project graal by oracle.
the class CompileQueue method defaultParseFunction.
@SuppressWarnings("try")
private void defaultParseFunction(DebugContext debug, HostedMethod method, CompileReason reason, RuntimeConfiguration config) {
if (method.getAnnotation(Fold.class) != null || method.getAnnotation(NodeIntrinsic.class) != null) {
throw VMError.shouldNotReachHere("Parsing method annotated with @Fold or @NodeIntrinsic: " + method.format("%H.%n(%p)"));
}
HostedProviders providers = (HostedProviders) config.lookupBackend(method).getProviders();
boolean needParsing = false;
OptionValues options = HostedOptionValues.singleton();
StructuredGraph graph = method.buildGraph(debug, method, providers, Purpose.AOT_COMPILATION);
if (graph == null) {
InvocationPlugin plugin = providers.getGraphBuilderPlugins().getInvocationPlugins().lookupInvocation(method);
if (plugin != null && !plugin.inlineOnly()) {
Bytecode code = new ResolvedJavaMethodBytecode(method);
// DebugContext debug = new DebugContext(options, providers.getSnippetReflection());
graph = new SubstrateIntrinsicGraphBuilder(debug.getOptions(), debug, providers.getMetaAccess(), providers.getConstantReflection(), providers.getConstantFieldProvider(), providers.getStampProvider(), code).buildGraph(plugin);
}
}
if (graph == null && method.isNative() && NativeImageOptions.ReportUnsupportedElementsAtRuntime.getValue()) {
graph = DeletedMethod.buildGraph(debug, method, providers, DeletedMethod.NATIVE_MESSAGE);
}
if (graph == null) {
needParsing = true;
if (!method.compilationInfo.isDeoptTarget()) {
/*
* Disabling liveness analysis preserves the values of local variables beyond the
* bytecode-liveness. This greatly helps debugging. When local variable numbers are
* reused by javac, local variables can still get illegal values. Since we cannot
* "restore" such illegal values during deoptimization, we must do liveness analysis
* for deoptimization target methods.
*/
options = new OptionValues(options, GraalOptions.OptClearNonLiveLocals, false);
}
graph = new StructuredGraph.Builder(options, debug).method(method).build();
}
try (DebugContext.Scope s = debug.scope("Parsing", graph, method, this)) {
try {
if (needParsing) {
GraphBuilderConfiguration gbConf = createHostedGraphBuilderConfiguration(providers, method);
new HostedGraphBuilderPhase(providers.getMetaAccess(), providers.getStampProvider(), providers.getConstantReflection(), providers.getConstantFieldProvider(), gbConf, optimisticOpts, null, providers.getWordTypes()).apply(graph);
} else {
graph.setGuardsStage(GuardsStage.FIXED_DEOPTS);
}
new DeadStoreRemovalPhase().apply(graph);
new DevirtualizeCallsPhase().apply(graph);
new CanonicalizerPhase().apply(graph, new PhaseContext(providers));
/*
* The StrengthenStampsPhase may not insert type check nodes for specialized
* methods, because we would get type state mismatches regarding Const<Type> !=
* <Type>
*/
/*
* cwimmer: the old, commented out, condition always disabled checking of static
* analysis results. Therefore, the checks are broken right now.
*/
// new StrengthenStampsPhase(BootImageOptions.CheckStaticAnalysisResults.getValue()
// && method.compilationInfo.deoptTarget != null &&
// !method.compilationInfo.isDeoptTarget).apply(graph);
new StrengthenStampsPhase(false).apply(graph);
new CanonicalizerPhase().apply(graph, new PhaseContext(providers));
/* Check that graph is in good shape after parsing. */
assert GraphOrder.assertSchedulableGraph(graph);
method.compilationInfo.graph = graph;
for (Invoke invoke : graph.getInvokes()) {
if (!canBeUsedForInlining(invoke)) {
invoke.setUseForInlining(false);
}
if (invoke.callTarget() instanceof MethodCallTargetNode) {
MethodCallTargetNode targetNode = (MethodCallTargetNode) invoke.callTarget();
HostedMethod invokeTarget = (HostedMethod) targetNode.targetMethod();
if (targetNode.invokeKind().isDirect()) {
if (invokeTarget.wrapped.isImplementationInvoked()) {
handleSpecialization(method, targetNode, invokeTarget, invokeTarget);
ensureParsed(invokeTarget, new DirectCallReason(method, reason));
}
} else {
for (HostedMethod invokeImplementation : invokeTarget.getImplementations()) {
handleSpecialization(method, targetNode, invokeTarget, invokeImplementation);
ensureParsed(invokeImplementation, new VirtualCallReason(method, invokeImplementation, reason));
}
}
}
}
} catch (Throwable ex) {
GraalError error = ex instanceof GraalError ? (GraalError) ex : new GraalError(ex);
error.addContext("method: " + method.format("%r %H.%n(%p)"));
throw error;
}
} catch (Throwable e) {
throw debug.handle(e);
}
}
use of com.oracle.graal.pointsto.meta.HostedProviders in project graal by oracle.
the class Target_com_oracle_truffle_api_interop_java_ObjectProxyHandler method beforeAnalysis.
@SuppressWarnings("deprecation")
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
BeforeAnalysisAccessImpl config = (BeforeAnalysisAccessImpl) access;
getLanguageClasses().forEach(config::registerForReflectiveInstantiation);
config.registerHierarchyForReflectiveInstantiation(TruffleInstrument.class);
config.registerHierarchyForReflectiveInstantiation(com.oracle.truffle.api.instrumentation.InstrumentableFactory.class);
if (useTruffleCompiler()) {
SubstrateTruffleRuntime truffleRuntime = (SubstrateTruffleRuntime) Truffle.getRuntime();
GraalFeature graalFeature = ImageSingletons.lookup(GraalFeature.class);
SnippetReflectionProvider snippetReflection = graalFeature.getHostedProviders().getSnippetReflection();
SubstrateTruffleCompiler truffleCompiler = truffleRuntime.initTruffleCompiler();
truffleRuntime.lookupCallMethods(config.getMetaAccess());
PartialEvaluator partialEvaluator = truffleCompiler.getPartialEvaluator();
registerKnownTruffleFields(config, partialEvaluator.getKnownTruffleTypes());
support.registerInterpreterEntryMethodsAsCompiled(partialEvaluator, access);
GraphBuilderConfiguration graphBuilderConfig = partialEvaluator.getConfigForParsing();
if (Options.TruffleInlineDuringParsing.getValue()) {
graphBuilderConfig.getPlugins().appendInlineInvokePlugin(new TruffleParsingInlineInvokePlugin(graalFeature.getHostedProviders().getReplacements(), graphBuilderConfig.getPlugins().getInvocationPlugins(), partialEvaluator, method -> includeCallee(method, null, null)));
}
registerNeverPartOfCompilation(graphBuilderConfig.getPlugins().getInvocationPlugins());
graphBuilderConfig.getPlugins().getInvocationPlugins().closeRegistration();
HostedProviders newHostedProviders = new HostedProviders(partialEvaluator.getProviders().getMetaAccess(), partialEvaluator.getProviders().getCodeCache(), partialEvaluator.getProviders().getConstantReflection(), new HostedTruffleConstantFieldProvider(partialEvaluator.getProviders().getConstantFieldProvider()), partialEvaluator.getProviders().getForeignCalls(), partialEvaluator.getProviders().getLowerer(), partialEvaluator.getProviders().getReplacements(), partialEvaluator.getProviders().getStampProvider(), snippetReflection, graalFeature.getHostedProviders().getWordTypes());
newHostedProviders.setGraphBuilderPlugins(graphBuilderConfig.getPlugins());
graalFeature.initializeRuntimeCompilationConfiguration(newHostedProviders, graphBuilderConfig, this::includeCallee, this::deoptimizeOnException);
for (ResolvedJavaMethod method : partialEvaluator.getCompilationRootMethods()) {
graalFeature.prepareMethodForRuntimeCompilation(method, config);
}
initializeMethodBlacklist(config.getMetaAccess());
/*
* Stack frames that are visited by Truffle-level stack walking must have full frame
* information available, otherwise SubstrateStackIntrospection cannot visit them.
*/
for (ResolvedJavaMethod method : truffleRuntime.getAnyFrameMethod()) {
graalFeature.requireFrameInformationForMethod(method);
/*
* To avoid corner case errors, we also force compilation of these methods. This
* only affects builds where no Truffle language is included, because any real
* language makes these methods reachable (and therefore compiled).
*/
config.registerAsCompiled((AnalysisMethod) method);
}
}
firstAnalysisRun = true;
}
use of com.oracle.graal.pointsto.meta.HostedProviders in project graal by oracle.
the class CEntryPointCallStubMethod method adaptReturnValue.
private ValueNode adaptReturnValue(ResolvedJavaMethod method, HostedProviders providers, Purpose purpose, UniverseMetaAccess metaAccess, NativeLibraries nativeLibraries, HostedGraphKit kit, ValueNode invokeValue) {
ValueNode returnValue = invokeValue;
if (returnValue.getStackKind().isPrimitive()) {
return returnValue;
}
JavaType returnType = method.getSignature().getReturnType(null);
ElementInfo typeInfo = nativeLibraries.findElementInfo(returnType);
if (typeInfo instanceof EnumInfo) {
UserError.guarantee(typeInfo.getChildren().stream().anyMatch(EnumValueInfo.class::isInstance), "Enum class " + returnType.toJavaName() + " needs a method that is annotated with @" + CEnumValue.class + " because it is used as the return type of an entry point method: " + targetMethod.format("%H.%n(%p)"));
IsNullNode isNull = kit.unique(new IsNullNode(returnValue));
kit.startIf(isNull, BranchProbabilityNode.VERY_SLOW_PATH_PROBABILITY);
kit.thenPart();
ResolvedJavaType enumExceptionType = metaAccess.lookupJavaType(RuntimeException.class);
NewInstanceNode enumException = kit.append(new NewInstanceNode(enumExceptionType, true));
Iterator<ResolvedJavaMethod> enumExceptionCtor = Arrays.stream(enumExceptionType.getDeclaredConstructors()).filter(c -> c.getSignature().getParameterCount(false) == 1 && c.getSignature().getParameterType(0, null).equals(metaAccess.lookupJavaType(String.class))).iterator();
ConstantNode enumExceptionMessage = kit.createConstant(kit.getConstantReflection().forString("null return value cannot be converted to a C enum value"), JavaKind.Object);
kit.createJavaCallWithExceptionAndUnwind(InvokeKind.Special, enumExceptionCtor.next(), enumException, enumExceptionMessage);
assert !enumExceptionCtor.hasNext();
kit.append(new CEntryPointLeaveNode(LeaveAction.ExceptionAbort, enumException));
kit.append(new DeadEndNode());
kit.endIf();
// Always return enum values as a signed word because it should never be a problem if
// the caller expects a narrower integer type and the various checks already handle
// replacements with word types
CInterfaceEnumTool tool = new CInterfaceEnumTool(providers.getMetaAccess(), providers.getSnippetReflection());
JavaKind cEnumReturnType = providers.getWordTypes().getWordKind();
assert !cEnumReturnType.isUnsigned() : "requires correct representation of signed values";
returnValue = tool.createEnumValueInvoke(kit, (EnumInfo) typeInfo, cEnumReturnType, returnValue);
} else if (purpose != Purpose.ANALYSIS) {
// for analysis test cases: abort only during compilation
throw UserError.abort("Entry point method return types are restricted to primitive types, word types and enumerations (@" + CEnum.class.getSimpleName() + "): " + targetMethod.format("%H.%n(%p)"));
}
return returnValue;
}
Aggregations