1 /*
  2  * Copyright (c) 1997, 2021, 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 #include "precompiled.hpp"
 26 #include "asm/macroAssembler.hpp"
 27 #include "asm/macroAssembler.inline.hpp"
 28 #include "cds/metaspaceShared.hpp"
 29 #include "compiler/disassembler.hpp"
 30 #include "interpreter/bytecodeHistogram.hpp"
 31 #include "interpreter/bytecodeStream.hpp"
 32 #include "interpreter/interpreter.hpp"
 33 #include "interpreter/interpreterRuntime.hpp"
 34 #include "interpreter/interp_masm.hpp"
 35 #include "interpreter/templateTable.hpp"
 36 #include "memory/allocation.inline.hpp"
 37 #include "memory/resourceArea.hpp"
 38 #include "oops/arrayOop.hpp"
 39 #include "oops/constantPool.hpp"
 40 #include "oops/cpCache.inline.hpp"
 41 #include "oops/methodData.hpp"
 42 #include "oops/method.inline.hpp"
 43 #include "oops/oop.inline.hpp"
 44 #include "prims/forte.hpp"
 45 #include "prims/jvmtiExport.hpp"
 46 #include "prims/methodHandles.hpp"
 47 #include "runtime/handles.inline.hpp"
 48 #include "runtime/sharedRuntime.hpp"
 49 #include "runtime/stubRoutines.hpp"
 50 #include "runtime/timer.hpp"
 51 
 52 # define __ _masm->
 53 
 54 //------------------------------------------------------------------------------------------------------------------------
 55 // Implementation of platform independent aspects of Interpreter
 56 
 57 void AbstractInterpreter::initialize() {
 58   // make sure 'imported' classes are initialized
 59   if (CountBytecodes || TraceBytecodes || StopInterpreterAt) BytecodeCounter::reset();
 60   if (PrintBytecodeHistogram)                                BytecodeHistogram::reset();
 61   if (PrintBytecodePairHistogram)                            BytecodePairHistogram::reset();
 62 }
 63 
 64 void AbstractInterpreter::print() {
 65   tty->cr();
 66   tty->print_cr("----------------------------------------------------------------------");
 67   tty->print_cr("Interpreter");
 68   tty->cr();
 69   tty->print_cr("code size        = %6dK bytes", (int)_code->used_space()/1024);
 70   tty->print_cr("total space      = %6dK bytes", (int)_code->total_space()/1024);
 71   tty->print_cr("wasted space     = %6dK bytes", (int)_code->available_space()/1024);
 72   tty->cr();
 73   tty->print_cr("# of codelets    = %6d"      , _code->number_of_stubs());
 74   if (_code->number_of_stubs() != 0) {
 75     tty->print_cr("avg codelet size = %6d bytes", _code->used_space() / _code->number_of_stubs());
 76     tty->cr();
 77   }
 78   _code->print();
 79   tty->print_cr("----------------------------------------------------------------------");
 80   tty->cr();
 81 }
 82 
 83 
 84 //------------------------------------------------------------------------------------------------------------------------
 85 // Implementation of interpreter
 86 
 87 StubQueue* AbstractInterpreter::_code                                       = NULL;
 88 bool       AbstractInterpreter::_notice_safepoints                          = false;
 89 address    AbstractInterpreter::_rethrow_exception_entry                    = NULL;
 90 
 91 address    AbstractInterpreter::_native_entry_begin                         = NULL;
 92 address    AbstractInterpreter::_native_entry_end                           = NULL;
 93 address    AbstractInterpreter::_slow_signature_handler;
 94 address    AbstractInterpreter::_entry_table            [AbstractInterpreter::number_of_method_entries];
 95 address    AbstractInterpreter::_native_abi_to_tosca    [AbstractInterpreter::number_of_result_handlers];
 96 
 97 //------------------------------------------------------------------------------------------------------------------------
 98 // Generation of complete interpreter
 99 
100 AbstractInterpreterGenerator::AbstractInterpreterGenerator(StubQueue* _code) {
101   _masm                      = NULL;
102 }
103 
104 
105 //------------------------------------------------------------------------------------------------------------------------
106 // Entry points
107 
108 AbstractInterpreter::MethodKind AbstractInterpreter::method_kind(const methodHandle& m) {
109   // Abstract method?
110   if (m->is_abstract()) return abstract;
111 
112   // Method handle primitive?
113   vmIntrinsics::ID iid = m->intrinsic_id();
114   if (iid != vmIntrinsics::_none) {
115     if (m->is_method_handle_intrinsic()) {
116       assert(MethodHandles::is_signature_polymorphic(iid), "must match an intrinsic");
117       MethodKind kind = (MethodKind)(method_handle_invoke_FIRST +
118                                     vmIntrinsics::as_int(iid) -
119                                     static_cast<int>(vmIntrinsics::FIRST_MH_SIG_POLY));
120       assert(kind <= method_handle_invoke_LAST, "parallel enum ranges");
121       return kind;
122     }
123 
124     switch (iid) {
125 #ifndef ZERO
126       // Use optimized stub code for CRC32 native methods.
127       case vmIntrinsics::_updateCRC32:       return java_util_zip_CRC32_update;
128       case vmIntrinsics::_updateBytesCRC32:  return java_util_zip_CRC32_updateBytes;
129       case vmIntrinsics::_updateByteBufferCRC32: return java_util_zip_CRC32_updateByteBuffer;
130       // Use optimized stub code for CRC32C methods.
131       case vmIntrinsics::_updateBytesCRC32C: return java_util_zip_CRC32C_updateBytes;
132       case vmIntrinsics::_updateDirectByteBufferCRC32C: return java_util_zip_CRC32C_updateDirectByteBuffer;
133       case vmIntrinsics::_intBitsToFloat:    return java_lang_Float_intBitsToFloat;
134       case vmIntrinsics::_floatToRawIntBits: return java_lang_Float_floatToRawIntBits;
135       case vmIntrinsics::_longBitsToDouble:  return java_lang_Double_longBitsToDouble;
136       case vmIntrinsics::_doubleToRawLongBits: return java_lang_Double_doubleToRawLongBits;
137 #endif // ZERO
138       case vmIntrinsics::_dsin:              return java_lang_math_sin;
139       case vmIntrinsics::_dcos:              return java_lang_math_cos;
140       case vmIntrinsics::_dtan:              return java_lang_math_tan;
141       case vmIntrinsics::_dabs:              return java_lang_math_abs;
142       case vmIntrinsics::_dlog:              return java_lang_math_log;
143       case vmIntrinsics::_dlog10:            return java_lang_math_log10;
144       case vmIntrinsics::_dpow:              return java_lang_math_pow;
145       case vmIntrinsics::_dexp:              return java_lang_math_exp;
146       case vmIntrinsics::_fmaD:              return java_lang_math_fmaD;
147       case vmIntrinsics::_fmaF:              return java_lang_math_fmaF;
148       case vmIntrinsics::_Reference_get:     return java_lang_ref_reference_get;
149       case vmIntrinsics::_dsqrt:
150         // _dsqrt will be selected for both Math::sqrt and StrictMath::sqrt, but the latter
151         // is native. Keep treating it like a native method in the interpreter
152         assert(m->name() == vmSymbols::sqrt_name() &&
153                (m->klass_name() == vmSymbols::java_lang_Math() ||
154                 m->klass_name() == vmSymbols::java_lang_StrictMath()), "must be");
155         return m->is_native() ? native : java_lang_math_sqrt;
156       case vmIntrinsics::_Object_init:
157         if (RegisterFinalizersAtInit && m->code_size() == 1) {
158           // We need to execute the special return bytecode to check for
159           // finalizer registration so create a normal frame.
160           return zerolocals;
161         }
162         break;
163       default: break;
164     }
165   }
166 
167   // Native method?
168   if (m->is_native()) {
169     assert(!m->is_method_handle_intrinsic(), "overlapping bits here, watch out");
170     return m->is_synchronized() ? native_synchronized : native;
171   }
172 
173   // Synchronized?
174   if (m->is_synchronized()) {
175     return zerolocals_synchronized;
176   }
177 
178   // Empty method?
179   if (m->is_empty_method()) {
180     return empty;
181   }
182 
183   // Getter method?
184   if (m->is_getter()) {
185     return getter;
186   }
187 
188   // Setter method?
189   if (m->is_setter()) {
190     return setter;
191   }
192 
193   // Note: for now: zero locals for all non-empty methods
194   return zerolocals;
195 }
196 
197 void AbstractInterpreter::set_entry_for_kind(AbstractInterpreter::MethodKind kind, address entry) {
198   assert(kind >= method_handle_invoke_FIRST &&
199          kind <= method_handle_invoke_LAST, "late initialization only for MH entry points");
200   assert(_entry_table[kind] == _entry_table[abstract], "previous value must be AME entry");
201   _entry_table[kind] = entry;
202 }
203 
204 // Return true if the interpreter can prove that the given bytecode has
205 // not yet been executed (in Java semantics, not in actual operation).
206 bool AbstractInterpreter::is_not_reached(const methodHandle& method, int bci) {
207   BytecodeStream s(method, bci);
208   Bytecodes::Code code = s.next();
209 
210   if (Bytecodes::is_invoke(code)) {
211     assert(!Bytecodes::must_rewrite(code), "invokes aren't rewritten");
212     ConstantPool* cpool = method()->constants();
213 
214     Bytecode invoke_bc(s.bytecode());
215 
216     switch (code) {
217       case Bytecodes::_invokedynamic: {
218         assert(invoke_bc.has_index_u4(code), "sanity");
219         int method_index = invoke_bc.get_index_u4(code);
220         return cpool->invokedynamic_cp_cache_entry_at(method_index)->is_f1_null();
221       }
222       case Bytecodes::_invokevirtual:   // fall-through
223       case Bytecodes::_invokeinterface: // fall-through
224       case Bytecodes::_invokespecial:   // fall-through
225       case Bytecodes::_invokestatic: {
226         if (cpool->has_preresolution()) {
227           return false; // might have been reached
228         }
229         assert(!invoke_bc.has_index_u4(code), "sanity");
230         int method_index = invoke_bc.get_index_u2_cpcache(code);
231         constantPoolHandle cp(Thread::current(), cpool);
232         Method* resolved_method = ConstantPool::method_at_if_loaded(cp, method_index);
233         return (resolved_method == NULL);
234       }
235       default: ShouldNotReachHere();
236     }
237   } else if (!Bytecodes::must_rewrite(code)) {
238     // might have been reached
239     return false;
240   }
241 
242   // the bytecode might not be rewritten if the method is an accessor, etc.
243   address ientry = method->interpreter_entry();
244   if (ientry != entry_for_kind(AbstractInterpreter::zerolocals) &&
245       ientry != entry_for_kind(AbstractInterpreter::zerolocals_synchronized))
246     return false;  // interpreter does not run this method!
247 
248   // otherwise, we can be sure this bytecode has never been executed
249   return true;
250 }
251 
252 
253 #ifndef PRODUCT
254 void AbstractInterpreter::print_method_kind(MethodKind kind) {
255   switch (kind) {
256     case zerolocals             : tty->print("zerolocals"             ); break;
257     case zerolocals_synchronized: tty->print("zerolocals_synchronized"); break;
258     case native                 : tty->print("native"                 ); break;
259     case native_synchronized    : tty->print("native_synchronized"    ); break;
260     case empty                  : tty->print("empty"                  ); break;
261     case getter                 : tty->print("getter"                 ); break;
262     case setter                 : tty->print("setter"                 ); break;
263     case abstract               : tty->print("abstract"               ); break;
264     case java_lang_math_sin     : tty->print("java_lang_math_sin"     ); break;
265     case java_lang_math_cos     : tty->print("java_lang_math_cos"     ); break;
266     case java_lang_math_tan     : tty->print("java_lang_math_tan"     ); break;
267     case java_lang_math_abs     : tty->print("java_lang_math_abs"     ); break;
268     case java_lang_math_sqrt    : tty->print("java_lang_math_sqrt"    ); break;
269     case java_lang_math_log     : tty->print("java_lang_math_log"     ); break;
270     case java_lang_math_log10   : tty->print("java_lang_math_log10"   ); break;
271     case java_lang_math_fmaD    : tty->print("java_lang_math_fmaD"    ); break;
272     case java_lang_math_fmaF    : tty->print("java_lang_math_fmaF"    ); break;
273     case java_util_zip_CRC32_update           : tty->print("java_util_zip_CRC32_update"); break;
274     case java_util_zip_CRC32_updateBytes      : tty->print("java_util_zip_CRC32_updateBytes"); break;
275     case java_util_zip_CRC32_updateByteBuffer : tty->print("java_util_zip_CRC32_updateByteBuffer"); break;
276     case java_util_zip_CRC32C_updateBytes     : tty->print("java_util_zip_CRC32C_updateBytes"); break;
277     case java_util_zip_CRC32C_updateDirectByteBuffer: tty->print("java_util_zip_CRC32C_updateDirectByteByffer"); break;
278     default:
279       if (kind >= method_handle_invoke_FIRST &&
280           kind <= method_handle_invoke_LAST) {
281         const char* kind_name = vmIntrinsics::name_at(method_handle_intrinsic(kind));
282         if (kind_name[0] == '_')  kind_name = &kind_name[1];  // '_invokeExact' => 'invokeExact'
283         tty->print("method_handle_%s", kind_name);
284         break;
285       }
286       ShouldNotReachHere();
287       break;
288   }
289 }
290 #endif // PRODUCT
291 
292 
293 //------------------------------------------------------------------------------------------------------------------------
294 // Deoptimization support
295 
296 /**
297  * If a deoptimization happens, this function returns the point of next bytecode to continue execution.
298  */
299 address AbstractInterpreter::deopt_continue_after_entry(Method* method, address bcp, int callee_parameters, bool is_top_frame) {
300   assert(method->contains(bcp), "just checkin'");
301 
302   // Get the original and rewritten bytecode.
303   Bytecodes::Code code = Bytecodes::java_code_at(method, bcp);
304   assert(!Interpreter::bytecode_should_reexecute(code), "should not reexecute");
305 
306   const int bci = method->bci_from(bcp);
307 
308   // compute continuation length
309   const int length = Bytecodes::length_at(method, bcp);
310 
311   // compute result type
312   BasicType type = T_ILLEGAL;
313 
314   switch (code) {
315     case Bytecodes::_invokevirtual  :
316     case Bytecodes::_invokespecial  :
317     case Bytecodes::_invokestatic   :
318     case Bytecodes::_invokeinterface: {
319       Thread *thread = Thread::current();
320       ResourceMark rm(thread);
321       methodHandle mh(thread, method);
322       type = Bytecode_invoke(mh, bci).result_type();
323       // since the cache entry might not be initialized:
324       // (NOT needed for the old calling convension)
325       if (!is_top_frame) {
326         int index = Bytes::get_native_u2(bcp+1);
327         method->constants()->cache()->entry_at(index)->set_parameter_size(callee_parameters);
328       }
329       break;
330     }
331 
332    case Bytecodes::_invokedynamic: {
333       Thread *thread = Thread::current();
334       ResourceMark rm(thread);
335       methodHandle mh(thread, method);
336       type = Bytecode_invoke(mh, bci).result_type();
337       // since the cache entry might not be initialized:
338       // (NOT needed for the old calling convension)
339       if (!is_top_frame) {
340         int index = Bytes::get_native_u4(bcp+1);
341         method->constants()->invokedynamic_cp_cache_entry_at(index)->set_parameter_size(callee_parameters);
342       }
343       break;
344     }
345 
346     case Bytecodes::_ldc   :
347     case Bytecodes::_ldc_w : // fall through
348     case Bytecodes::_ldc2_w:
349       {
350         Thread *thread = Thread::current();
351         ResourceMark rm(thread);
352         methodHandle mh(thread, method);
353         type = Bytecode_loadconstant(mh, bci).result_type();
354         break;
355       }
356 
357     default:
358       type = Bytecodes::result_type(code);
359       break;
360   }
361 
362   // return entry point for computed continuation state & bytecode length
363   return
364     is_top_frame
365     ? Interpreter::deopt_entry (as_TosState(type), length)
366     : Interpreter::return_entry(as_TosState(type), length, code);
367 }
368 
369 // If deoptimization happens, this function returns the point where the interpreter reexecutes
370 // the bytecode.
371 // Note: Bytecodes::_athrow is a special case in that it does not return
372 //       Interpreter::deopt_entry(vtos, 0) like others
373 address AbstractInterpreter::deopt_reexecute_entry(Method* method, address bcp) {
374   assert(method->contains(bcp), "just checkin'");
375   Bytecodes::Code code   = Bytecodes::java_code_at(method, bcp);
376 #if defined(COMPILER1) || INCLUDE_JVMCI
377   if(code == Bytecodes::_athrow ) {
378     return Interpreter::rethrow_exception_entry();
379   }
380 #endif /* COMPILER1 || INCLUDE_JVMCI */
381   return Interpreter::deopt_entry(vtos, 0);
382 }
383 
384 // If deoptimization happens, the interpreter should reexecute these bytecodes.
385 // This function mainly helps the compilers to set up the reexecute bit.
386 bool AbstractInterpreter::bytecode_should_reexecute(Bytecodes::Code code) {
387   switch (code) {
388     case Bytecodes::_lookupswitch:
389     case Bytecodes::_tableswitch:
390     case Bytecodes::_fast_binaryswitch:
391     case Bytecodes::_fast_linearswitch:
392     // recompute condtional expression folded into _if<cond>
393     case Bytecodes::_lcmp      :
394     case Bytecodes::_fcmpl     :
395     case Bytecodes::_fcmpg     :
396     case Bytecodes::_dcmpl     :
397     case Bytecodes::_dcmpg     :
398     case Bytecodes::_ifnull    :
399     case Bytecodes::_ifnonnull :
400     case Bytecodes::_goto      :
401     case Bytecodes::_goto_w    :
402     case Bytecodes::_ifeq      :
403     case Bytecodes::_ifne      :
404     case Bytecodes::_iflt      :
405     case Bytecodes::_ifge      :
406     case Bytecodes::_ifgt      :
407     case Bytecodes::_ifle      :
408     case Bytecodes::_if_icmpeq :
409     case Bytecodes::_if_icmpne :
410     case Bytecodes::_if_icmplt :
411     case Bytecodes::_if_icmpge :
412     case Bytecodes::_if_icmpgt :
413     case Bytecodes::_if_icmple :
414     case Bytecodes::_if_acmpeq :
415     case Bytecodes::_if_acmpne :
416     // special cases
417     case Bytecodes::_getfield  :
418     case Bytecodes::_putfield  :
419     case Bytecodes::_getstatic :
420     case Bytecodes::_putstatic :
421     case Bytecodes::_aastore   :
422 #ifdef COMPILER1
423     //special case of reexecution
424     case Bytecodes::_athrow    :
425 #endif
426       return true;
427 
428     default:
429       return false;
430   }
431 }
432 
433 void AbstractInterpreter::initialize_method_handle_entries() {
434   // method handle entry kinds are generated later in MethodHandlesAdapterGenerator::generate:
435   for (int i = method_handle_invoke_FIRST; i <= method_handle_invoke_LAST; i++) {
436     MethodKind kind = (MethodKind) i;
437     _entry_table[kind] = _entry_table[Interpreter::abstract];
438   }
439 }