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