1 /*
   2  * Copyright (c) 2016, 2020, 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 
  26 #include "aot/aotCodeHeap.hpp"
  27 #include "aot/aotLoader.hpp"
  28 #include "ci/ciUtilities.inline.hpp"
  29 #include "classfile/javaAssertions.hpp"
  30 #include "gc/shared/cardTable.hpp"
  31 #include "gc/shared/cardTableBarrierSet.hpp"
  32 #include "gc/shared/gcConfig.hpp"
  33 #include "gc/g1/heapRegion.hpp"
  34 #include "interpreter/abstractInterpreter.hpp"
  35 #include "jvmci/compilerRuntime.hpp"
  36 #include "jvmci/jvmciRuntime.hpp"
  37 #include "logging/log.hpp"
  38 #include "memory/allocation.inline.hpp"
  39 #include "memory/universe.hpp"
  40 #include "oops/compressedOops.hpp"
  41 #include "oops/klass.inline.hpp"
  42 #include "oops/method.inline.hpp"
  43 #include "runtime/atomic.hpp"
  44 #include "runtime/deoptimization.hpp"
  45 #include "runtime/handles.inline.hpp"
  46 #include "runtime/os.hpp"
  47 #include "runtime/safepointVerifiers.hpp"
  48 #include "runtime/sharedRuntime.hpp"
  49 #include "runtime/vmOperations.hpp"
  50 #include "utilities/powerOfTwo.hpp"
  51 #include "utilities/sizes.hpp"
  52 
  53 bool AOTLib::_narrow_oop_shift_initialized = false;
  54 int  AOTLib::_narrow_oop_shift = 0;
  55 int  AOTLib::_narrow_klass_shift = 0;
  56 
  57 address AOTLib::load_symbol(const char *name) {
  58   address symbol = (address) os::dll_lookup(_dl_handle, name);
  59   if (symbol == NULL) {
  60     tty->print_cr("Shared file %s error: missing %s", _name, name);
  61     vm_exit(1);
  62   }
  63   return symbol;
  64 }
  65 
  66 Klass* AOTCodeHeap::get_klass_from_got(const char* klass_name, int klass_len, const Method* method) {
  67   AOTKlassData* klass_data = (AOTKlassData*)_lib->load_symbol(klass_name);
  68   Klass* k = (Klass*)_klasses_got[klass_data->_got_index];
  69   if (k == NULL) {
  70     Thread* thread = Thread::current();
  71     k = lookup_klass(klass_name, klass_len, method, thread);
  72     // Note, exceptions are cleared.
  73     if (k == NULL) {
  74       fatal("Shared file %s error: klass %s should be resolved already", _lib->name(), klass_name);
  75       vm_exit(1);
  76     }
  77     // Patch now to avoid extra runtime lookup
  78     _klasses_got[klass_data->_got_index] = k;
  79     if (k->is_instance_klass()) {
  80       InstanceKlass* ik = InstanceKlass::cast(k);
  81       if (ik->is_initialized()) {
  82         _klasses_got[klass_data->_got_index - 1] = ik;
  83       }
  84     }
  85   }
  86   return k;
  87 }
  88 
  89 Klass* AOTCodeHeap::lookup_klass(const char* name, int len, const Method* method, Thread* thread) {
  90   ResourceMark rm(thread);
  91   assert(method != NULL, "incorrect call parameter");
  92   methodHandle caller(thread, (Method*)method);
  93 
  94   // Use class loader of aot method.
  95   Handle loader(thread, caller->method_holder()->class_loader());
  96   Handle protection_domain(thread, caller->method_holder()->protection_domain());
  97 
  98   // Ignore wrapping L and ;
  99   if (name[0] == JVM_SIGNATURE_CLASS) {
 100     assert(len > 2, "small name %s", name);
 101     name++;
 102     len -= 2;
 103   }
 104   TempNewSymbol sym = SymbolTable::probe(name, len);
 105   if (sym == NULL) {
 106     log_debug(aot, class, resolve)("Probe failed for AOT class %s", name);
 107     return NULL;
 108   }
 109   Klass* k = SystemDictionary::find_instance_or_array_klass(sym, loader, protection_domain, thread);
 110   assert(!thread->has_pending_exception(), "should not throw");
 111 
 112   if (k != NULL) {
 113     log_info(aot, class, resolve)("%s %s (lookup)", caller->method_holder()->external_name(), k->external_name());
 114   }
 115   return k;
 116 }
 117 
 118 void AOTLib::handle_config_error(const char* format, ...) {
 119   if (PrintAOT) {
 120     va_list ap;
 121     va_start(ap, format);
 122     tty->vprint_cr(format, ap);
 123     va_end(ap);
 124   }
 125   if (UseAOTStrictLoading) {
 126     vm_exit(1);
 127   }
 128   _valid = false;
 129 }
 130 
 131 void AOTLib::verify_flag(bool aot_flag, bool flag, const char* name) {
 132   if (_valid && aot_flag != flag) {
 133     handle_config_error("Shared file %s error: %s has different value '%s' from current '%s'", _name, name , (aot_flag ? "true" : "false"), (flag ? "true" : "false"));
 134   }
 135 }
 136 
 137 void AOTLib::verify_flag(int aot_flag, int flag, const char* name) {
 138   if (_valid && aot_flag != flag) {
 139     handle_config_error("Shared file %s error: %s has different value '%d' from current '%d'", _name, name , aot_flag, flag);
 140   }
 141 }
 142 
 143 void AOTLib::verify_config() {
 144   GrowableArray<AOTLib*>* libraries = AOTLoader::libraries();
 145   for (GrowableArrayIterator<AOTLib*> lib = libraries->begin(); lib != libraries->end(); ++lib) {
 146     if ((*lib)->_config == _config) {
 147       handle_config_error("AOT library %s already loaded.", (*lib)->_name);
 148       return;
 149     }
 150   }
 151 
 152   if (_header->_version != AOTHeader::AOT_SHARED_VERSION) {
 153     handle_config_error("Invalid version of the shared file %s. Expected %d but was %d", _name, _header->_version, AOTHeader::AOT_SHARED_VERSION);
 154     return;
 155   }
 156 
 157   const char* aot_jvm_version = (const char*)_header + _header->_jvm_version_offset + 2;
 158   if (strcmp(aot_jvm_version, VM_Version::jre_release_version()) != 0) {
 159     handle_config_error("JVM version '%s' recorded in the shared file %s does not match current version '%s'", aot_jvm_version, _name, VM_Version::jre_release_version());
 160     return;
 161   }
 162 
 163   // Debug VM has different layout of runtime and metadata structures
 164 #ifdef ASSERT
 165   verify_flag(_config->_debug_VM, true, "Debug VM version");
 166 #else
 167   verify_flag(!(_config->_debug_VM), true, "Product VM version");
 168 #endif
 169   // Check configuration size
 170   verify_flag(_config->_config_size, AOTConfiguration::CONFIG_SIZE, "AOT configuration size");
 171 
 172   // Check GC
 173   CollectedHeap::Name gc = (CollectedHeap::Name)_config->_gc;
 174   if (_valid && !GCConfig::is_gc_selected(gc)) {
 175     handle_config_error("Shared file %s error: used '%s' is different from current '%s'", _name, GCConfig::hs_err_name(gc), GCConfig::hs_err_name());
 176   }
 177 
 178   // Check flags
 179   verify_flag(_config->_useCompressedOops, UseCompressedOops, "UseCompressedOops");
 180   verify_flag(_config->_useCompressedClassPointers, UseCompressedClassPointers, "UseCompressedClassPointers");
 181   verify_flag(_config->_useTLAB, UseTLAB, "UseTLAB");
 182   verify_flag(_config->_useBiasedLocking, UseBiasedLocking, "UseBiasedLocking");
 183   verify_flag(_config->_objectAlignment, ObjectAlignmentInBytes, "ObjectAlignmentInBytes");
 184   verify_flag(_config->_contendedPaddingWidth, ContendedPaddingWidth, "ContendedPaddingWidth");
 185   verify_flag(_config->_enableContended, EnableContended, "EnableContended");
 186   verify_flag(_config->_restrictContended, RestrictContended, "RestrictContended");
 187 
 188   if (!TieredCompilation && _config->_tieredAOT) {
 189     handle_config_error("Shared file %s error: Expected to run with tiered compilation on", _name);
 190   }
 191 
 192   // Shifts are static values which initialized by 0 until java heap initialization.
 193   // AOT libs are loaded before heap initialized so shift values are not set.
 194   // It is okay since ObjectAlignmentInBytes flag which defines shifts value is set before AOT libs are loaded.
 195   // Set shifts value based on first AOT library config.
 196   if (UseCompressedOops && _valid) {
 197     if (!_narrow_oop_shift_initialized) {
 198       _narrow_oop_shift = _config->_narrowOopShift;
 199       if (UseCompressedClassPointers) { // It is set only if UseCompressedOops is set
 200         _narrow_klass_shift = _config->_narrowKlassShift;
 201       }
 202       _narrow_oop_shift_initialized = true;
 203     } else {
 204       verify_flag(_config->_narrowOopShift, _narrow_oop_shift, "aot_config->_narrowOopShift");
 205       if (UseCompressedClassPointers) { // It is set only if UseCompressedOops is set
 206         verify_flag(_config->_narrowKlassShift, _narrow_klass_shift, "aot_config->_narrowKlassShift");
 207       }
 208     }
 209   }
 210 }
 211 
 212 AOTLib::~AOTLib() {
 213   os::free((void*) _name);
 214 }
 215 
 216 AOTCodeHeap::~AOTCodeHeap() {
 217   FREE_C_HEAP_ARRAY(AOTClass, _classes);
 218   FREE_C_HEAP_ARRAY(CodeToAMethod, _code_to_aot);
 219 }
 220 
 221 AOTLib::AOTLib(void* handle, const char* name, int dso_id) : _valid(true), _dl_handle(handle), _dso_id(dso_id) {
 222   _name = (const char*) os::strdup(name);
 223 
 224   // Verify that VM runs with the same parameters as AOT tool.
 225   _config = (AOTConfiguration*) load_symbol("A.config");
 226   _header = (AOTHeader*) load_symbol("A.header");
 227 
 228   verify_config();
 229 
 230   if (!_valid && PrintAOT) {
 231       tty->print("%7d ", (int) tty->time_stamp().milliseconds());
 232       tty->print_cr("%4d     skipped %s  aot library", _dso_id, _name);
 233   }
 234 }
 235 
 236 AOTCodeHeap::AOTCodeHeap(AOTLib* lib) :
 237     CodeHeap("CodeHeap 'AOT'", CodeBlobType::AOT), _lib(lib), _classes(NULL), _code_to_aot(NULL) {
 238   assert(_lib->is_valid(), "invalid library");
 239 
 240   _lib_symbols_initialized = false;
 241   _aot_id = 0;
 242 
 243   _class_count = _lib->header()->_class_count;
 244   _method_count = _lib->header()->_method_count;
 245 
 246   // Collect metaspace info: names -> address in .got section
 247   _metaspace_names = (const char*) _lib->load_symbol("A.meta.names");
 248   _method_metadata =     (address) _lib->load_symbol("A.meth.metadata");
 249   _methods_offsets =     (address) _lib->load_symbol("A.meth.offsets");
 250   _klasses_offsets =     (address) _lib->load_symbol("A.kls.offsets");
 251   _dependencies    =     (address) _lib->load_symbol("A.kls.dependencies");
 252   _code_space      =     (address) _lib->load_symbol("A.text");
 253 
 254   // First cell is number of elements.
 255   _klasses_got      = (Metadata**) _lib->load_symbol("A.kls.got");
 256   _klasses_got_size = _lib->header()->_klasses_got_size;
 257 
 258   _metadata_got      = (Metadata**) _lib->load_symbol("A.meta.got");
 259   _metadata_got_size = _lib->header()->_metadata_got_size;
 260 
 261   _oop_got      = (oop*) _lib->load_symbol("A.oop.got");
 262   _oop_got_size = _lib->header()->_oop_got_size;
 263 
 264   // Collect stubs info
 265   _stubs_offsets = (int*) _lib->load_symbol("A.stubs.offsets");
 266 
 267   // code segments table
 268   _code_segments = (address) _lib->load_symbol("A.code.segments");
 269 
 270   // method state
 271   _method_state = (jlong*) _lib->load_symbol("A.meth.state");
 272 
 273   // Create a table for mapping classes
 274   _classes = NEW_C_HEAP_ARRAY(AOTClass, _class_count, mtCode);
 275   memset(_classes, 0, _class_count * sizeof(AOTClass));
 276 
 277   // Create table for searching AOTCompiledMethod based on pc.
 278   _code_to_aot = NEW_C_HEAP_ARRAY(CodeToAMethod, _method_count, mtCode);
 279   memset(_code_to_aot, 0, _method_count * sizeof(CodeToAMethod));
 280 
 281   _memory.set_low_boundary((char *)_code_space);
 282   _memory.set_high_boundary((char *)_code_space);
 283   _memory.set_low((char *)_code_space);
 284   _memory.set_high((char *)_code_space);
 285 
 286   _segmap.set_low_boundary((char *)_code_segments);
 287   _segmap.set_low((char *)_code_segments);
 288 
 289   _log2_segment_size = exact_log2(_lib->config()->_codeSegmentSize);
 290 
 291   // Register aot stubs
 292   register_stubs();
 293 
 294   if (PrintAOT || (PrintCompilation && PrintAOT)) {
 295     tty->print("%7d ", (int) tty->time_stamp().milliseconds());
 296     tty->print_cr("%4d     loaded    %s  aot library", _lib->id(), _lib->name());
 297   }
 298 }
 299 
 300 void AOTCodeHeap::publish_aot(const methodHandle& mh, AOTMethodData* method_data, int code_id) {
 301   // The method may be explicitly excluded by the user.
 302   // Or Interpreter uses an intrinsic for this method.
 303   // Or method has breakpoints.
 304   if (CompilerOracle::should_exclude(mh) ||
 305       !AbstractInterpreter::can_be_compiled(mh) ||
 306       (mh->number_of_breakpoints() > 0)) {
 307     return;
 308   }
 309   // Make sure no break points were set in the method in case of a safepoint
 310   // in the following code until aot code is registered.
 311   NoSafepointVerifier nsv;
 312 
 313   address code = method_data->_code;
 314   const char* name = method_data->_name;
 315   aot_metadata* meta = method_data->_meta;
 316 
 317   if (meta->scopes_pcs_begin() == meta->scopes_pcs_end()) {
 318     // Switch off NoSafepointVerifier because log_info() may cause safepoint
 319     // and it is fine because aot code will not be registered here.
 320     PauseNoSafepointVerifier pnsv(&nsv);
 321 
 322     // When the AOT compiler compiles something big we fail to generate metadata
 323     // in CodeInstaller::gather_metadata. In that case the scopes_pcs_begin == scopes_pcs_end.
 324     // In all successful cases we always have 2 entries of scope pcs.
 325     log_info(aot, class, resolve)("Failed to load %s (no metadata available)", mh->name_and_sig_as_C_string());
 326     _code_to_aot[code_id]._state = invalid;
 327     return;
 328   }
 329 
 330   jlong* state_adr = &_method_state[code_id];
 331   address metadata_table = method_data->_metadata_table;
 332   int metadata_size = method_data->_metadata_size;
 333   assert(code_id < _method_count, "sanity");
 334   _aot_id++;
 335 
 336 #ifdef ASSERT
 337   if (_aot_id > CIStop || _aot_id < CIStart) {
 338     // Skip compilation
 339     return;
 340   }
 341 #endif
 342   // Check one more time.
 343   if (_code_to_aot[code_id]._state == invalid) {
 344     return;
 345   }
 346   AOTCompiledMethod *aot = new AOTCompiledMethod(code, mh(), meta, metadata_table, metadata_size, state_adr, this, name, code_id, _aot_id);
 347   assert(_code_to_aot[code_id]._aot == NULL, "should be not initialized");
 348   _code_to_aot[code_id]._aot = aot; // Should set this first
 349   if (Atomic::cmpxchg(&_code_to_aot[code_id]._state, not_set, in_use) != not_set) {
 350     _code_to_aot[code_id]._aot = NULL; // Clean
 351   } else { // success
 352     // Publish method
 353 #ifdef TIERED
 354     mh->set_aot_code(aot);
 355 #endif
 356     {
 357       MutexLocker pl(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
 358       Method::set_code(mh, aot);
 359     }
 360     if (PrintAOT || (PrintCompilation && PrintAOT)) {
 361       PauseNoSafepointVerifier pnsv(&nsv); // aot code is registered already
 362       aot->print_on(tty, NULL);
 363     }
 364     // Publish oop only after we are visible to CompiledMethodIterator
 365     aot->set_oop(mh()->method_holder()->klass_holder());
 366   }
 367 }
 368 
 369 void AOTCodeHeap::link_primitive_array_klasses() {
 370   ResourceMark rm;
 371   for (int i = T_BOOLEAN; i <= T_CONFLICT; i++) {
 372     BasicType t = (BasicType)i;
 373     if (is_java_primitive(t)) {
 374       const Klass* arr_klass = Universe::typeArrayKlassObj(t);
 375       AOTKlassData* klass_data = (AOTKlassData*) os::dll_lookup(_lib->dl_handle(), arr_klass->signature_name());
 376       if (klass_data != NULL) {
 377         // Set both GOT cells, resolved and initialized klass pointers.
 378         // _got_index points to second cell - resolved klass pointer.
 379         _klasses_got[klass_data->_got_index-1] = (Metadata*)arr_klass; // Initialized
 380         _klasses_got[klass_data->_got_index  ] = (Metadata*)arr_klass; // Resolved
 381         if (PrintAOT) {
 382           tty->print_cr("[Found  %s  in  %s]", arr_klass->internal_name(), _lib->name());
 383         }
 384       }
 385     }
 386   }
 387 }
 388 
 389 void AOTCodeHeap::register_stubs() {
 390   int stubs_count = _stubs_offsets[0]; // contains number
 391   _stubs_offsets++;
 392   AOTMethodOffsets* stub_offsets = (AOTMethodOffsets*)_stubs_offsets;
 393   for (int i = 0; i < stubs_count; ++i) {
 394     const char* stub_name = _metaspace_names + stub_offsets[i]._name_offset;
 395     address entry = _code_space  + stub_offsets[i]._code_offset;
 396     aot_metadata* meta = (aot_metadata *) (_method_metadata + stub_offsets[i]._meta_offset);
 397     address metadata_table = (address)_metadata_got + stub_offsets[i]._metadata_got_offset;
 398     int metadata_size = stub_offsets[i]._metadata_got_size;
 399     int code_id = stub_offsets[i]._code_id;
 400     assert(code_id < _method_count, "sanity");
 401     jlong* state_adr = &_method_state[code_id];
 402     int len = Bytes::get_Java_u2((address)stub_name);
 403     stub_name += 2;
 404     char* full_name = NEW_C_HEAP_ARRAY(char, len+5, mtCode);
 405     memcpy(full_name, "AOT ", 4);
 406     memcpy(full_name+4, stub_name, len);
 407     full_name[len+4] = 0;
 408     guarantee(_code_to_aot[code_id]._state != invalid, "stub %s can't be invalidated", full_name);
 409     AOTCompiledMethod* aot = new AOTCompiledMethod(entry, NULL, meta, metadata_table, metadata_size, state_adr, this, full_name, code_id, i);
 410     assert(_code_to_aot[code_id]._aot  == NULL, "should be not initialized");
 411     _code_to_aot[code_id]._aot  = aot;
 412     if (Atomic::cmpxchg(&_code_to_aot[code_id]._state, not_set, in_use) != not_set) {
 413       fatal("stab '%s' code state is %d", full_name, _code_to_aot[code_id]._state);
 414     }
 415     // Adjust code buffer boundaries only for stubs because they are last in the buffer.
 416     adjust_boundaries(aot);
 417     if (PrintAOT && Verbose) {
 418       aot->print_on(tty, NULL);
 419     }
 420   }
 421 }
 422 
 423 #define SET_AOT_GLOBAL_SYMBOL_VALUE(AOTSYMNAME, AOTSYMTYPE, VMSYMVAL) \
 424   {                                                                   \
 425     AOTSYMTYPE * adr = (AOTSYMTYPE *) os::dll_lookup(_lib->dl_handle(), AOTSYMNAME);  \
 426     /* Check for a lookup error */                                    \
 427     guarantee(adr != NULL, "AOT Symbol not found %s", AOTSYMNAME);    \
 428     *adr = (AOTSYMTYPE) VMSYMVAL;                                     \
 429   }
 430 
 431 void AOTCodeHeap::link_graal_runtime_symbols()  {
 432     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_monitorenter", address, JVMCIRuntime::monitorenter);
 433     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_monitorexit", address, JVMCIRuntime::monitorexit);
 434     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_object", address, JVMCIRuntime::log_object);
 435     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_printf", address, JVMCIRuntime::log_printf);
 436     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_primitive", address, JVMCIRuntime::log_primitive);
 437     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_instance", address, JVMCIRuntime::new_instance);
 438     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_array", address, JVMCIRuntime::new_array);
 439     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_multi_array", address, JVMCIRuntime::new_multi_array);
 440     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_instance", address, JVMCIRuntime::dynamic_new_instance);
 441     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_array", address, JVMCIRuntime::dynamic_new_array);
 442     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_instance_or_null", address, JVMCIRuntime::new_instance_or_null);
 443     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_array_or_null", address, JVMCIRuntime::new_array_or_null);
 444     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_multi_array_or_null", address, JVMCIRuntime::new_multi_array_or_null);
 445     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_instance_or_null", address, JVMCIRuntime::dynamic_new_instance_or_null);
 446     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_array_or_null", address, JVMCIRuntime::dynamic_new_array_or_null);
 447     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_validate_object", address, JVMCIRuntime::validate_object);
 448 #if INCLUDE_G1GC
 449     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_write_barrier_pre", address, JVMCIRuntime::write_barrier_pre);
 450     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_write_barrier_post", address, JVMCIRuntime::write_barrier_post);
 451 #endif
 452     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_identity_hash_code", address, JVMCIRuntime::identity_hash_code);
 453     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_exception_handler_for_pc", address, JVMCIRuntime::exception_handler_for_pc);
 454     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_test_deoptimize_call_int", address, JVMCIRuntime::test_deoptimize_call_int);
 455     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_and_post_jvmti_exception", address, JVMCIRuntime::throw_and_post_jvmti_exception);
 456     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_klass_external_name_exception", address, JVMCIRuntime::throw_klass_external_name_exception);
 457     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_class_cast_exception", address, JVMCIRuntime::throw_class_cast_exception);
 458     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_vm_message", address, JVMCIRuntime::vm_message);
 459     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_vm_error", address, JVMCIRuntime::vm_error);
 460 }
 461 
 462 void AOTCodeHeap::link_shared_runtime_symbols() {
 463     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_static_entry", address, SharedRuntime::get_resolve_static_call_stub());
 464     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_virtual_entry", address, SharedRuntime::get_resolve_virtual_call_stub());
 465     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_opt_virtual_entry", address, SharedRuntime::get_resolve_opt_virtual_call_stub());
 466     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_deopt_blob_unpack", address, SharedRuntime::deopt_blob()->unpack());
 467     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_deopt_blob_unpack_with_exception_in_tls", address, SharedRuntime::deopt_blob()->unpack_with_exception_in_tls());
 468     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_deopt_blob_uncommon_trap", address, SharedRuntime::deopt_blob()->uncommon_trap());
 469     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_ic_miss_stub", address, SharedRuntime::get_ic_miss_stub());
 470     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_handle_wrong_method_stub", address, SharedRuntime::get_handle_wrong_method_stub());
 471     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_exception_handler_for_return_address", address, SharedRuntime::exception_handler_for_return_address);
 472     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_register_finalizer", address, SharedRuntime::register_finalizer);
 473     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_object_notify", address, JVMCIRuntime::object_notify);
 474     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_object_notifyAll", address, JVMCIRuntime::object_notifyAll);
 475     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_OSR_migration_end", address, SharedRuntime::OSR_migration_end);
 476     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_enable_stack_reserved_zone", address, SharedRuntime::enable_stack_reserved_zone);
 477     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_dynamic_invoke", address, CompilerRuntime::resolve_dynamic_invoke);
 478     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_string_by_symbol", address, CompilerRuntime::resolve_string_by_symbol);
 479     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_klass_by_symbol", address, CompilerRuntime::resolve_klass_by_symbol);
 480     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_method_by_symbol_and_load_counters", address, CompilerRuntime::resolve_method_by_symbol_and_load_counters);
 481     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_initialize_klass_by_symbol", address, CompilerRuntime::initialize_klass_by_symbol);
 482     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_invocation_event", address, CompilerRuntime::invocation_event);
 483     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_backedge_event", address, CompilerRuntime::backedge_event);
 484 
 485     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dpow", address, SharedRuntime::dpow);
 486     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dexp", address, SharedRuntime::dexp);
 487     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dcos", address, SharedRuntime::dcos);
 488     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dsin", address, SharedRuntime::dsin);
 489     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dtan", address, SharedRuntime::dtan);
 490     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dlog", address, SharedRuntime::dlog);
 491     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dlog10", address, SharedRuntime::dlog10);
 492 }
 493 
 494 void AOTCodeHeap::link_stub_routines_symbols() {
 495     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jbyte_arraycopy", address, StubRoutines::_jbyte_arraycopy);
 496     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jshort_arraycopy", address, StubRoutines::_jshort_arraycopy);
 497     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jint_arraycopy", address, StubRoutines::_jint_arraycopy);
 498     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jlong_arraycopy", address, StubRoutines::_jlong_arraycopy);
 499     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_arraycopy", address, StubRoutines::_oop_arraycopy);
 500     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_arraycopy_uninit", address, StubRoutines::_oop_arraycopy_uninit);
 501 
 502     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jbyte_disjoint_arraycopy", address, StubRoutines::_jbyte_disjoint_arraycopy);
 503     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jshort_disjoint_arraycopy", address, StubRoutines::_jshort_disjoint_arraycopy);
 504     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jint_disjoint_arraycopy", address, StubRoutines::_jint_disjoint_arraycopy);
 505     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jlong_disjoint_arraycopy", address, StubRoutines::_jlong_disjoint_arraycopy);
 506     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_disjoint_arraycopy", address, StubRoutines::_oop_disjoint_arraycopy);
 507     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_disjoint_arraycopy_uninit", address, StubRoutines::_oop_disjoint_arraycopy_uninit);
 508 
 509     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jbyte_arraycopy", address, StubRoutines::_arrayof_jbyte_arraycopy);
 510     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jshort_arraycopy", address, StubRoutines::_arrayof_jshort_arraycopy);
 511     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jint_arraycopy", address, StubRoutines::_arrayof_jint_arraycopy);
 512     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jlong_arraycopy", address, StubRoutines::_arrayof_jlong_arraycopy);
 513     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_arraycopy", address, StubRoutines::_arrayof_oop_arraycopy);
 514     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_arraycopy_uninit", address, StubRoutines::_arrayof_oop_arraycopy_uninit);
 515 
 516     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jbyte_disjoint_arraycopy", address, StubRoutines::_arrayof_jbyte_disjoint_arraycopy);
 517     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jshort_disjoint_arraycopy", address, StubRoutines::_arrayof_jshort_disjoint_arraycopy);
 518     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jint_disjoint_arraycopy", address, StubRoutines::_arrayof_jint_disjoint_arraycopy);
 519     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jlong_disjoint_arraycopy", address, StubRoutines::_arrayof_jlong_disjoint_arraycopy);
 520     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_disjoint_arraycopy", address, StubRoutines::_arrayof_oop_disjoint_arraycopy);
 521     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_disjoint_arraycopy_uninit", address, StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit);
 522 
 523     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_unsafe_arraycopy", address, StubRoutines::_unsafe_arraycopy);
 524 
 525     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_checkcast_arraycopy", address, StubRoutines::_checkcast_arraycopy);
 526 
 527     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_generic_arraycopy", address, StubRoutines::_generic_arraycopy);
 528 
 529     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_aescrypt_encryptBlock", address, StubRoutines::_aescrypt_encryptBlock);
 530     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_aescrypt_decryptBlock", address, StubRoutines::_aescrypt_decryptBlock);
 531     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_cipherBlockChaining_encryptAESCrypt", address, StubRoutines::_cipherBlockChaining_encryptAESCrypt);
 532     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_cipherBlockChaining_decryptAESCrypt", address, StubRoutines::_cipherBlockChaining_decryptAESCrypt);
 533     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_electronicCodeBook_encryptAESCrypt", address, StubRoutines::_electronicCodeBook_encryptAESCrypt);
 534     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_electronicCodeBook_decryptAESCrypt", address, StubRoutines::_electronicCodeBook_decryptAESCrypt);
 535     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_update_bytes_crc32", address, StubRoutines::_updateBytesCRC32);
 536     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_crc_table_adr", address, StubRoutines::_crc_table_adr);
 537 
 538 
 539     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha1_implCompress", address, StubRoutines::_sha1_implCompress);
 540     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha1_implCompressMB", address, StubRoutines::_sha1_implCompressMB);
 541     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha256_implCompress", address, StubRoutines::_sha256_implCompress);
 542     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha256_implCompressMB", address, StubRoutines::_sha256_implCompressMB);
 543     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha512_implCompress", address, StubRoutines::_sha512_implCompress);
 544     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha512_implCompressMB", address, StubRoutines::_sha512_implCompressMB);
 545     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_multiplyToLen", address, StubRoutines::_multiplyToLen);
 546 
 547     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_counterMode_AESCrypt", address, StubRoutines::_counterMode_AESCrypt);
 548     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_ghash_processBlocks", address, StubRoutines::_ghash_processBlocks);
 549     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_base64_encodeBlock", address, StubRoutines::_base64_encodeBlock);
 550     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_crc32c_table_addr", address, StubRoutines::_crc32c_table_addr);
 551     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_updateBytesCRC32C", address, StubRoutines::_updateBytesCRC32C);
 552     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_updateBytesAdler32", address, StubRoutines::_updateBytesAdler32);
 553     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_squareToLen", address, StubRoutines::_squareToLen);
 554     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_mulAdd", address, StubRoutines::_mulAdd);
 555     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_montgomeryMultiply",  address, StubRoutines::_montgomeryMultiply);
 556     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_montgomerySquare", address, StubRoutines::_montgomerySquare);
 557     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_vectorizedMismatch", address, StubRoutines::_vectorizedMismatch);
 558     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_bigIntegerRightShiftWorker", address, StubRoutines::_bigIntegerRightShiftWorker);
 559     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_bigIntegerLeftShiftWorker", address, StubRoutines::_bigIntegerLeftShiftWorker);
 560 
 561     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_throw_delayed_StackOverflowError_entry", address, StubRoutines::_throw_delayed_StackOverflowError_entry);
 562 
 563 }
 564 
 565 void AOTCodeHeap::link_os_symbols() {
 566     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_os_javaTimeMillis", address, os::javaTimeMillis);
 567     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_os_javaTimeNanos", address, os::javaTimeNanos);
 568 }
 569 
 570 /*
 571  * Link any global symbols in precompiled DSO with dlopen() _dl_handle
 572  * dso_handle.
 573  */
 574 
 575 void AOTCodeHeap::link_global_lib_symbols() {
 576   if (!_lib_symbols_initialized) {
 577     _lib_symbols_initialized = true;
 578 
 579     CollectedHeap* heap = Universe::heap();
 580     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_card_table_address", address, (BarrierSet::barrier_set()->is_a(BarrierSet::CardTableBarrierSet) ? ci_card_table_address() : NULL));
 581     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_top_address", address, (heap->supports_inline_contig_alloc() ? heap->top_addr() : NULL));
 582     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_end_address", address, (heap->supports_inline_contig_alloc() ? heap->end_addr() : NULL));
 583     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_polling_page", address, os::get_polling_page());
 584     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_klass_base_address", address, CompressedKlassPointers::base());
 585     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_oop_base_address", address, CompressedOops::base());
 586 #if INCLUDE_G1GC
 587     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_log_of_heap_region_grain_bytes", int, HeapRegion::LogOfHRGrainBytes);
 588 #endif
 589     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_inline_contiguous_allocation_supported", bool, heap->supports_inline_contig_alloc());
 590     link_shared_runtime_symbols();
 591     link_stub_routines_symbols();
 592     link_os_symbols();
 593     link_graal_runtime_symbols();
 594 
 595     // Link primitive array klasses.
 596     link_primitive_array_klasses();
 597   }
 598 }
 599 
 600 #ifndef PRODUCT
 601 int AOTCodeHeap::klasses_seen = 0;
 602 int AOTCodeHeap::aot_klasses_found = 0;
 603 int AOTCodeHeap::aot_klasses_fp_miss = 0;
 604 int AOTCodeHeap::aot_klasses_cl_miss = 0;
 605 int AOTCodeHeap::aot_methods_found = 0;
 606 
 607 void AOTCodeHeap::print_statistics() {
 608   tty->print_cr("Classes seen: %d  AOT classes found: %d  AOT methods found: %d", klasses_seen, aot_klasses_found, aot_methods_found);
 609   tty->print_cr("AOT fingerprint mismatches: %d  AOT class loader mismatches: %d", aot_klasses_fp_miss, aot_klasses_cl_miss);
 610 }
 611 #endif
 612 
 613 Method* AOTCodeHeap::find_method(Klass* klass, Thread* thread, const char* method_name) {
 614   int method_name_len = Bytes::get_Java_u2((address)method_name);
 615   method_name += 2;
 616   const char* signature_name = method_name + method_name_len;
 617   int signature_name_len = Bytes::get_Java_u2((address)signature_name);
 618   signature_name += 2;
 619   // The class should have been loaded so the method and signature should already be
 620   // in the symbol table.  If they're not there, the method doesn't exist.
 621   TempNewSymbol name = SymbolTable::probe(method_name, method_name_len);
 622   TempNewSymbol signature = SymbolTable::probe(signature_name, signature_name_len);
 623 
 624   Method* m;
 625   if (name == NULL || signature == NULL) {
 626     m = NULL;
 627   } else if (name == vmSymbols::object_initializer_name() ||
 628              name == vmSymbols::class_initializer_name()) {
 629     // Never search superclasses for constructors
 630     if (klass->is_instance_klass()) {
 631       m = InstanceKlass::cast(klass)->find_method(name, signature);
 632     } else {
 633       m = NULL;
 634     }
 635   } else {
 636     m = klass->lookup_method(name, signature);
 637     if (m == NULL && klass->is_instance_klass()) {
 638       m = InstanceKlass::cast(klass)->lookup_method_in_ordered_interfaces(name, signature);
 639     }
 640   }
 641   if (m == NULL) {
 642     // Fatal error because we assume classes and methods should not be changed since aot compilation.
 643     const char* klass_name = klass->external_name();
 644     int klass_len = (int)strlen(klass_name);
 645     char* meta_name = NEW_RESOURCE_ARRAY(char, klass_len + 1 + method_name_len + signature_name_len + 1);
 646     memcpy(meta_name, klass_name, klass_len);
 647     meta_name[klass_len] = '.';
 648     memcpy(&meta_name[klass_len + 1], method_name, method_name_len);
 649     memcpy(&meta_name[klass_len + 1 + method_name_len], signature_name, signature_name_len);
 650     meta_name[klass_len + 1 + method_name_len + signature_name_len] = '\0';
 651     Handle exception = Exceptions::new_exception(thread, vmSymbols::java_lang_NoSuchMethodError(), meta_name);
 652     java_lang_Throwable::print(exception(), tty);
 653     tty->cr();
 654     java_lang_Throwable::print_stack_trace(exception, tty);
 655     tty->cr();
 656     fatal("Failed to find method '%s'", meta_name);
 657   }
 658   NOT_PRODUCT( aot_methods_found++; )
 659   return m;
 660 }
 661 
 662 AOTKlassData* AOTCodeHeap::find_klass(const char *name) {
 663   return (AOTKlassData*) os::dll_lookup(_lib->dl_handle(), name);
 664 }
 665 
 666 AOTKlassData* AOTCodeHeap::find_klass(InstanceKlass* ik) {
 667   ResourceMark rm;
 668   AOTKlassData* klass_data = find_klass(ik->signature_name());
 669   return klass_data;
 670 }
 671 
 672 bool AOTCodeHeap::is_dependent_method(Klass* dependee, AOTCompiledMethod* aot) {
 673   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
 674   AOTKlassData* klass_data = find_klass(dependee_ik);
 675   if (klass_data == NULL) {
 676     return false; // no AOT records for this class - no dependencies
 677   }
 678   if (!dependee_ik->has_passed_fingerprint_check()) {
 679     return false; // different class
 680   }
 681 
 682   int methods_offset = klass_data->_dependent_methods_offset;
 683   if (methods_offset >= 0) {
 684     address methods_cnt_adr = _dependencies + methods_offset;
 685     int methods_cnt = *(int*)methods_cnt_adr;
 686     int* indexes = (int*)(methods_cnt_adr + 4);
 687     for (int i = 0; i < methods_cnt; ++i) {
 688       int code_id = indexes[i];
 689       if (_code_to_aot[code_id]._aot == aot) {
 690         return true; // found dependent method
 691       }
 692     }
 693   }
 694   return false;
 695 }
 696 
 697 void AOTCodeHeap::mark_evol_dependent_methods(InstanceKlass* dependee) {
 698   AOTKlassData* klass_data = find_klass(dependee);
 699   if (klass_data == NULL) {
 700     return; // no AOT records for this class - no dependencies
 701   }
 702   if (!dependee->has_passed_fingerprint_check()) {
 703     return; // different class
 704   }
 705 
 706   int methods_offset = klass_data->_dependent_methods_offset;
 707   if (methods_offset >= 0) {
 708     address methods_cnt_adr = _dependencies + methods_offset;
 709     int methods_cnt = *(int*)methods_cnt_adr;
 710     int* indexes = (int*)(methods_cnt_adr + 4);
 711     for (int i = 0; i < methods_cnt; ++i) {
 712       int code_id = indexes[i];
 713       AOTCompiledMethod* aot = _code_to_aot[code_id]._aot;
 714       if (aot != NULL) {
 715         aot->mark_for_deoptimization(false);
 716       }
 717     }
 718   }
 719 }
 720 
 721 void AOTCodeHeap::sweep_dependent_methods(int* indexes, int methods_cnt) {
 722   int marked = 0;
 723   for (int i = 0; i < methods_cnt; ++i) {
 724     int code_id = indexes[i];
 725     // Invalidate aot code.
 726     if (Atomic::cmpxchg(&_code_to_aot[code_id]._state, not_set, invalid) != not_set) {
 727       if (_code_to_aot[code_id]._state == in_use) {
 728         AOTCompiledMethod* aot = _code_to_aot[code_id]._aot;
 729         assert(aot != NULL, "aot should be set");
 730         if (!aot->is_runtime_stub()) { // Something is wrong - should not invalidate stubs.
 731           aot->mark_for_deoptimization(false);
 732           marked++;
 733         }
 734       }
 735     }
 736   }
 737   if (marked > 0) {
 738     Deoptimization::deoptimize_all_marked();
 739   }
 740 }
 741 
 742 void AOTCodeHeap::sweep_dependent_methods(AOTKlassData* klass_data) {
 743   // Make dependent methods non_entrant forever.
 744   int methods_offset = klass_data->_dependent_methods_offset;
 745   if (methods_offset >= 0) {
 746     address methods_cnt_adr = _dependencies + methods_offset;
 747     int methods_cnt = *(int*)methods_cnt_adr;
 748     int* indexes = (int*)(methods_cnt_adr + 4);
 749     sweep_dependent_methods(indexes, methods_cnt);
 750   }
 751 }
 752 
 753 void AOTCodeHeap::sweep_dependent_methods(InstanceKlass* ik) {
 754   AOTKlassData* klass_data = find_klass(ik);
 755   vmassert(klass_data != NULL, "dependency data missing");
 756   sweep_dependent_methods(klass_data);
 757 }
 758 
 759 void AOTCodeHeap::sweep_method(AOTCompiledMethod *aot) {
 760   int indexes[] = {aot->method_index()};
 761   sweep_dependent_methods(indexes, 1);
 762   vmassert(aot->method()->code() != aot TIERED_ONLY( && aot->method()->aot_code() == NULL), "method still active");
 763 }
 764 
 765 
 766 bool AOTCodeHeap::load_klass_data(InstanceKlass* ik, Thread* thread) {
 767   ResourceMark rm;
 768 
 769   NOT_PRODUCT( klasses_seen++; )
 770 
 771   // AOT does not support custom class loaders.
 772   ClassLoaderData* cld = ik->class_loader_data();
 773   if (!cld->is_builtin_class_loader_data()) {
 774     log_trace(aot, class, load)("skip class  %s  for custom classloader %s (%p) tid=" INTPTR_FORMAT,
 775                                 ik->internal_name(), cld->loader_name(), cld, p2i(thread));
 776     return false;
 777   }
 778 
 779   AOTKlassData* klass_data = find_klass(ik);
 780   if (klass_data == NULL) {
 781     return false;
 782   }
 783 
 784   if (!ik->has_passed_fingerprint_check()) {
 785     NOT_PRODUCT( aot_klasses_fp_miss++; )
 786     log_trace(aot, class, fingerprint)("class  %s%s  has bad fingerprint in  %s tid=" INTPTR_FORMAT,
 787                                        ik->internal_name(), ik->is_shared() ? " (shared)" : "",
 788                                        _lib->name(), p2i(thread));
 789     sweep_dependent_methods(klass_data);
 790     return false;
 791   }
 792 
 793   if (ik->has_been_redefined()) {
 794     log_trace(aot, class, load)("class  %s%s in %s  has been redefined tid=" INTPTR_FORMAT,
 795                                 ik->internal_name(), ik->is_shared() ? " (shared)" : "",
 796                                 _lib->name(), p2i(thread));
 797     sweep_dependent_methods(klass_data);
 798     return false;
 799   }
 800 
 801   assert(klass_data->_class_id < _class_count, "invalid class id");
 802   AOTClass* aot_class = &_classes[klass_data->_class_id];
 803   ClassLoaderData* aot_cld = aot_class->_classloader;
 804   if (aot_cld != NULL && aot_cld != cld) {
 805     log_trace(aot, class, load)("class  %s  in  %s already loaded for classloader %s (%p) vs %s (%p) tid=" INTPTR_FORMAT,
 806                                 ik->internal_name(), _lib->name(), aot_cld->loader_name(), aot_cld, cld->loader_name(), cld, p2i(thread));
 807     NOT_PRODUCT( aot_klasses_cl_miss++; )
 808     return false;
 809   }
 810 
 811   if (_lib->config()->_omitAssertions && JavaAssertions::enabled(ik->name()->as_C_string(), ik->class_loader() == NULL)) {
 812     log_trace(aot, class, load)("class  %s  in  %s does not have java assertions in compiled code, but assertions are enabled for this execution.", ik->internal_name(), _lib->name());
 813     sweep_dependent_methods(klass_data);
 814     return false;
 815   }
 816 
 817   NOT_PRODUCT( aot_klasses_found++; )
 818 
 819   log_trace(aot, class, load)("found  %s  in  %s for classloader %s (%p) tid=" INTPTR_FORMAT, ik->internal_name(), _lib->name(), cld->loader_name(), cld, p2i(thread));
 820 
 821   aot_class->_classloader = cld;
 822   // Set klass's Resolve (second) got cell.
 823   _klasses_got[klass_data->_got_index] = ik;
 824   if (ik->is_initialized()) {
 825     _klasses_got[klass_data->_got_index - 1] = ik;
 826   }
 827 
 828   // Initialize global symbols of the DSO to the corresponding VM symbol values.
 829   link_global_lib_symbols();
 830 
 831   int methods_offset = klass_data->_compiled_methods_offset;
 832   if (methods_offset >= 0) {
 833     address methods_cnt_adr = _methods_offsets + methods_offset;
 834     int methods_cnt = *(int*)methods_cnt_adr;
 835     // Collect data about compiled methods
 836     AOTMethodData* methods_data = NEW_RESOURCE_ARRAY(AOTMethodData, methods_cnt);
 837     AOTMethodOffsets* methods_offsets = (AOTMethodOffsets*)(methods_cnt_adr + 4);
 838     for (int i = 0; i < methods_cnt; ++i) {
 839       AOTMethodOffsets* method_offsets = &methods_offsets[i];
 840       int code_id = method_offsets->_code_id;
 841       if (_code_to_aot[code_id]._state == invalid) {
 842         continue; // skip AOT methods slots which have been invalidated
 843       }
 844       AOTMethodData* method_data = &methods_data[i];
 845       const char* aot_name = _metaspace_names + method_offsets->_name_offset;
 846       method_data->_name = aot_name;
 847       method_data->_code = _code_space  + method_offsets->_code_offset;
 848       method_data->_meta = (aot_metadata*)(_method_metadata + method_offsets->_meta_offset);
 849       method_data->_metadata_table = (address)_metadata_got + method_offsets->_metadata_got_offset;
 850       method_data->_metadata_size  = method_offsets->_metadata_got_size;
 851       // aot_name format: "<u2_size>Ljava/lang/ThreadGroup;<u2_size>addUnstarted<u2_size>()V"
 852       int klass_len = Bytes::get_Java_u2((address)aot_name);
 853       const char* method_name = aot_name + 2 + klass_len;
 854       Method* m = AOTCodeHeap::find_method(ik, thread, method_name);
 855       methodHandle mh(thread, m);
 856       if (mh->code() != NULL) { // Does it have already compiled code?
 857         continue; // Don't overwrite
 858       }
 859       publish_aot(mh, method_data, code_id);
 860     }
 861   }
 862   return true;
 863 }
 864 
 865 AOTCompiledMethod* AOTCodeHeap::next_in_use_at(int start) const {
 866   for (int index = start; index < _method_count; index++) {
 867     if (_code_to_aot[index]._state != in_use) {
 868       continue; // Skip uninitialized entries.
 869     }
 870     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 871     return aot;
 872   }
 873   return NULL;
 874 }
 875 
 876 void* AOTCodeHeap::first() const {
 877   return next_in_use_at(0);
 878 }
 879 
 880 void* AOTCodeHeap::next(void* p) const {
 881   AOTCompiledMethod *aot = (AOTCompiledMethod *)p;
 882   int next_index = aot->method_index() + 1;
 883   assert(next_index <= _method_count, "");
 884   if (next_index == _method_count) {
 885     return NULL;
 886   }
 887   return next_in_use_at(next_index);
 888 }
 889 
 890 void* AOTCodeHeap::find_start(void* p) const {
 891   if (!contains(p)) {
 892     return NULL;
 893   }
 894   size_t offset = pointer_delta(p, low_boundary(), 1);
 895   // Use segments table
 896   size_t seg_idx = offset / _lib->config()->_codeSegmentSize;
 897   if ((int)(_code_segments[seg_idx]) == 0xff) {
 898     return NULL;
 899   }
 900   while (_code_segments[seg_idx] > 0) {
 901     seg_idx -= (int)_code_segments[seg_idx];
 902   }
 903   int code_offset = (int)seg_idx * _lib->config()->_codeSegmentSize;
 904   int aot_index = *(int*)(_code_space + code_offset);
 905   AOTCompiledMethod* aot = _code_to_aot[aot_index]._aot;
 906   assert(aot != NULL, "should find registered aot method");
 907   return aot;
 908 }
 909 
 910 AOTCompiledMethod* AOTCodeHeap::find_aot(address p) const {
 911   assert(contains(p), "should be here");
 912   return (AOTCompiledMethod *)find_start(p);
 913 }
 914 
 915 CodeBlob* AOTCodeHeap::find_blob_unsafe(void* start) const {
 916   return (CodeBlob*)AOTCodeHeap::find_start(start);
 917 }
 918 
 919 void AOTCodeHeap::oops_do(OopClosure* f) {
 920   for (int i = 0; i < _oop_got_size; i++) {
 921     oop* p = &_oop_got[i];
 922     if (*p == NULL)  continue;  // skip non-oops
 923     f->do_oop(p);
 924   }
 925   for (int index = 0; index < _method_count; index++) {
 926     if (_code_to_aot[index]._state != in_use) {
 927       continue; // Skip uninitialized entries.
 928     }
 929     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 930     aot->do_oops(f);
 931   }
 932 }
 933 
 934 // Scan only klasses_got cells which should have only Klass*,
 935 // metadata_got cells are scanned only for alive AOT methods
 936 // by AOTCompiledMethod::metadata_do().
 937 void AOTCodeHeap::got_metadata_do(MetadataClosure* f) {
 938   for (int i = 1; i < _klasses_got_size; i++) {
 939     Metadata** p = &_klasses_got[i];
 940     Metadata* md = *p;
 941     if (md == NULL)  continue;  // skip non-oops
 942     if (Metaspace::contains(md)) {
 943       f->do_metadata(md);
 944     } else {
 945       intptr_t meta = (intptr_t)md;
 946       fatal("Invalid value in _klasses_got[%d] = " INTPTR_FORMAT, i, meta);
 947     }
 948   }
 949 }
 950 
 951 void AOTCodeHeap::cleanup_inline_caches() {
 952   for (int index = 0; index < _method_count; index++) {
 953     if (_code_to_aot[index]._state != in_use) {
 954       continue; // Skip uninitialized entries.
 955     }
 956     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 957     aot->cleanup_inline_caches(false);
 958   }
 959 }
 960 
 961 #ifdef ASSERT
 962 int AOTCodeHeap::verify_icholder_relocations() {
 963   int count = 0;
 964   for (int index = 0; index < _method_count; index++) {
 965     if (_code_to_aot[index]._state != in_use) {
 966       continue; // Skip uninitialized entries.
 967     }
 968     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 969     count += aot->verify_icholder_relocations();
 970   }
 971   return count;
 972 }
 973 #endif
 974 
 975 void AOTCodeHeap::metadata_do(MetadataClosure* f) {
 976   for (int index = 0; index < _method_count; index++) {
 977     if (_code_to_aot[index]._state != in_use) {
 978       continue; // Skip uninitialized entries.
 979     }
 980     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 981     if (aot->_is_alive()) {
 982       aot->metadata_do(f);
 983     }
 984   }
 985   // Scan klasses_got cells.
 986   got_metadata_do(f);
 987 }
 988 
 989 bool AOTCodeHeap::reconcile_dynamic_klass(AOTCompiledMethod *caller, InstanceKlass* holder, int index, Klass *dyno_klass, const char *descriptor1, const char *descriptor2) {
 990   const char * const descriptors[2] = {descriptor1, descriptor2};
 991   JavaThread *thread = JavaThread::current();
 992   ResourceMark rm(thread);
 993 
 994   AOTKlassData* holder_data = find_klass(holder);
 995   vmassert(holder_data != NULL, "klass %s not found", holder->signature_name());
 996   vmassert(is_dependent_method(holder, caller), "sanity");
 997 
 998   AOTKlassData* dyno_data = NULL;
 999   bool adapter_failed = false;
1000   char buf[64];
1001   int descriptor_index = 0;
1002   // descriptors[0] specific name ("adapter:<method_id>") for matching
1003   // descriptors[1] fall-back name ("adapter") for depdencies
1004   while (descriptor_index < 2) {
1005     const char *descriptor = descriptors[descriptor_index];
1006     if (descriptor == NULL) {
1007       break;
1008     }
1009     jio_snprintf(buf, sizeof buf, "%s<%d:%d>", descriptor, holder_data->_class_id, index);
1010     dyno_data = find_klass(buf);
1011     if (dyno_data != NULL) {
1012       break;
1013     }
1014     // If match failed then try fall-back for dependencies
1015     ++descriptor_index;
1016     adapter_failed = true;
1017   }
1018 
1019   if (dyno_data == NULL && dyno_klass == NULL) {
1020     // all is well, no (appendix) at compile-time, and still none
1021     return true;
1022   }
1023 
1024   if (dyno_data == NULL) {
1025     // no (appendix) at build-time, but now there is
1026     sweep_dependent_methods(holder_data);
1027     return false;
1028   }
1029 
1030   if (adapter_failed) {
1031     // adapter method mismatch
1032     sweep_dependent_methods(holder_data);
1033     sweep_dependent_methods(dyno_data);
1034     return false;
1035   }
1036 
1037   if (dyno_klass == NULL) {
1038     // (appendix) at build-time, none now
1039     sweep_dependent_methods(holder_data);
1040     sweep_dependent_methods(dyno_data);
1041     return false;
1042   }
1043 
1044   // TODO: support array appendix object
1045   if (!dyno_klass->is_instance_klass()) {
1046     sweep_dependent_methods(holder_data);
1047     sweep_dependent_methods(dyno_data);
1048     return false;
1049   }
1050 
1051   InstanceKlass* dyno = InstanceKlass::cast(dyno_klass);
1052 
1053   if (!dyno->is_unsafe_anonymous()) {
1054     if (_klasses_got[dyno_data->_got_index] != dyno) {
1055       // compile-time class different from runtime class, fail and deoptimize
1056       sweep_dependent_methods(holder_data);
1057       sweep_dependent_methods(dyno_data);
1058       return false;
1059     }
1060 
1061     if (dyno->is_initialized()) {
1062       _klasses_got[dyno_data->_got_index - 1] = dyno;
1063     }
1064     return true;
1065   }
1066 
1067   // TODO: support anonymous supers
1068   if (!dyno->supers_have_passed_fingerprint_checks() || dyno->get_stored_fingerprint() != dyno_data->_fingerprint) {
1069       NOT_PRODUCT( aot_klasses_fp_miss++; )
1070       log_trace(aot, class, fingerprint)("class  %s%s  has bad fingerprint in  %s tid=" INTPTR_FORMAT,
1071           dyno->internal_name(), dyno->is_shared() ? " (shared)" : "",
1072           _lib->name(), p2i(thread));
1073     sweep_dependent_methods(holder_data);
1074     sweep_dependent_methods(dyno_data);
1075     return false;
1076   }
1077 
1078   _klasses_got[dyno_data->_got_index] = dyno;
1079   if (dyno->is_initialized()) {
1080     _klasses_got[dyno_data->_got_index - 1] = dyno;
1081   }
1082 
1083   // TODO: hook up any AOT code
1084   // load_klass_data(dyno_data, thread);
1085   return true;
1086 }
1087 
1088 bool AOTCodeHeap::reconcile_dynamic_method(AOTCompiledMethod *caller, InstanceKlass* holder, int index, Method *adapter_method) {
1089     InstanceKlass *adapter_klass = adapter_method->method_holder();
1090     char buf[64];
1091     jio_snprintf(buf, sizeof buf, "adapter:%d", adapter_method->method_idnum());
1092     if (!reconcile_dynamic_klass(caller, holder, index, adapter_klass, buf, "adapter")) {
1093       return false;
1094     }
1095     return true;
1096 }
1097 
1098 bool AOTCodeHeap::reconcile_dynamic_invoke(AOTCompiledMethod* caller, InstanceKlass* holder, int index, Method* adapter_method, Klass *appendix_klass) {
1099     if (!reconcile_dynamic_klass(caller, holder, index, appendix_klass, "appendix")) {
1100       return false;
1101     }
1102 
1103     if (!reconcile_dynamic_method(caller, holder, index, adapter_method)) {
1104       return false;
1105     }
1106 
1107     return true;
1108 }