1 /*
   2  * Copyright (c) 2013, 2016, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package org.graalvm.compiler.replacements;
  24 
  25 import static org.graalvm.compiler.core.common.GraalOptions.SnippetCounters;
  26 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_IGNORED;
  27 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_IGNORED;
  28 import static org.graalvm.compiler.replacements.SnippetTemplate.DEFAULT_REPLACER;
  29 
  30 import java.lang.reflect.Field;
  31 import java.util.Arrays;
  32 
  33 import org.graalvm.compiler.api.replacements.Fold;
  34 import org.graalvm.compiler.api.replacements.Snippet;
  35 import org.graalvm.compiler.api.replacements.Snippet.ConstantParameter;
  36 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
  37 import org.graalvm.compiler.core.common.LocationIdentity;
  38 import org.graalvm.compiler.core.common.type.StampFactory;
  39 import org.graalvm.compiler.debug.GraalError;
  40 import org.graalvm.compiler.graph.NodeClass;
  41 import org.graalvm.compiler.nodeinfo.NodeInfo;
  42 import org.graalvm.compiler.nodes.FixedWithNextNode;
  43 import org.graalvm.compiler.nodes.NamedLocationIdentity;
  44 import org.graalvm.compiler.nodes.StructuredGraph;
  45 import org.graalvm.compiler.nodes.ValueNode;
  46 import org.graalvm.compiler.nodes.spi.Lowerable;
  47 import org.graalvm.compiler.nodes.spi.LoweringTool;
  48 import org.graalvm.compiler.phases.util.Providers;
  49 import org.graalvm.compiler.replacements.SnippetTemplate.AbstractTemplates;
  50 import org.graalvm.compiler.replacements.SnippetTemplate.Arguments;
  51 import org.graalvm.compiler.replacements.SnippetTemplate.SnippetInfo;
  52 import org.graalvm.compiler.word.ObjectAccess;
  53 
  54 import jdk.vm.ci.code.TargetDescription;
  55 import sun.misc.Unsafe;
  56 
  57 /**
  58  * This node can be used to add a counter to the code that will estimate the dynamic number of calls
  59  * by adding an increment to the compiled code. This should of course only be used for
  60  * debugging/testing purposes.
  61  *
  62  * A unique counter will be created for each unique name passed to the constructor. Depending on the
  63  * value of withContext, the name of the root method is added to the counter's name.
  64  */
  65 @NodeInfo(cycles = CYCLES_IGNORED, size = SIZE_IGNORED)
  66 public class SnippetCounterNode extends FixedWithNextNode implements Lowerable {
  67 
  68     public static final NodeClass<SnippetCounterNode> TYPE = NodeClass.create(SnippetCounterNode.class);
  69 
  70     @Input protected ValueNode increment;
  71 
  72     protected final SnippetCounter counter;
  73 
  74     public SnippetCounterNode(SnippetCounter counter, ValueNode increment) {
  75         super(TYPE, StampFactory.forVoid());
  76         this.counter = counter;
  77         this.increment = increment;
  78     }
  79 
  80     public SnippetCounter getCounter() {
  81         return counter;
  82     }
  83 
  84     public ValueNode getIncrement() {
  85         return increment;
  86     }
  87 
  88     @NodeIntrinsic
  89     public static native void add(@ConstantNodeParameter SnippetCounter counter, int increment);
  90 
  91     public static void increment(@ConstantNodeParameter SnippetCounter counter) {
  92         add(counter, 1);
  93     }
  94 
  95     @Override
  96     public void lower(LoweringTool tool) {
  97         if (graph().getGuardsStage().areFrameStatesAtDeopts()) {
  98             SnippetCounterSnippets.Templates templates = tool.getReplacements().getSnippetTemplateCache(SnippetCounterSnippets.Templates.class);
  99             templates.lower(this, tool);
 100         }
 101     }
 102 
 103     /**
 104      * When {@link #SnippetCounters} are enabled make sure {@link #SNIPPET_COUNTER_LOCATION} is part
 105      * of the private locations.
 106      *
 107      * @param privateLocations
 108      * @return a copy of privateLocations with any needed locations added
 109      */
 110     public static LocationIdentity[] addSnippetCounters(LocationIdentity[] privateLocations) {
 111         if (SnippetCounters.getValue()) {
 112             for (LocationIdentity location : privateLocations) {
 113                 if (location.equals(SNIPPET_COUNTER_LOCATION)) {
 114                     return privateLocations;
 115                 }
 116             }
 117             LocationIdentity[] result = Arrays.copyOf(privateLocations, privateLocations.length + 1);
 118             result[result.length - 1] = SnippetCounterNode.SNIPPET_COUNTER_LOCATION;
 119             return result;
 120         }
 121         return privateLocations;
 122     }
 123 
 124     /**
 125      * We do not want to use the {@link LocationIdentity} of the {@link SnippetCounter#value} field,
 126      * so that the usage in snippets is always possible. If a method accesses the counter via the
 127      * field and the snippet, the result might not be correct though.
 128      */
 129     public static final LocationIdentity SNIPPET_COUNTER_LOCATION = NamedLocationIdentity.mutable("SnippetCounter");
 130 
 131     static class SnippetCounterSnippets implements Snippets {
 132 
 133         @Fold
 134         static int countOffset() {
 135             try {
 136                 return (int) UNSAFE.objectFieldOffset(SnippetCounter.class.getDeclaredField("value"));
 137             } catch (Exception e) {
 138                 throw new GraalError(e);
 139             }
 140         }
 141 
 142         @Snippet
 143         public static void add(@ConstantParameter SnippetCounter counter, int increment) {
 144             long loadedValue = ObjectAccess.readLong(counter, countOffset(), SNIPPET_COUNTER_LOCATION);
 145             ObjectAccess.writeLong(counter, countOffset(), loadedValue + increment, SNIPPET_COUNTER_LOCATION);
 146         }
 147 
 148         public static class Templates extends AbstractTemplates {
 149 
 150             private final SnippetInfo add = snippet(SnippetCounterSnippets.class, "add", SNIPPET_COUNTER_LOCATION);
 151 
 152             Templates(Providers providers, SnippetReflectionProvider snippetReflection, TargetDescription target) {
 153                 super(providers, snippetReflection, target);
 154             }
 155 
 156             public void lower(SnippetCounterNode counter, LoweringTool tool) {
 157                 StructuredGraph graph = counter.graph();
 158                 Arguments args = new Arguments(add, graph.getGuardsStage(), tool.getLoweringStage());
 159                 args.addConst("counter", counter.getCounter());
 160                 args.add("increment", counter.getIncrement());
 161 
 162                 template(args).instantiate(providers.getMetaAccess(), counter, DEFAULT_REPLACER, args);
 163             }
 164         }
 165     }
 166 
 167     private static final Unsafe UNSAFE = initUnsafe();
 168 
 169     private static Unsafe initUnsafe() {
 170         try {
 171             return Unsafe.getUnsafe();
 172         } catch (SecurityException se) {
 173             try {
 174                 Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
 175                 theUnsafe.setAccessible(true);
 176                 return (Unsafe) theUnsafe.get(Unsafe.class);
 177             } catch (Exception e) {
 178                 throw new RuntimeException("exception while trying to get Unsafe", e);
 179             }
 180         }
 181     }
 182 }