Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/interpreter/rewriter.cpp
32285 views
/*1* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "interpreter/bytecodes.hpp"26#include "interpreter/interpreter.hpp"27#include "interpreter/rewriter.hpp"28#include "memory/gcLocker.hpp"29#include "memory/resourceArea.hpp"30#include "oops/generateOopMap.hpp"31#include "prims/methodHandles.hpp"3233// Computes a CPC map (new_index -> original_index) for constant pool entries34// that are referred to by the interpreter at runtime via the constant pool cache.35// Also computes a CP map (original_index -> new_index).36// Marks entries in CP which require additional processing.37void Rewriter::compute_index_maps() {38const int length = _pool->length();39init_maps(length);40bool saw_mh_symbol = false;41for (int i = 0; i < length; i++) {42int tag = _pool->tag_at(i).value();43switch (tag) {44case JVM_CONSTANT_InterfaceMethodref:45case JVM_CONSTANT_Fieldref : // fall through46case JVM_CONSTANT_Methodref : // fall through47add_cp_cache_entry(i);48break;49case JVM_CONSTANT_String:50case JVM_CONSTANT_MethodHandle : // fall through51case JVM_CONSTANT_MethodType : // fall through52add_resolved_references_entry(i);53break;54case JVM_CONSTANT_Utf8:55if (_pool->symbol_at(i) == vmSymbols::java_lang_invoke_MethodHandle())56saw_mh_symbol = true;57break;58}59}6061// Record limits of resolved reference map for constant pool cache indices62record_map_limits();6364guarantee((int)_cp_cache_map.length()-1 <= (int)((u2)-1),65"all cp cache indexes fit in a u2");6667if (saw_mh_symbol)68_method_handle_invokers.initialize(length, (int)0);69}7071// Unrewrite the bytecodes if an error occurs.72void Rewriter::restore_bytecodes() {73int len = _methods->length();74bool invokespecial_error = false;7576for (int i = len-1; i >= 0; i--) {77Method* method = _methods->at(i);78scan_method(method, true, &invokespecial_error);79assert(!invokespecial_error, "reversing should not get an invokespecial error");80}81}8283// Creates a constant pool cache given a CPC map84void Rewriter::make_constant_pool_cache(TRAPS) {85ClassLoaderData* loader_data = _pool->pool_holder()->class_loader_data();86ConstantPoolCache* cache =87ConstantPoolCache::allocate(loader_data, _cp_cache_map,88_invokedynamic_cp_cache_map,89_invokedynamic_references_map, CHECK);9091// initialize object cache in constant pool92_pool->initialize_resolved_references(loader_data, _resolved_references_map,93_resolved_reference_limit,94CHECK);95_pool->set_cache(cache);96cache->set_constant_pool(_pool());97}9899100101// The new finalization semantics says that registration of102// finalizable objects must be performed on successful return from the103// Object.<init> constructor. We could implement this trivially if104// <init> were never rewritten but since JVMTI allows this to occur, a105// more complicated solution is required. A special return bytecode106// is used only by Object.<init> to signal the finalization107// registration point. Additionally local 0 must be preserved so it's108// available to pass to the registration function. For simplicty we109// require that local 0 is never overwritten so it's available as an110// argument for registration.111112void Rewriter::rewrite_Object_init(methodHandle method, TRAPS) {113RawBytecodeStream bcs(method);114while (!bcs.is_last_bytecode()) {115Bytecodes::Code opcode = bcs.raw_next();116switch (opcode) {117case Bytecodes::_return: *bcs.bcp() = Bytecodes::_return_register_finalizer; break;118119case Bytecodes::_istore:120case Bytecodes::_lstore:121case Bytecodes::_fstore:122case Bytecodes::_dstore:123case Bytecodes::_astore:124if (bcs.get_index() != 0) continue;125126// fall through127case Bytecodes::_istore_0:128case Bytecodes::_lstore_0:129case Bytecodes::_fstore_0:130case Bytecodes::_dstore_0:131case Bytecodes::_astore_0:132THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),133"can't overwrite local 0 in Object.<init>");134break;135}136}137}138139140// Rewrite a classfile-order CP index into a native-order CPC index.141void Rewriter::rewrite_member_reference(address bcp, int offset, bool reverse) {142address p = bcp + offset;143if (!reverse) {144int cp_index = Bytes::get_Java_u2(p);145int cache_index = cp_entry_to_cp_cache(cp_index);146Bytes::put_native_u2(p, cache_index);147if (!_method_handle_invokers.is_empty())148maybe_rewrite_invokehandle(p - 1, cp_index, cache_index, reverse);149} else {150int cache_index = Bytes::get_native_u2(p);151int pool_index = cp_cache_entry_pool_index(cache_index);152Bytes::put_Java_u2(p, pool_index);153if (!_method_handle_invokers.is_empty())154maybe_rewrite_invokehandle(p - 1, pool_index, cache_index, reverse);155}156}157158// If the constant pool entry for invokespecial is InterfaceMethodref,159// we need to add a separate cpCache entry for its resolution, because it is160// different than the resolution for invokeinterface with InterfaceMethodref.161// These cannot share cpCache entries. It's unclear if all invokespecial to162// InterfaceMethodrefs would resolve to the same thing so a new cpCache entry163// is created for each one. This was added with lambda.164void Rewriter::rewrite_invokespecial(address bcp, int offset, bool reverse, bool* invokespecial_error) {165address p = bcp + offset;166if (!reverse) {167int cp_index = Bytes::get_Java_u2(p);168if (_pool->tag_at(cp_index).is_interface_method()) {169int cache_index = add_invokespecial_cp_cache_entry(cp_index);170if (cache_index != (int)(jushort) cache_index) {171*invokespecial_error = true;172}173Bytes::put_native_u2(p, cache_index);174} else {175rewrite_member_reference(bcp, offset, reverse);176}177} else {178rewrite_member_reference(bcp, offset, reverse);179}180}181182183// Adjust the invocation bytecode for a signature-polymorphic method (MethodHandle.invoke, etc.)184void Rewriter::maybe_rewrite_invokehandle(address opc, int cp_index, int cache_index, bool reverse) {185if (!reverse) {186if ((*opc) == (u1)Bytecodes::_invokevirtual ||187// allow invokespecial as an alias, although it would be very odd:188(*opc) == (u1)Bytecodes::_invokespecial) {189assert(_pool->tag_at(cp_index).is_method(), "wrong index");190// Determine whether this is a signature-polymorphic method.191if (cp_index >= _method_handle_invokers.length()) return;192int status = _method_handle_invokers[cp_index];193assert(status >= -1 && status <= 1, "oob tri-state");194if (status == 0) {195if (_pool->klass_ref_at_noresolve(cp_index) == vmSymbols::java_lang_invoke_MethodHandle() &&196MethodHandles::is_signature_polymorphic_name(SystemDictionary::MethodHandle_klass(),197_pool->name_ref_at(cp_index))) {198// we may need a resolved_refs entry for the appendix199add_invokedynamic_resolved_references_entries(cp_index, cache_index);200status = +1;201} else {202status = -1;203}204_method_handle_invokers[cp_index] = status;205}206// We use a special internal bytecode for such methods (if non-static).207// The basic reason for this is that such methods need an extra "appendix" argument208// to transmit the call site's intended call type.209if (status > 0) {210(*opc) = (u1)Bytecodes::_invokehandle;211}212}213} else {214// Do not need to look at cp_index.215if ((*opc) == (u1)Bytecodes::_invokehandle) {216(*opc) = (u1)Bytecodes::_invokevirtual;217// Ignore corner case of original _invokespecial instruction.218// This is safe because (a) the signature polymorphic method was final, and219// (b) the implementation of MethodHandle will not call invokespecial on it.220}221}222}223224225void Rewriter::rewrite_invokedynamic(address bcp, int offset, bool reverse) {226address p = bcp + offset;227assert(p[-1] == Bytecodes::_invokedynamic, "not invokedynamic bytecode");228if (!reverse) {229int cp_index = Bytes::get_Java_u2(p);230int cache_index = add_invokedynamic_cp_cache_entry(cp_index);231int resolved_index = add_invokedynamic_resolved_references_entries(cp_index, cache_index);232// Replace the trailing four bytes with a CPC index for the dynamic233// call site. Unlike other CPC entries, there is one per bytecode,234// not just one per distinct CP entry. In other words, the235// CPC-to-CP relation is many-to-one for invokedynamic entries.236// This means we must use a larger index size than u2 to address237// all these entries. That is the main reason invokedynamic238// must have a five-byte instruction format. (Of course, other JVM239// implementations can use the bytes for other purposes.)240// Note: We use native_u4 format exclusively for 4-byte indexes.241Bytes::put_native_u4(p, ConstantPool::encode_invokedynamic_index(cache_index));242// add the bcp in case we need to patch this bytecode if we also find a243// invokespecial/InterfaceMethodref in the bytecode stream244_patch_invokedynamic_bcps->push(p);245_patch_invokedynamic_refs->push(resolved_index);246} else {247int cache_index = ConstantPool::decode_invokedynamic_index(248Bytes::get_native_u4(p));249// We will reverse the bytecode rewriting _after_ adjusting them.250// Adjust the cache index by offset to the invokedynamic entries in the251// cpCache plus the delta if the invokedynamic bytecodes were adjusted.252int adjustment = cp_cache_delta() + _first_iteration_cp_cache_limit;253int cp_index = invokedynamic_cp_cache_entry_pool_index(cache_index - adjustment);254assert(_pool->tag_at(cp_index).is_invoke_dynamic(), "wrong index");255// zero out 4 bytes256Bytes::put_Java_u4(p, 0);257Bytes::put_Java_u2(p, cp_index);258}259}260261void Rewriter::patch_invokedynamic_bytecodes() {262// If the end of the cp_cache is the same as after initializing with the263// cpool, nothing needs to be done. Invokedynamic bytecodes are at the264// correct offsets. ie. no invokespecials added265int delta = cp_cache_delta();266if (delta > 0) {267int length = _patch_invokedynamic_bcps->length();268assert(length == _patch_invokedynamic_refs->length(),269"lengths should match");270for (int i = 0; i < length; i++) {271address p = _patch_invokedynamic_bcps->at(i);272int cache_index = ConstantPool::decode_invokedynamic_index(273Bytes::get_native_u4(p));274Bytes::put_native_u4(p, ConstantPool::encode_invokedynamic_index(cache_index + delta));275276// invokedynamic resolved references map also points to cp cache and must277// add delta to each.278int resolved_index = _patch_invokedynamic_refs->at(i);279for (int entry = 0; entry < ConstantPoolCacheEntry::_indy_resolved_references_entries; entry++) {280assert(_invokedynamic_references_map[resolved_index+entry] == cache_index,281"should be the same index");282_invokedynamic_references_map.at_put(resolved_index+entry,283cache_index + delta);284}285}286}287}288289290// Rewrite some ldc bytecodes to _fast_aldc291void Rewriter::maybe_rewrite_ldc(address bcp, int offset, bool is_wide,292bool reverse) {293if (!reverse) {294assert((*bcp) == (is_wide ? Bytecodes::_ldc_w : Bytecodes::_ldc), "not ldc bytecode");295address p = bcp + offset;296int cp_index = is_wide ? Bytes::get_Java_u2(p) : (u1)(*p);297constantTag tag = _pool->tag_at(cp_index).value();298if (tag.is_method_handle() || tag.is_method_type() || tag.is_string()) {299int ref_index = cp_entry_to_resolved_references(cp_index);300if (is_wide) {301(*bcp) = Bytecodes::_fast_aldc_w;302assert(ref_index == (u2)ref_index, "index overflow");303Bytes::put_native_u2(p, ref_index);304} else {305(*bcp) = Bytecodes::_fast_aldc;306assert(ref_index == (u1)ref_index, "index overflow");307(*p) = (u1)ref_index;308}309}310} else {311Bytecodes::Code rewritten_bc =312(is_wide ? Bytecodes::_fast_aldc_w : Bytecodes::_fast_aldc);313if ((*bcp) == rewritten_bc) {314address p = bcp + offset;315int ref_index = is_wide ? Bytes::get_native_u2(p) : (u1)(*p);316int pool_index = resolved_references_entry_to_pool_index(ref_index);317if (is_wide) {318(*bcp) = Bytecodes::_ldc_w;319assert(pool_index == (u2)pool_index, "index overflow");320Bytes::put_Java_u2(p, pool_index);321} else {322(*bcp) = Bytecodes::_ldc;323assert(pool_index == (u1)pool_index, "index overflow");324(*p) = (u1)pool_index;325}326}327}328}329330331// Rewrites a method given the index_map information332void Rewriter::scan_method(Method* method, bool reverse, bool* invokespecial_error) {333334int nof_jsrs = 0;335bool has_monitor_bytecodes = false;336337{338// We cannot tolerate a GC in this block, because we've339// cached the bytecodes in 'code_base'. If the Method*340// moves, the bytecodes will also move.341No_Safepoint_Verifier nsv;342Bytecodes::Code c;343344// Bytecodes and their length345const address code_base = method->code_base();346const int code_length = method->code_size();347348int bc_length;349for (int bci = 0; bci < code_length; bci += bc_length) {350address bcp = code_base + bci;351int prefix_length = 0;352c = (Bytecodes::Code)(*bcp);353354// Since we have the code, see if we can get the length355// directly. Some more complicated bytecodes will report356// a length of zero, meaning we need to make another method357// call to calculate the length.358bc_length = Bytecodes::length_for(c);359if (bc_length == 0) {360bc_length = Bytecodes::length_at(method, bcp);361362// length_at will put us at the bytecode after the one modified363// by 'wide'. We don't currently examine any of the bytecodes364// modified by wide, but in case we do in the future...365if (c == Bytecodes::_wide) {366prefix_length = 1;367c = (Bytecodes::Code)bcp[1];368}369}370371assert(bc_length != 0, "impossible bytecode length");372373switch (c) {374case Bytecodes::_lookupswitch : {375#ifndef CC_INTERP376Bytecode_lookupswitch bc(method, bcp);377(*bcp) = (378bc.number_of_pairs() < BinarySwitchThreshold379? Bytecodes::_fast_linearswitch380: Bytecodes::_fast_binaryswitch381);382#endif383break;384}385case Bytecodes::_fast_linearswitch:386case Bytecodes::_fast_binaryswitch: {387#ifndef CC_INTERP388(*bcp) = Bytecodes::_lookupswitch;389#endif390break;391}392393case Bytecodes::_invokespecial : {394rewrite_invokespecial(bcp, prefix_length+1, reverse, invokespecial_error);395break;396}397398case Bytecodes::_putstatic :399case Bytecodes::_putfield : {400if (!reverse) {401// Check if any final field of the class given as parameter is modified402// outside of initializer methods of the class. Fields that are modified403// are marked with a flag. For marked fields, the compilers do not perform404// constant folding (as the field can be changed after initialization).405//406// The check is performed after verification and only if verification has407// succeeded. Therefore, the class is guaranteed to be well-formed.408InstanceKlass* klass = method->method_holder();409u2 bc_index = Bytes::get_Java_u2(bcp + prefix_length + 1);410constantPoolHandle cp(method->constants());411Symbol* ref_class_name = cp->klass_name_at(cp->klass_ref_index_at(bc_index));412413if (klass->name() == ref_class_name) {414Symbol* field_name = cp->name_ref_at(bc_index);415Symbol* field_sig = cp->signature_ref_at(bc_index);416417fieldDescriptor fd;418if (klass->find_field(field_name, field_sig, &fd) != NULL) {419if (fd.access_flags().is_final()) {420if (fd.access_flags().is_static()) {421if (!method->is_static_initializer()) {422fd.set_has_initialized_final_update(true);423}424} else {425if (!method->is_object_initializer()) {426fd.set_has_initialized_final_update(true);427}428}429}430}431}432}433}434// fall through435case Bytecodes::_getstatic : // fall through436case Bytecodes::_getfield : // fall through437case Bytecodes::_invokevirtual : // fall through438case Bytecodes::_invokestatic :439case Bytecodes::_invokeinterface:440case Bytecodes::_invokehandle : // if reverse=true441rewrite_member_reference(bcp, prefix_length+1, reverse);442break;443case Bytecodes::_invokedynamic:444rewrite_invokedynamic(bcp, prefix_length+1, reverse);445break;446case Bytecodes::_ldc:447case Bytecodes::_fast_aldc: // if reverse=true448maybe_rewrite_ldc(bcp, prefix_length+1, false, reverse);449break;450case Bytecodes::_ldc_w:451case Bytecodes::_fast_aldc_w: // if reverse=true452maybe_rewrite_ldc(bcp, prefix_length+1, true, reverse);453break;454case Bytecodes::_jsr : // fall through455case Bytecodes::_jsr_w : nof_jsrs++; break;456case Bytecodes::_monitorenter : // fall through457case Bytecodes::_monitorexit : has_monitor_bytecodes = true; break;458}459}460}461462// Update access flags463if (has_monitor_bytecodes) {464method->set_has_monitor_bytecodes();465}466467// The present of a jsr bytecode implies that the method might potentially468// have to be rewritten, so we run the oopMapGenerator on the method469if (nof_jsrs > 0) {470method->set_has_jsrs();471// Second pass will revisit this method.472assert(method->has_jsrs(), "didn't we just set this?");473}474}475476// After constant pool is created, revisit methods containing jsrs.477methodHandle Rewriter::rewrite_jsrs(methodHandle method, TRAPS) {478ResourceMark rm(THREAD);479ResolveOopMapConflicts romc(method);480methodHandle original_method = method;481method = romc.do_potential_rewrite(CHECK_(methodHandle()));482// Update monitor matching info.483if (romc.monitor_safe()) {484method->set_guaranteed_monitor_matching();485}486487return method;488}489490void Rewriter::rewrite_bytecodes(TRAPS) {491assert(_pool->cache() == NULL, "constant pool cache must not be set yet");492493// determine index maps for Method* rewriting494compute_index_maps();495496if (RegisterFinalizersAtInit && _klass->name() == vmSymbols::java_lang_Object()) {497bool did_rewrite = false;498int i = _methods->length();499while (i-- > 0) {500Method* method = _methods->at(i);501if (method->intrinsic_id() == vmIntrinsics::_Object_init) {502// rewrite the return bytecodes of Object.<init> to register the503// object for finalization if needed.504methodHandle m(THREAD, method);505rewrite_Object_init(m, CHECK);506did_rewrite = true;507break;508}509}510assert(did_rewrite, "must find Object::<init> to rewrite it");511}512513// rewrite methods, in two passes514int len = _methods->length();515bool invokespecial_error = false;516517for (int i = len-1; i >= 0; i--) {518Method* method = _methods->at(i);519scan_method(method, false, &invokespecial_error);520if (invokespecial_error) {521// If you get an error here, there is no reversing bytecodes522// This exception is stored for this class and no further attempt is523// made at verifying or rewriting.524THROW_MSG(vmSymbols::java_lang_InternalError(),525"This classfile overflows invokespecial for interfaces "526"and cannot be loaded");527return;528}529}530531// May have to fix invokedynamic bytecodes if invokestatic/InterfaceMethodref532// entries had to be added.533patch_invokedynamic_bytecodes();534}535536void Rewriter::rewrite(instanceKlassHandle klass, TRAPS) {537ResourceMark rm(THREAD);538Rewriter rw(klass, klass->constants(), klass->methods(), CHECK);539// (That's all, folks.)540}541542543Rewriter::Rewriter(instanceKlassHandle klass, constantPoolHandle cpool, Array<Method*>* methods, TRAPS)544: _klass(klass),545_pool(cpool),546_methods(methods)547{548549// Rewrite bytecodes - exception here exits.550rewrite_bytecodes(CHECK);551552// Stress restoring bytecodes553if (StressRewriter) {554restore_bytecodes();555rewrite_bytecodes(CHECK);556}557558// allocate constant pool cache, now that we've seen all the bytecodes559make_constant_pool_cache(THREAD);560561// Restore bytecodes to their unrewritten state if there are exceptions562// rewriting bytecodes or allocating the cpCache563if (HAS_PENDING_EXCEPTION) {564restore_bytecodes();565return;566}567568// Relocate after everything, but still do this under the is_rewritten flag,569// so methods with jsrs in custom class lists in aren't attempted to be570// rewritten in the RO section of the shared archive.571// Relocated bytecodes don't have to be restored, only the cp cache entries572int len = _methods->length();573for (int i = len-1; i >= 0; i--) {574methodHandle m(THREAD, _methods->at(i));575576if (m->has_jsrs()) {577m = rewrite_jsrs(m, THREAD);578// Restore bytecodes to their unrewritten state if there are exceptions579// relocating bytecodes. If some are relocated, that is ok because that580// doesn't affect constant pool to cpCache rewriting.581if (HAS_PENDING_EXCEPTION) {582restore_bytecodes();583return;584}585// Method might have gotten rewritten.586methods->at_put(i, m());587}588}589}590591592