1/*
2 * Copyright (c) 2011, 2017, 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#include "precompiled.hpp"
25#include "memory/oopFactory.hpp"
26#include "memory/resourceArea.hpp"
27#include "oops/oop.inline.hpp"
28#include "prims/jvm.h"
29#include "runtime/javaCalls.hpp"
30#include "runtime/handles.hpp"
31#include "jvmci/jvmciJavaClasses.hpp"
32#include "jvmci/jvmciCompiler.hpp"
33#include "jvmci/jvmciEnv.hpp"
34#include "jvmci/jvmciRuntime.hpp"
35#include "runtime/compilationPolicy.hpp"
36#include "runtime/globals_extension.hpp"
37
38JVMCICompiler* JVMCICompiler::_instance = NULL;
39elapsedTimer JVMCICompiler::_codeInstallTimer;
40
41JVMCICompiler::JVMCICompiler() : AbstractCompiler(compiler_jvmci) {
42  _bootstrapping = false;
43  _bootstrap_compilation_request_handled = false;
44  _methods_compiled = 0;
45  assert(_instance == NULL, "only one instance allowed");
46  _instance = this;
47}
48
49// Initialization
50void JVMCICompiler::initialize() {
51  if (!UseCompiler || !EnableJVMCI || !UseJVMCICompiler || !should_perform_init()) {
52    return;
53  }
54
55  set_state(initialized);
56
57  // JVMCI is considered as application code so we need to
58  // stop the VM deferring compilation now.
59  CompilationPolicy::completed_vm_startup();
60}
61
62void JVMCICompiler::bootstrap(TRAPS) {
63  if (Arguments::mode() == Arguments::_int) {
64    // Nothing to do in -Xint mode
65    return;
66  }
67#ifndef PRODUCT
68  // We turn off CompileTheWorld so that compilation requests are not
69  // ignored during bootstrap or that JVMCI can be compiled by C1/C2.
70  FlagSetting ctwOff(CompileTheWorld, false);
71#endif
72
73  _bootstrapping = true;
74  ResourceMark rm;
75  HandleMark hm;
76  if (PrintBootstrap) {
77    tty->print("Bootstrapping JVMCI");
78  }
79  jlong start = os::javaTimeMillis();
80
81  Array<Method*>* objectMethods = SystemDictionary::Object_klass()->methods();
82  // Initialize compile queue with a selected set of methods.
83  int len = objectMethods->length();
84  for (int i = 0; i < len; i++) {
85    methodHandle mh = objectMethods->at(i);
86    if (!mh->is_native() && !mh->is_static() && !mh->is_initializer()) {
87      ResourceMark rm;
88      int hot_count = 10; // TODO: what's the appropriate value?
89      CompileBroker::compile_method(mh, InvocationEntryBci, CompLevel_full_optimization, mh, hot_count, CompileTask::Reason_Bootstrap, THREAD);
90    }
91  }
92
93  int qsize;
94  bool first_round = true;
95  int z = 0;
96  do {
97    // Loop until there is something in the queue.
98    do {
99      os::sleep(THREAD, 100, true);
100      qsize = CompileBroker::queue_size(CompLevel_full_optimization);
101    } while (!_bootstrap_compilation_request_handled && first_round && qsize == 0);
102    first_round = false;
103    if (PrintBootstrap) {
104      while (z < (_methods_compiled / 100)) {
105        ++z;
106        tty->print_raw(".");
107      }
108    }
109  } while (qsize != 0);
110
111  if (PrintBootstrap) {
112    tty->print_cr(" in " JLONG_FORMAT " ms (compiled %d methods)", os::javaTimeMillis() - start, _methods_compiled);
113  }
114  _bootstrapping = false;
115  JVMCIRuntime::bootstrap_finished(CHECK);
116}
117
118#define CHECK_EXIT THREAD); \
119if (HAS_PENDING_EXCEPTION) { \
120  char buf[256]; \
121  jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
122  JVMCICompiler::exit_on_pending_exception(PENDING_EXCEPTION, buf); \
123  return; \
124} \
125(void)(0
126
127void JVMCICompiler::compile_method(const methodHandle& method, int entry_bci, JVMCIEnv* env) {
128  JVMCI_EXCEPTION_CONTEXT
129
130  bool is_osr = entry_bci != InvocationEntryBci;
131  if (_bootstrapping && is_osr) {
132      // no OSR compilations during bootstrap - the compiler is just too slow at this point,
133      // and we know that there are no endless loops
134      return;
135  }
136
137  JVMCIRuntime::initialize_well_known_classes(CHECK_EXIT);
138
139  HandleMark hm;
140  Handle receiver = JVMCIRuntime::get_HotSpotJVMCIRuntime(CHECK_EXIT);
141
142  JavaValue method_result(T_OBJECT);
143  JavaCallArguments args;
144  args.push_long((jlong) (address) method());
145  JavaCalls::call_static(&method_result, SystemDictionary::HotSpotResolvedJavaMethodImpl_klass(),
146                         vmSymbols::fromMetaspace_name(), vmSymbols::method_fromMetaspace_signature(), &args, THREAD);
147
148  JavaValue result(T_OBJECT);
149  if (!HAS_PENDING_EXCEPTION) {
150    JavaCallArguments args;
151    args.push_oop(receiver);
152    args.push_oop(Handle(THREAD, (oop)method_result.get_jobject()));
153    args.push_int(entry_bci);
154    args.push_long((jlong) (address) env);
155    args.push_int(env->task()->compile_id());
156    JavaCalls::call_special(&result, receiver->klass(),
157                            vmSymbols::compileMethod_name(), vmSymbols::compileMethod_signature(), &args, THREAD);
158  }
159
160  // An uncaught exception was thrown during compilation.  Generally these
161  // should be handled by the Java code in some useful way but if they leak
162  // through to here report them instead of dying or silently ignoring them.
163  if (HAS_PENDING_EXCEPTION) {
164    Handle exception(THREAD, PENDING_EXCEPTION);
165    CLEAR_PENDING_EXCEPTION;
166
167    java_lang_Throwable::java_printStackTrace(exception, THREAD);
168    if (HAS_PENDING_EXCEPTION) {
169      CLEAR_PENDING_EXCEPTION;
170    }
171
172    env->set_failure("exception throw", false);
173  } else {
174    oop result_object = (oop) result.get_jobject();
175    if (result_object != NULL) {
176      oop failure_message = HotSpotCompilationRequestResult::failureMessage(result_object);
177      if (failure_message != NULL) {
178        const char* failure_reason = java_lang_String::as_utf8_string(failure_message);
179        env->set_failure(failure_reason, HotSpotCompilationRequestResult::retry(result_object) != 0);
180      } else {
181        if (env->task()->code() == NULL) {
182          env->set_failure("no nmethod produced", true);
183        } else {
184          env->task()->set_num_inlined_bytecodes(HotSpotCompilationRequestResult::inlinedBytecodes(result_object));
185          Atomic::inc(&_methods_compiled);
186        }
187      }
188    } else {
189      assert(false, "JVMCICompiler.compileMethod should always return non-null");
190    }
191  }
192  if (_bootstrapping) {
193    _bootstrap_compilation_request_handled = true;
194  }
195}
196
197CompLevel JVMCIRuntime::adjust_comp_level(const methodHandle& method, bool is_osr, CompLevel level, JavaThread* thread) {
198  if (!thread->adjusting_comp_level()) {
199    thread->set_adjusting_comp_level(true);
200    level = adjust_comp_level_inner(method, is_osr, level, thread);
201    thread->set_adjusting_comp_level(false);
202  }
203  return level;
204}
205
206void JVMCICompiler::exit_on_pending_exception(oop exception, const char* message) {
207  JavaThread* THREAD = JavaThread::current();
208  CLEAR_PENDING_EXCEPTION;
209
210  static volatile int report_error = 0;
211  if (!report_error && Atomic::cmpxchg(1, &report_error, 0) == 0) {
212    // Only report an error once
213    tty->print_raw_cr(message);
214    Handle ex(THREAD, exception);
215    java_lang_Throwable::java_printStackTrace(ex, THREAD);
216  } else {
217    // Allow error reporting thread to print the stack trace.
218    os::sleep(THREAD, 200, false);
219  }
220
221  before_exit(THREAD);
222  vm_exit(-1);
223}
224
225// Compilation entry point for methods
226void JVMCICompiler::compile_method(ciEnv* env, ciMethod* target, int entry_bci, DirectiveSet* directive) {
227  ShouldNotReachHere();
228}
229
230bool JVMCICompiler::is_trivial(Method* method) {
231  if (_bootstrapping) {
232    return false;
233  }
234  return JVMCIRuntime::treat_as_trivial(method);
235}
236
237// Print compilation timers and statistics
238void JVMCICompiler::print_timers() {
239  print_compilation_timers();
240}
241
242// Print compilation timers and statistics
243void JVMCICompiler::print_compilation_timers() {
244  TRACE_jvmci_1("JVMCICompiler::print_timers");
245  tty->print_cr("       JVMCI code install time:        %6.3f s",    _codeInstallTimer.seconds());
246}
247