1 /*
   2  * Copyright (c) 2011, 2018, 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 
  24 
  25 package org.graalvm.compiler.core.test;
  26 
  27 import java.lang.invoke.MethodHandle;
  28 import java.lang.invoke.MethodHandles;
  29 import java.lang.reflect.Field;
  30 
  31 import org.junit.Test;
  32 
  33 import org.graalvm.compiler.nodes.DeoptimizeNode;
  34 import org.graalvm.compiler.nodes.StructuredGraph;
  35 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
  36 import org.graalvm.compiler.test.AddExports;
  37 
  38 // Export needed to open String.value field to reflection by this test
  39 @AddExports("java.base/java.lang")
  40 public final class MethodHandleEagerResolution extends GraalCompilerTest {
  41     private static final MethodHandle FIELD_HANDLE;
  42 
  43     static {
  44         Field field;
  45         try {
  46             field = String.class.getDeclaredField("value");
  47         } catch (NoSuchFieldException ex) {
  48             throw new RuntimeException(ex.getMessage(), ex);
  49         }
  50         field.setAccessible(true);
  51 
  52         try {
  53             FIELD_HANDLE = MethodHandles.lookup().unreflectGetter(field);
  54         } catch (IllegalAccessException e) {
  55             throw new RuntimeException("unable to initialize field handle", e);
  56         }
  57     }
  58 
  59     public static char[] getBackingCharArray(String str) {
  60         try {
  61             return (char[]) FIELD_HANDLE.invokeExact(str);
  62         } catch (Throwable e) {
  63             throw new IllegalStateException();
  64         }
  65     }
  66 
  67     @Test
  68     public void testFieldInvokeExact() {
  69         StructuredGraph graph = parseEager("getBackingCharArray", AllowAssumptions.NO);
  70         assertTrue(graph.getNodes().filter(DeoptimizeNode.class).isEmpty());
  71     }
  72 
  73 }