use of org.graalvm.compiler.debug.DebugContext in project graal by oracle.
the class TruffleGraphBuilderPlugins method logPerformanceWarningLocationNotConstant.
@SuppressWarnings("try")
static void logPerformanceWarningLocationNotConstant(ValueNode location, ResolvedJavaMethod targetMethod, UnsafeAccessNode access) {
if (!PartialEvaluator.PerformanceInformationHandler.isEnabled()) {
return;
}
StructuredGraph graph = location.graph();
DebugContext debug = access.getDebug();
try (DebugContext.Scope s = debug.scope("TrufflePerformanceWarnings", graph)) {
TruffleDebugJavaMethod truffleMethod = debug.contextLookup(TruffleDebugJavaMethod.class);
String callTargetName = truffleMethod != null ? truffleMethod.getName() : "";
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("location", location);
properties.put("method", targetMethod.format("%h.%n"));
PartialEvaluator.PerformanceInformationHandler.logPerformanceWarning(callTargetName, Collections.singletonList(access), "location argument not PE-constant", properties);
debug.dump(DebugContext.VERBOSE_LEVEL, graph, "perf warn: location argument not PE-constant: %s", location);
} catch (Throwable t) {
debug.handle(t);
}
}
use of org.graalvm.compiler.debug.DebugContext in project graal by oracle.
the class ObjectCloneNode method getLoweredSnippetGraph.
@Override
@SuppressWarnings("try")
protected StructuredGraph getLoweredSnippetGraph(LoweringTool tool) {
ResolvedJavaType type = StampTool.typeOrNull(getObject());
if (type != null) {
if (type.isArray()) {
Method method = ObjectCloneSnippets.arrayCloneMethods.get(type.getComponentType().getJavaKind());
if (method != null) {
final ResolvedJavaMethod snippetMethod = tool.getMetaAccess().lookupJavaMethod(method);
final Replacements replacements = tool.getReplacements();
StructuredGraph snippetGraph = null;
DebugContext debug = getDebug();
try (DebugContext.Scope s = debug.scope("ArrayCloneSnippet", snippetMethod)) {
snippetGraph = replacements.getSnippet(snippetMethod, null, graph().trackNodeSourcePosition(), this.getNodeSourcePosition());
} catch (Throwable e) {
throw debug.handle(e);
}
assert snippetGraph != null : "ObjectCloneSnippets should be installed";
assert getConcreteType(stamp(NodeView.DEFAULT)) != null;
return lowerReplacement((StructuredGraph) snippetGraph.copy(getDebug()), tool);
}
assert false : "unhandled array type " + type.getComponentType().getJavaKind();
} else {
Assumptions assumptions = graph().getAssumptions();
type = getConcreteType(getObject().stamp(NodeView.DEFAULT));
if (type != null) {
StructuredGraph newGraph = new StructuredGraph.Builder(graph().getOptions(), graph().getDebug(), AllowAssumptions.ifNonNull(assumptions)).build();
ParameterNode param = newGraph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(getObject().stamp(NodeView.DEFAULT))));
NewInstanceNode newInstance = newGraph.add(new NewInstanceNode(type, true));
newGraph.addAfterFixed(newGraph.start(), newInstance);
ReturnNode returnNode = newGraph.add(new ReturnNode(newInstance));
newGraph.addAfterFixed(newInstance, returnNode);
for (ResolvedJavaField field : type.getInstanceFields(true)) {
LoadFieldNode load = newGraph.add(LoadFieldNode.create(newGraph.getAssumptions(), param, field));
newGraph.addBeforeFixed(returnNode, load);
newGraph.addBeforeFixed(returnNode, newGraph.add(new StoreFieldNode(newInstance, field, load)));
}
assert getConcreteType(stamp(NodeView.DEFAULT)) != null;
return lowerReplacement(newGraph, tool);
}
}
}
assert getConcreteType(stamp(NodeView.DEFAULT)) == null;
return null;
}
use of org.graalvm.compiler.debug.DebugContext in project graal by oracle.
the class OnStackReplacementPhase method run.
@Override
@SuppressWarnings("try")
protected void run(StructuredGraph graph) {
DebugContext debug = graph.getDebug();
if (graph.getEntryBCI() == JVMCICompiler.INVOCATION_ENTRY_BCI) {
// used.
assert graph.getNodes(EntryMarkerNode.TYPE).isEmpty();
return;
}
debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement initial at bci %d", graph.getEntryBCI());
EntryMarkerNode osr;
int maxIterations = -1;
int iterations = 0;
final EntryMarkerNode originalOSRNode = getEntryMarker(graph);
final LoopBeginNode originalOSRLoop = osrLoop(originalOSRNode);
final boolean currentOSRWithLocks = osrWithLocks(originalOSRNode);
if (originalOSRLoop == null) {
/*
* OSR with Locks: We do not have an OSR loop for the original OSR bci. Therefore we
* cannot decide where to deopt and which framestate will be used. In the worst case the
* framestate of the OSR entry would be used.
*/
throw new PermanentBailoutException("OSR compilation without OSR entry loop.");
}
if (!supportOSRWithLocks(graph.getOptions()) && currentOSRWithLocks) {
throw new PermanentBailoutException("OSR with locks disabled.");
}
do {
osr = getEntryMarker(graph);
LoopsData loops = new LoopsData(graph);
// Find the loop that contains the EntryMarker
Loop<Block> l = loops.getCFG().getNodeToBlock().get(osr).getLoop();
if (l == null) {
break;
}
iterations++;
if (maxIterations == -1) {
maxIterations = l.getDepth();
} else if (iterations > maxIterations) {
throw GraalError.shouldNotReachHere();
}
// Peel the outermost loop first
while (l.getParent() != null) {
l = l.getParent();
}
LoopTransformations.peel(loops.loop(l));
osr.replaceAtUsages(InputType.Guard, AbstractBeginNode.prevBegin((FixedNode) osr.predecessor()));
for (Node usage : osr.usages().snapshot()) {
EntryProxyNode proxy = (EntryProxyNode) usage;
proxy.replaceAndDelete(proxy.value());
}
GraphUtil.removeFixedWithUnusedInputs(osr);
debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement loop peeling result");
} while (true);
StartNode start = graph.start();
FrameState osrState = osr.stateAfter();
OSRStartNode osrStart;
try (DebugCloseable context = osr.withNodeSourcePosition()) {
osr.setStateAfter(null);
osrStart = graph.add(new OSRStartNode());
FixedNode next = osr.next();
osr.setNext(null);
osrStart.setNext(next);
graph.setStart(osrStart);
osrStart.setStateAfter(osrState);
debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after setting OSR start");
final int localsSize = osrState.localsSize();
final int locksSize = osrState.locksSize();
for (int i = 0; i < localsSize + locksSize; i++) {
ValueNode value = null;
if (i >= localsSize) {
value = osrState.lockAt(i - localsSize);
} else {
value = osrState.localAt(i);
}
if (value instanceof EntryProxyNode) {
EntryProxyNode proxy = (EntryProxyNode) value;
/*
* We need to drop the stamp since the types we see during OSR may be too
* precise (if a branch was not parsed for example). In cases when this is
* possible, we insert a guard and narrow the OSRLocal stamp at its usages.
*/
Stamp narrowedStamp = proxy.value().stamp(NodeView.DEFAULT);
Stamp unrestrictedStamp = proxy.stamp(NodeView.DEFAULT).unrestricted();
ValueNode osrLocal;
if (i >= localsSize) {
osrLocal = graph.addOrUnique(new OSRLockNode(i - localsSize, unrestrictedStamp));
} else {
osrLocal = graph.addOrUnique(new OSRLocalNode(i, unrestrictedStamp));
}
// Speculate on the OSRLocal stamps that could be more precise.
OSRLocalSpeculationReason reason = new OSRLocalSpeculationReason(osrState.bci, narrowedStamp, i);
if (graph.getSpeculationLog().maySpeculate(reason) && osrLocal instanceof OSRLocalNode && value.getStackKind().equals(JavaKind.Object) && !narrowedStamp.isUnrestricted()) {
// Add guard.
LogicNode check = graph.addOrUniqueWithInputs(InstanceOfNode.createHelper((ObjectStamp) narrowedStamp, osrLocal, null, null));
JavaConstant constant = graph.getSpeculationLog().speculate(reason);
FixedGuardNode guard = graph.add(new FixedGuardNode(check, DeoptimizationReason.OptimizedTypeCheckViolated, DeoptimizationAction.InvalidateRecompile, constant, false));
graph.addAfterFixed(osrStart, guard);
// Replace with a more specific type at usages.
// We know that we are at the root,
// so we need to replace the proxy in the state.
proxy.replaceAtMatchingUsages(osrLocal, n -> n == osrState);
osrLocal = graph.addOrUnique(new PiNode(osrLocal, narrowedStamp, guard));
}
proxy.replaceAndDelete(osrLocal);
} else {
assert value == null || value instanceof OSRLocalNode;
}
}
osr.replaceAtUsages(InputType.Guard, osrStart);
}
debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after replacing entry proxies");
GraphUtil.killCFG(start);
debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
new DeadCodeEliminationPhase(Required).apply(graph);
if (currentOSRWithLocks) {
OsrWithLocksCount.increment(debug);
try (DebugCloseable context = osrStart.withNodeSourcePosition()) {
for (int i = osrState.monitorIdCount() - 1; i >= 0; --i) {
MonitorIdNode id = osrState.monitorIdAt(i);
ValueNode lockedObject = osrState.lockAt(i);
OSRMonitorEnterNode osrMonitorEnter = graph.add(new OSRMonitorEnterNode(lockedObject, id));
for (Node usage : id.usages()) {
if (usage instanceof AccessMonitorNode) {
AccessMonitorNode access = (AccessMonitorNode) usage;
access.setObject(lockedObject);
}
}
FixedNode oldNext = osrStart.next();
oldNext.replaceAtPredecessor(null);
osrMonitorEnter.setNext(oldNext);
osrStart.setNext(osrMonitorEnter);
}
}
debug.dump(DebugContext.DETAILED_LEVEL, graph, "After inserting OSR monitor enters");
/*
* Ensure balanced monitorenter - monitorexit
*
* Ensure that there is no monitor exit without a monitor enter in the graph. If there
* is one this can only be done by bytecode as we have the monitor enter before the OSR
* loop but the exit in a path of the loop that must be under a condition, else it will
* throw an IllegalStateException anyway in the 2.iteration
*/
for (MonitorExitNode exit : graph.getNodes(MonitorExitNode.TYPE)) {
MonitorIdNode id = exit.getMonitorId();
if (id.usages().filter(MonitorEnterNode.class).count() != 1) {
throw new PermanentBailoutException("Unbalanced monitor enter-exit in OSR compilation with locks. Object is locked before the loop but released inside the loop.");
}
}
}
debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
new DeadCodeEliminationPhase(Required).apply(graph);
/*
* There must not be any parameter nodes left after OSR compilation.
*/
assert graph.getNodes(ParameterNode.TYPE).count() == 0 : "OSR Compilation contains references to parameters.";
}
use of org.graalvm.compiler.debug.DebugContext in project graal by oracle.
the class ForeignCallStub method getGraph.
/**
* Creates a graph for this stub.
* <p>
* If the stub returns an object, the graph created corresponds to this pseudo code:
*
* <pre>
* Object foreignFunctionStub(args...) {
* foreignFunction(currentThread, args);
* if (clearPendingException(thread())) {
* getAndClearObjectResult(thread());
* DeoptimizeCallerNode.deopt(InvalidateReprofile, RuntimeConstraint);
* }
* return verifyObject(getAndClearObjectResult(thread()));
* }
* </pre>
*
* If the stub returns a primitive or word, the graph created corresponds to this pseudo code
* (using {@code int} as the primitive return type):
*
* <pre>
* int foreignFunctionStub(args...) {
* int result = foreignFunction(currentThread, args);
* if (clearPendingException(thread())) {
* DeoptimizeCallerNode.deopt(InvalidateReprofile, RuntimeConstraint);
* }
* return result;
* }
* </pre>
*
* If the stub is void, the graph created corresponds to this pseudo code:
*
* <pre>
* void foreignFunctionStub(args...) {
* foreignFunction(currentThread, args);
* if (clearPendingException(thread())) {
* DeoptimizeCallerNode.deopt(InvalidateReprofile, RuntimeConstraint);
* }
* }
* </pre>
*
* In each example above, the {@code currentThread} argument is the C++ JavaThread value (i.e.,
* %r15 on AMD64) and is only prepended if {@link #prependThread} is true.
*/
@Override
@SuppressWarnings("try")
protected StructuredGraph getGraph(DebugContext debug, CompilationIdentifier compilationId) {
WordTypes wordTypes = providers.getWordTypes();
Class<?>[] args = linkage.getDescriptor().getArgumentTypes();
boolean isObjectResult = !LIRKind.isValue(linkage.getOutgoingCallingConvention().getReturn());
try {
ResolvedJavaMethod thisMethod = providers.getMetaAccess().lookupJavaMethod(ForeignCallStub.class.getDeclaredMethod("getGraph", DebugContext.class, CompilationIdentifier.class));
GraphKit kit = new GraphKit(debug, thisMethod, providers, wordTypes, providers.getGraphBuilderPlugins(), compilationId, toString());
StructuredGraph graph = kit.getGraph();
ParameterNode[] params = createParameters(kit, args);
ReadRegisterNode thread = kit.append(new ReadRegisterNode(providers.getRegisters().getThreadRegister(), wordTypes.getWordKind(), true, false));
ValueNode result = createTargetCall(kit, params, thread);
kit.createInvoke(StubUtil.class, "handlePendingException", thread, ConstantNode.forBoolean(isObjectResult, graph));
if (isObjectResult) {
InvokeNode object = kit.createInvoke(HotSpotReplacementsUtil.class, "getAndClearObjectResult", thread);
result = kit.createInvoke(StubUtil.class, "verifyObject", object);
}
kit.append(new ReturnNode(linkage.getDescriptor().getResultType() == void.class ? null : result));
debug.dump(DebugContext.VERBOSE_LEVEL, graph, "Initial stub graph");
kit.inlineInvokes();
new RemoveValueProxyPhase().apply(graph);
debug.dump(DebugContext.VERBOSE_LEVEL, graph, "Stub graph before compilation");
return graph;
} catch (Exception e) {
throw GraalError.shouldNotReachHere(e);
}
}
use of org.graalvm.compiler.debug.DebugContext in project graal by oracle.
the class InlineableGraph method parseBytecodes.
/**
* This method builds the IR nodes for the given <code>method</code> and canonicalizes them.
* Provided profiling info is mature, the resulting graph is cached. The caller is responsible
* for cloning before modification.
* </p>
*/
@SuppressWarnings("try")
private static StructuredGraph parseBytecodes(ResolvedJavaMethod method, HighTierContext context, CanonicalizerPhase canonicalizer, StructuredGraph caller, boolean trackNodeSourcePosition) {
DebugContext debug = caller.getDebug();
StructuredGraph newGraph = new StructuredGraph.Builder(caller.getOptions(), debug, AllowAssumptions.ifNonNull(caller.getAssumptions())).method(method).trackNodeSourcePosition(trackNodeSourcePosition).build();
try (DebugContext.Scope s = debug.scope("InlineGraph", newGraph)) {
if (!caller.isUnsafeAccessTrackingEnabled()) {
newGraph.disableUnsafeAccessTracking();
}
if (context.getGraphBuilderSuite() != null) {
context.getGraphBuilderSuite().apply(newGraph, context);
}
assert newGraph.start().next() != null : "graph needs to be populated by the GraphBuilderSuite " + method + ", " + method.canBeInlined();
new DeadCodeEliminationPhase(Optional).apply(newGraph);
canonicalizer.apply(newGraph, context);
return newGraph;
} catch (Throwable e) {
throw debug.handle(e);
}
}
Aggregations