comparison graal/com.oracle.truffle.api/src/com/oracle/truffle/api/tools/NodeExecCounter.java @ 18987:ac114ad31cdd

Truffle/Tools: a new framework for pluggable tools that gather Truffle execution data - Abstract com.oracle.truffle.api.instrument.TruffleTool defines, documents, and enforces a standard "life cycle": -- includes creation, installation, enabling/disabling, and disposing. -- data retrieval is tool dependent, but each is encouraged to provide a default print() method for demo & debugging - com.oracle.truffle.api.tools contains three instances, all language-agnostic: -- LineToProbesMap: existing utility used by the debugger, adapted to the frameowrk -- CoverageTracker: code coverage, tabulated by line -- NodeExecCounter: raw execution counts, tabulated by node type, can be filtered by SyntaxTag
author Michael Van De Vanter <michael.van.de.vanter@oracle.com>
date Tue, 27 Jan 2015 20:26:41 -0800
parents
children c7e57dffc5ad
comparison
equal deleted inserted replaced
18986:50b22daf6d53 18987:ac114ad31cdd
1 /*
2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package com.oracle.truffle.api.tools;
26
27 import java.io.*;
28 import java.util.*;
29 import java.util.concurrent.atomic.*;
30
31 import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
32 import com.oracle.truffle.api.frame.*;
33 import com.oracle.truffle.api.instrument.*;
34 import com.oracle.truffle.api.instrument.impl.*;
35 import com.oracle.truffle.api.nodes.*;
36 import com.oracle.truffle.api.nodes.Node.Child;
37
38 /**
39 * A {@link TruffleTool} that counts interpreter <em>execution calls</em> to AST nodes, tabulated by
40 * the type of called nodes; counting can be enabled <em>all</em> nodes or restricted to nodes with
41 * a specified {@linkplain SyntaxTag tag} that is presumed to be applied external to the tool.
42 * <p>
43 * <b>Tool Life Cycle</b>
44 * <p>
45 * See {@link TruffleTool} for the life cycle common to all such tools.
46 * </p>
47 * <b>Execution Counts</b>
48 * <p>
49 * <ul>
50 * <li>"Execution call" on a node is is defined as invocation of a node method that is instrumented
51 * to produce the event {@link TruffleEventReceiver#enter(Node, VirtualFrame)};</li>
52 * <li>Execution calls are tabulated only at <em>instrumented</em> nodes, i.e. those for which
53 * {@linkplain Node#isInstrumentable() isInstrumentable() == true};</li>
54 * <li>Execution calls are tabulated only at nodes present in the AST when originally created;
55 * dynamically added nodes will not be instrumented.</li>
56 * </ul>
57 * </p>
58 * <b>Failure Log</b>
59 * <p>
60 * For the benefit of language implementors, the tool maintains a log describing failed attempts to
61 * probe AST nodes. Most failures occur when the type of the wrapper created by
62 * {@link Node#createWrapperNode()} is not assignable to the relevant {@link Child} field in the
63 * node's parent.
64 * </p>
65 * <p>
66 * {@linkplain #reset() Resetting} the counts has no effect on the failure log.
67 * </p>
68 * <b>Results</b>
69 * <p>
70 * A modification-safe copy of the {@linkplain #getCounts() counts} can be retrieved at any time,
71 * without effect on the state of the tool.
72 * </p>
73 * <p>
74 * A "default" {@linkplain #print(PrintStream) print()} method can summarizes the current counts at
75 * any time in a simple textual format, without effect on the state of the tool.
76 * </p>
77 *
78 * @see Instrument
79 * @see SyntaxTag
80 * @see ProbeFailure
81 */
82 public final class NodeExecCounter extends TruffleTool {
83
84 /**
85 * Execution count for AST nodes of a particular type.
86 */
87 public interface NodeExecutionCount {
88 Class<?> nodeClass();
89
90 long executionCount();
91 }
92
93 /**
94 * Receiver for events at instrumented nodes. Counts are maintained in a shared table, so the
95 * receiver is stateless and can be shared by every {@link Instrument}.
96 */
97 private final TruffleEventReceiver eventReceiver = new DefaultEventReceiver() {
98 @Override
99 @TruffleBoundary
100 public void enter(Node node, VirtualFrame frame) {
101 if (isEnabled()) {
102 final Class<?> nodeClass = node.getClass();
103 AtomicLong nodeCounter = counters.get(nodeClass);
104 if (nodeCounter == null) {
105 nodeCounter = new AtomicLong();
106 counters.put(nodeClass, nodeCounter);
107 }
108 nodeCounter.getAndIncrement();
109 }
110 }
111 };
112
113 /** Counting data. */
114 private final Map<Class<?>, AtomicLong> counters = new HashMap<>();
115
116 /** Failure log. */
117 private final List<ProbeFailure> failures = new ArrayList<>();
118
119 /** For disposal. */
120 private final List<Instrument> instruments = new ArrayList<>();
121
122 /**
123 * If non-null, counting is restricted to nodes holding this tag.
124 */
125 private final SyntaxTag countingTag;
126
127 /**
128 * Prober used only when instrumenting every node.
129 */
130 private ASTProber astProber;
131
132 /**
133 * Listener used only when restricting counting to a specific tag.
134 */
135 private ProbeListener probeListener;
136
137 /**
138 * Create a per node-type execution counting tool for all nodes in subsequently created ASTs.
139 */
140 public NodeExecCounter() {
141 this.countingTag = null;
142 }
143
144 /**
145 * Creates a per-type execution counting for nodes tagged as specified in subsequently created
146 * ASTs.
147 */
148 public NodeExecCounter(SyntaxTag tag) {
149 this.countingTag = tag;
150 }
151
152 @Override
153 protected boolean internalInstall() {
154 if (countingTag == null) {
155 astProber = new ExecCounterASTProber();
156 Probe.registerASTProber(astProber);
157 } else {
158 probeListener = new NodeExecCounterProbeListener();
159 Probe.addProbeListener(probeListener);
160 }
161 return true;
162 }
163
164 @Override
165 protected void internalReset() {
166 counters.clear();
167 failures.clear();
168 }
169
170 @Override
171 protected void internalDispose() {
172 if (astProber != null) {
173 Probe.unregisterASTProber(astProber);
174 }
175 if (probeListener != null) {
176 Probe.removeProbeListener(probeListener);
177 }
178 for (Instrument instrument : instruments) {
179 instrument.dispose();
180 }
181 }
182
183 /**
184 * Gets a modification-safe summary of the current per-type node execution counts; does not
185 * affect the counts.
186 */
187 public NodeExecutionCount[] getCounts() {
188 final Collection<Map.Entry<Class<?>, AtomicLong>> entrySet = counters.entrySet();
189 final NodeExecutionCount[] result = new NodeExecCountImpl[entrySet.size()];
190 int i = 0;
191 for (Map.Entry<Class<?>, AtomicLong> entry : entrySet) {
192 result[i++] = new NodeExecCountImpl(entry.getKey(), entry.getValue().longValue());
193 }
194 return result;
195 }
196
197 /**
198 * Gets a log containing a report of every failed attempt to instrument a node.
199 */
200 public ProbeFailure[] getFailures() {
201 return failures.toArray(new ProbeFailure[failures.size()]);
202 }
203
204 /**
205 * A default printer for the current counts, producing lines of the form
206 * " <count> : <node type>" in descending order of count.
207 */
208 public void print(PrintStream out) {
209 print(out, false);
210 }
211
212 /**
213 * A default printer for the current counts, producing lines of the form
214 * " <count> : <node type>" in descending order of count.
215 *
216 * @param out
217 * @param verbose whether to describe nodes on which instrumentation failed
218 */
219 public void print(PrintStream out, boolean verbose) {
220
221 final long missedNodes = failures.size();
222 out.println();
223 if (countingTag == null) {
224 out.println("Execution counts by node type:");
225 } else {
226 out.println("\"" + countingTag.name() + "\"-tagged execution counts by node type:");
227 }
228 final StringBuilder disclaim = new StringBuilder("(");
229 if (missedNodes > 0) {
230 disclaim.append(Long.toString(missedNodes) + " original AST nodes not instrumented, ");
231 }
232 disclaim.append("dynamically added nodes not instrumented)");
233 out.println(disclaim.toString());
234 NodeExecutionCount[] execCounts = getCounts();
235 // Sort in descending order
236 Arrays.sort(execCounts, new Comparator<NodeExecutionCount>() {
237
238 public int compare(NodeExecutionCount o1, NodeExecutionCount o2) {
239 return Long.compare(o2.executionCount(), o1.executionCount());
240 }
241
242 });
243 for (NodeExecutionCount nodeCount : execCounts) {
244 out.format("%12d", nodeCount.executionCount());
245 out.println(" : " + nodeCount.nodeClass().getName());
246 }
247
248 if (verbose && missedNodes > 0) {
249 out.println("Instrumentation failures for execution counts:");
250
251 for (ProbeFailure failure : failures) {
252 out.println("\t" + failure.getMessage());
253 }
254 }
255 }
256
257 /**
258 * A prober that attempts to probe and instrument every node.
259 */
260 private class ExecCounterASTProber implements ASTProber, NodeVisitor {
261
262 public boolean visit(Node node) {
263
264 if (node.isInstrumentable()) {
265 try {
266 final Instrument instrument = Instrument.create(eventReceiver, "NodeExecCounter");
267 instruments.add(instrument);
268 node.probe().attach(instrument);
269 } catch (ProbeException ex) {
270 failures.add(ex.getFailure());
271 }
272 }
273 return true;
274 }
275
276 public void probeAST(Node node) {
277 node.accept(this);
278 }
279 }
280
281 /**
282 * A listener that assumes ASTs have been tagged external to this tool, and which instruments
283 * nodes holding a specified tag.
284 */
285 private class NodeExecCounterProbeListener extends DefaultProbeListener {
286
287 @Override
288 public void probeTaggedAs(Probe probe, SyntaxTag tag, Object tagValue) {
289 if (countingTag == tag) {
290 final Instrument instrument = Instrument.create(eventReceiver, NodeExecCounter.class.getSimpleName());
291 instruments.add(instrument);
292 probe.attach(instrument);
293 }
294 }
295 }
296
297 private static class NodeExecCountImpl implements NodeExecutionCount {
298
299 private final Class<?> nodeClass;
300 private final long count;
301
302 public NodeExecCountImpl(Class<?> nodeClass, long count) {
303 this.nodeClass = nodeClass;
304 this.count = count;
305 }
306
307 public Class<?> nodeClass() {
308 return nodeClass;
309 }
310
311 public long executionCount() {
312 return count;
313 }
314 }
315 }