1 /* 2 * Copyright (c) 1997, 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 25 #include "precompiled.hpp" 26 #include "aot/aotLoader.hpp" 27 #include "code/codeBlob.hpp" 28 #include "code/codeCache.hpp" 29 #include "code/codeHeapState.hpp" 30 #include "code/compiledIC.hpp" 31 #include "code/dependencies.hpp" 32 #include "code/dependencyContext.hpp" 33 #include "code/icBuffer.hpp" 34 #include "code/nmethod.hpp" 35 #include "code/pcDesc.hpp" 36 #include "compiler/compileBroker.hpp" 37 #include "jfr/jfrEvents.hpp" 38 #include "logging/log.hpp" 39 #include "logging/logStream.hpp" 40 #include "memory/allocation.inline.hpp" 41 #include "memory/iterator.hpp" 42 #include "memory/resourceArea.hpp" 43 #include "oops/method.inline.hpp" 44 #include "oops/objArrayOop.hpp" 45 #include "oops/oop.inline.hpp" 46 #include "oops/verifyOopClosure.hpp" 47 #include "runtime/arguments.hpp" 48 #include "runtime/compilationPolicy.hpp" 49 #include "runtime/deoptimization.hpp" 50 #include "runtime/handles.inline.hpp" 51 #include "runtime/icache.hpp" 52 #include "runtime/java.hpp" 53 #include "runtime/mutexLocker.hpp" 54 #include "runtime/safepointVerifiers.hpp" 55 #include "runtime/sweeper.hpp" 56 #include "runtime/vmThread.hpp" 57 #include "services/memoryService.hpp" 58 #include "utilities/align.hpp" 59 #include "utilities/vmError.hpp" 60 #include "utilities/xmlstream.hpp" 61 #ifdef COMPILER1 62 #include "c1/c1_Compilation.hpp" 63 #include "c1/c1_Compiler.hpp" 64 #endif 65 #ifdef COMPILER2 66 #include "opto/c2compiler.hpp" 67 #include "opto/compile.hpp" 68 #include "opto/node.hpp" 69 #endif 70 71 // Helper class for printing in CodeCache 72 class CodeBlob_sizes { 73 private: 74 int count; 75 int total_size; 76 int header_size; 77 int code_size; 78 int stub_size; 79 int relocation_size; 80 int scopes_oop_size; 81 int scopes_metadata_size; 82 int scopes_data_size; 83 int scopes_pcs_size; 84 85 public: 86 CodeBlob_sizes() { 87 count = 0; 88 total_size = 0; 89 header_size = 0; 90 code_size = 0; 91 stub_size = 0; 92 relocation_size = 0; 93 scopes_oop_size = 0; 94 scopes_metadata_size = 0; 95 scopes_data_size = 0; 96 scopes_pcs_size = 0; 97 } 98 99 int total() { return total_size; } 100 bool is_empty() { return count == 0; } 101 102 void print(const char* title) { 103 tty->print_cr(" #%d %s = %dK (hdr %d%%, loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])", 104 count, 105 title, 106 (int)(total() / K), 107 header_size * 100 / total_size, 108 relocation_size * 100 / total_size, 109 code_size * 100 / total_size, 110 stub_size * 100 / total_size, 111 scopes_oop_size * 100 / total_size, 112 scopes_metadata_size * 100 / total_size, 113 scopes_data_size * 100 / total_size, 114 scopes_pcs_size * 100 / total_size); 115 } 116 117 void add(CodeBlob* cb) { 118 count++; 119 total_size += cb->size(); 120 header_size += cb->header_size(); 121 relocation_size += cb->relocation_size(); 122 if (cb->is_nmethod()) { 123 nmethod* nm = cb->as_nmethod_or_null(); 124 code_size += nm->insts_size(); 125 stub_size += nm->stub_size(); 126 127 scopes_oop_size += nm->oops_size(); 128 scopes_metadata_size += nm->metadata_size(); 129 scopes_data_size += nm->scopes_data_size(); 130 scopes_pcs_size += nm->scopes_pcs_size(); 131 } else { 132 code_size += cb->code_size(); 133 } 134 } 135 }; 136 137 // Iterate over all CodeHeaps 138 #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap) 139 #define FOR_ALL_NMETHOD_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _nmethod_heaps->begin(); heap != _nmethod_heaps->end(); ++heap) 140 #define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap) 141 142 // Iterate over all CodeBlobs (cb) on the given CodeHeap 143 #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb)) 144 145 address CodeCache::_low_bound = 0; 146 address CodeCache::_high_bound = 0; 147 int CodeCache::_number_of_nmethods_with_dependencies = 0; 148 nmethod* CodeCache::_scavenge_root_nmethods = NULL; 149 ExceptionCache* volatile CodeCache::_exception_cache_purge_list = NULL; 150 151 // Initialize arrays of CodeHeap subsets 152 GrowableArray<CodeHeap*>* CodeCache::_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true); 153 GrowableArray<CodeHeap*>* CodeCache::_compiled_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true); 154 GrowableArray<CodeHeap*>* CodeCache::_nmethod_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true); 155 GrowableArray<CodeHeap*>* CodeCache::_allocable_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true); 156 157 void CodeCache::check_heap_sizes(size_t non_nmethod_size, size_t profiled_size, size_t non_profiled_size, size_t cache_size, bool all_set) { 158 size_t total_size = non_nmethod_size + profiled_size + non_profiled_size; 159 // Prepare error message 160 const char* error = "Invalid code heap sizes"; 161 err_msg message("NonNMethodCodeHeapSize (" SIZE_FORMAT "K) + ProfiledCodeHeapSize (" SIZE_FORMAT "K)" 162 " + NonProfiledCodeHeapSize (" SIZE_FORMAT "K) = " SIZE_FORMAT "K", 163 non_nmethod_size/K, profiled_size/K, non_profiled_size/K, total_size/K); 164 165 if (total_size > cache_size) { 166 // Some code heap sizes were explicitly set: total_size must be <= cache_size 167 message.append(" is greater than ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K); 168 vm_exit_during_initialization(error, message); 169 } else if (all_set && total_size != cache_size) { 170 // All code heap sizes were explicitly set: total_size must equal cache_size 171 message.append(" is not equal to ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K); 172 vm_exit_during_initialization(error, message); 173 } 174 } 175 176 void CodeCache::initialize_heaps() { 177 bool non_nmethod_set = FLAG_IS_CMDLINE(NonNMethodCodeHeapSize); 178 bool profiled_set = FLAG_IS_CMDLINE(ProfiledCodeHeapSize); 179 bool non_profiled_set = FLAG_IS_CMDLINE(NonProfiledCodeHeapSize); 180 size_t min_size = os::vm_page_size(); 181 size_t cache_size = ReservedCodeCacheSize; 182 size_t non_nmethod_size = NonNMethodCodeHeapSize; 183 size_t profiled_size = ProfiledCodeHeapSize; 184 size_t non_profiled_size = NonProfiledCodeHeapSize; 185 // Check if total size set via command line flags exceeds the reserved size 186 check_heap_sizes((non_nmethod_set ? non_nmethod_size : min_size), 187 (profiled_set ? profiled_size : min_size), 188 (non_profiled_set ? non_profiled_size : min_size), 189 cache_size, 190 non_nmethod_set && profiled_set && non_profiled_set); 191 192 // Determine size of compiler buffers 193 size_t code_buffers_size = 0; 194 #ifdef COMPILER1 195 // C1 temporary code buffers (see Compiler::init_buffer_blob()) 196 const int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple); 197 code_buffers_size += c1_count * Compiler::code_buffer_size(); 198 #endif 199 #ifdef COMPILER2 200 // C2 scratch buffers (see Compile::init_scratch_buffer_blob()) 201 const int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization); 202 // Initial size of constant table (this may be increased if a compiled method needs more space) 203 code_buffers_size += c2_count * C2Compiler::initial_code_buffer_size(); 204 #endif 205 206 // Increase default non_nmethod_size to account for compiler buffers 207 if (!non_nmethod_set) { 208 non_nmethod_size += code_buffers_size; 209 } 210 // Calculate default CodeHeap sizes if not set by user 211 if (!non_nmethod_set && !profiled_set && !non_profiled_set) { 212 // Check if we have enough space for the non-nmethod code heap 213 if (cache_size > non_nmethod_size) { 214 // Use the default value for non_nmethod_size and one half of the 215 // remaining size for non-profiled and one half for profiled methods 216 size_t remaining_size = cache_size - non_nmethod_size; 217 profiled_size = remaining_size / 2; 218 non_profiled_size = remaining_size - profiled_size; 219 } else { 220 // Use all space for the non-nmethod heap and set other heaps to minimal size 221 non_nmethod_size = cache_size - 2 * min_size; 222 profiled_size = min_size; 223 non_profiled_size = min_size; 224 } 225 } else if (!non_nmethod_set || !profiled_set || !non_profiled_set) { 226 // The user explicitly set some code heap sizes. Increase or decrease the (default) 227 // sizes of the other code heaps accordingly. First adapt non-profiled and profiled 228 // code heap sizes and then only change non-nmethod code heap size if still necessary. 229 intx diff_size = cache_size - (non_nmethod_size + profiled_size + non_profiled_size); 230 if (non_profiled_set) { 231 if (!profiled_set) { 232 // Adapt size of profiled code heap 233 if (diff_size < 0 && ((intx)profiled_size + diff_size) <= 0) { 234 // Not enough space available, set to minimum size 235 diff_size += profiled_size - min_size; 236 profiled_size = min_size; 237 } else { 238 profiled_size += diff_size; 239 diff_size = 0; 240 } 241 } 242 } else if (profiled_set) { 243 // Adapt size of non-profiled code heap 244 if (diff_size < 0 && ((intx)non_profiled_size + diff_size) <= 0) { 245 // Not enough space available, set to minimum size 246 diff_size += non_profiled_size - min_size; 247 non_profiled_size = min_size; 248 } else { 249 non_profiled_size += diff_size; 250 diff_size = 0; 251 } 252 } else if (non_nmethod_set) { 253 // Distribute remaining size between profiled and non-profiled code heaps 254 diff_size = cache_size - non_nmethod_size; 255 profiled_size = diff_size / 2; 256 non_profiled_size = diff_size - profiled_size; 257 diff_size = 0; 258 } 259 if (diff_size != 0) { 260 // Use non-nmethod code heap for remaining space requirements 261 assert(!non_nmethod_set && ((intx)non_nmethod_size + diff_size) > 0, "sanity"); 262 non_nmethod_size += diff_size; 263 } 264 } 265 266 // We do not need the profiled CodeHeap, use all space for the non-profiled CodeHeap 267 if (!heap_available(CodeBlobType::MethodProfiled)) { 268 non_profiled_size += profiled_size; 269 profiled_size = 0; 270 } 271 // We do not need the non-profiled CodeHeap, use all space for the non-nmethod CodeHeap 272 if (!heap_available(CodeBlobType::MethodNonProfiled)) { 273 non_nmethod_size += non_profiled_size; 274 non_profiled_size = 0; 275 } 276 // Make sure we have enough space for VM internal code 277 uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3); 278 if (non_nmethod_size < min_code_cache_size) { 279 vm_exit_during_initialization(err_msg( 280 "Not enough space in non-nmethod code heap to run VM: " SIZE_FORMAT "K < " SIZE_FORMAT "K", 281 non_nmethod_size/K, min_code_cache_size/K)); 282 } 283 284 // Verify sizes and update flag values 285 assert(non_profiled_size + profiled_size + non_nmethod_size == cache_size, "Invalid code heap sizes"); 286 FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, non_nmethod_size); 287 FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, profiled_size); 288 FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, non_profiled_size); 289 290 // If large page support is enabled, align code heaps according to large 291 // page size to make sure that code cache is covered by large pages. 292 const size_t alignment = MAX2(page_size(false), (size_t) os::vm_allocation_granularity()); 293 non_nmethod_size = align_up(non_nmethod_size, alignment); 294 profiled_size = align_down(profiled_size, alignment); 295 296 // Reserve one continuous chunk of memory for CodeHeaps and split it into 297 // parts for the individual heaps. The memory layout looks like this: 298 // ---------- high ----------- 299 // Non-profiled nmethods 300 // Profiled nmethods 301 // Non-nmethods 302 // ---------- low ------------ 303 ReservedCodeSpace rs = reserve_heap_memory(cache_size); 304 ReservedSpace non_method_space = rs.first_part(non_nmethod_size); 305 ReservedSpace rest = rs.last_part(non_nmethod_size); 306 ReservedSpace profiled_space = rest.first_part(profiled_size); 307 ReservedSpace non_profiled_space = rest.last_part(profiled_size); 308 309 // Non-nmethods (stubs, adapters, ...) 310 add_heap(non_method_space, "CodeHeap 'non-nmethods'", CodeBlobType::NonNMethod); 311 // Tier 2 and tier 3 (profiled) methods 312 add_heap(profiled_space, "CodeHeap 'profiled nmethods'", CodeBlobType::MethodProfiled); 313 // Tier 1 and tier 4 (non-profiled) methods and native methods 314 add_heap(non_profiled_space, "CodeHeap 'non-profiled nmethods'", CodeBlobType::MethodNonProfiled); 315 } 316 317 size_t CodeCache::page_size(bool aligned) { 318 if (os::can_execute_large_page_memory()) { 319 return aligned ? os::page_size_for_region_aligned(ReservedCodeCacheSize, 8) : 320 os::page_size_for_region_unaligned(ReservedCodeCacheSize, 8); 321 } else { 322 return os::vm_page_size(); 323 } 324 } 325 326 ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) { 327 // Align and reserve space for code cache 328 const size_t rs_ps = page_size(); 329 const size_t rs_align = MAX2(rs_ps, (size_t) os::vm_allocation_granularity()); 330 const size_t rs_size = align_up(size, rs_align); 331 ReservedCodeSpace rs(rs_size, rs_align, rs_ps > (size_t) os::vm_page_size()); 332 if (!rs.is_reserved()) { 333 vm_exit_during_initialization(err_msg("Could not reserve enough space for code cache (" SIZE_FORMAT "K)", 334 rs_size/K)); 335 } 336 337 // Initialize bounds 338 _low_bound = (address)rs.base(); 339 _high_bound = _low_bound + rs.size(); 340 return rs; 341 } 342 343 // Heaps available for allocation 344 bool CodeCache::heap_available(int code_blob_type) { 345 if (!SegmentedCodeCache) { 346 // No segmentation: use a single code heap 347 return (code_blob_type == CodeBlobType::All); 348 } else if (Arguments::is_interpreter_only()) { 349 // Interpreter only: we don't need any method code heaps 350 return (code_blob_type == CodeBlobType::NonNMethod); 351 } else if (TieredCompilation && (TieredStopAtLevel > CompLevel_simple)) { 352 // Tiered compilation: use all code heaps 353 return (code_blob_type < CodeBlobType::All); 354 } else { 355 // No TieredCompilation: we only need the non-nmethod and non-profiled code heap 356 return (code_blob_type == CodeBlobType::NonNMethod) || 357 (code_blob_type == CodeBlobType::MethodNonProfiled); 358 } 359 } 360 361 const char* CodeCache::get_code_heap_flag_name(int code_blob_type) { 362 switch(code_blob_type) { 363 case CodeBlobType::NonNMethod: 364 return "NonNMethodCodeHeapSize"; 365 break; 366 case CodeBlobType::MethodNonProfiled: 367 return "NonProfiledCodeHeapSize"; 368 break; 369 case CodeBlobType::MethodProfiled: 370 return "ProfiledCodeHeapSize"; 371 break; 372 } 373 ShouldNotReachHere(); 374 return NULL; 375 } 376 377 int CodeCache::code_heap_compare(CodeHeap* const &lhs, CodeHeap* const &rhs) { 378 if (lhs->code_blob_type() == rhs->code_blob_type()) { 379 return (lhs > rhs) ? 1 : ((lhs < rhs) ? -1 : 0); 380 } else { 381 return lhs->code_blob_type() - rhs->code_blob_type(); 382 } 383 } 384 385 void CodeCache::add_heap(CodeHeap* heap) { 386 assert(!Universe::is_fully_initialized(), "late heap addition?"); 387 388 _heaps->insert_sorted<code_heap_compare>(heap); 389 390 int type = heap->code_blob_type(); 391 if (code_blob_type_accepts_compiled(type)) { 392 _compiled_heaps->insert_sorted<code_heap_compare>(heap); 393 } 394 if (code_blob_type_accepts_nmethod(type)) { 395 _nmethod_heaps->insert_sorted<code_heap_compare>(heap); 396 } 397 if (code_blob_type_accepts_allocable(type)) { 398 _allocable_heaps->insert_sorted<code_heap_compare>(heap); 399 } 400 } 401 402 void CodeCache::add_heap(ReservedSpace rs, const char* name, int code_blob_type) { 403 // Check if heap is needed 404 if (!heap_available(code_blob_type)) { 405 return; 406 } 407 408 // Create CodeHeap 409 CodeHeap* heap = new CodeHeap(name, code_blob_type); 410 add_heap(heap); 411 412 // Reserve Space 413 size_t size_initial = MIN2((size_t)InitialCodeCacheSize, rs.size()); 414 size_initial = align_up(size_initial, os::vm_page_size()); 415 if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) { 416 vm_exit_during_initialization(err_msg("Could not reserve enough space in %s (" SIZE_FORMAT "K)", 417 heap->name(), size_initial/K)); 418 } 419 420 // Register the CodeHeap 421 MemoryService::add_code_heap_memory_pool(heap, name); 422 } 423 424 CodeHeap* CodeCache::get_code_heap_containing(void* start) { 425 FOR_ALL_HEAPS(heap) { 426 if ((*heap)->contains(start)) { 427 return *heap; 428 } 429 } 430 return NULL; 431 } 432 433 CodeHeap* CodeCache::get_code_heap(const CodeBlob* cb) { 434 assert(cb != NULL, "CodeBlob is null"); 435 FOR_ALL_HEAPS(heap) { 436 if ((*heap)->contains_blob(cb)) { 437 return *heap; 438 } 439 } 440 ShouldNotReachHere(); 441 return NULL; 442 } 443 444 CodeHeap* CodeCache::get_code_heap(int code_blob_type) { 445 FOR_ALL_HEAPS(heap) { 446 if ((*heap)->accepts(code_blob_type)) { 447 return *heap; 448 } 449 } 450 return NULL; 451 } 452 453 CodeBlob* CodeCache::first_blob(CodeHeap* heap) { 454 assert_locked_or_safepoint(CodeCache_lock); 455 assert(heap != NULL, "heap is null"); 456 return (CodeBlob*)heap->first(); 457 } 458 459 CodeBlob* CodeCache::first_blob(int code_blob_type) { 460 if (heap_available(code_blob_type)) { 461 return first_blob(get_code_heap(code_blob_type)); 462 } else { 463 return NULL; 464 } 465 } 466 467 CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) { 468 assert_locked_or_safepoint(CodeCache_lock); 469 assert(heap != NULL, "heap is null"); 470 return (CodeBlob*)heap->next(cb); 471 } 472 473 /** 474 * Do not seize the CodeCache lock here--if the caller has not 475 * already done so, we are going to lose bigtime, since the code 476 * cache will contain a garbage CodeBlob until the caller can 477 * run the constructor for the CodeBlob subclass he is busy 478 * instantiating. 479 */ 480 CodeBlob* CodeCache::allocate(int size, int code_blob_type, int orig_code_blob_type) { 481 // Possibly wakes up the sweeper thread. 482 NMethodSweeper::notify(code_blob_type); 483 assert_locked_or_safepoint(CodeCache_lock); 484 assert(size > 0, "Code cache allocation request must be > 0 but is %d", size); 485 if (size <= 0) { 486 return NULL; 487 } 488 CodeBlob* cb = NULL; 489 490 // Get CodeHeap for the given CodeBlobType 491 CodeHeap* heap = get_code_heap(code_blob_type); 492 assert(heap != NULL, "heap is null"); 493 494 while (true) { 495 cb = (CodeBlob*)heap->allocate(size); 496 if (cb != NULL) break; 497 if (!heap->expand_by(CodeCacheExpansionSize)) { 498 // Save original type for error reporting 499 if (orig_code_blob_type == CodeBlobType::All) { 500 orig_code_blob_type = code_blob_type; 501 } 502 // Expansion failed 503 if (SegmentedCodeCache) { 504 // Fallback solution: Try to store code in another code heap. 505 // NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled) 506 // Note that in the sweeper, we check the reverse_free_ratio of the code heap 507 // and force stack scanning if less than 10% of the code heap are free. 508 int type = code_blob_type; 509 switch (type) { 510 case CodeBlobType::NonNMethod: 511 type = CodeBlobType::MethodNonProfiled; 512 break; 513 case CodeBlobType::MethodNonProfiled: 514 type = CodeBlobType::MethodProfiled; 515 break; 516 case CodeBlobType::MethodProfiled: 517 // Avoid loop if we already tried that code heap 518 if (type == orig_code_blob_type) { 519 type = CodeBlobType::MethodNonProfiled; 520 } 521 break; 522 } 523 if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) { 524 if (PrintCodeCacheExtension) { 525 tty->print_cr("Extension of %s failed. Trying to allocate in %s.", 526 heap->name(), get_code_heap(type)->name()); 527 } 528 return allocate(size, type, orig_code_blob_type); 529 } 530 } 531 MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 532 CompileBroker::handle_full_code_cache(orig_code_blob_type); 533 return NULL; 534 } 535 if (PrintCodeCacheExtension) { 536 ResourceMark rm; 537 if (_nmethod_heaps->length() >= 1) { 538 tty->print("%s", heap->name()); 539 } else { 540 tty->print("CodeCache"); 541 } 542 tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)", 543 (intptr_t)heap->low_boundary(), (intptr_t)heap->high(), 544 (address)heap->high() - (address)heap->low_boundary()); 545 } 546 } 547 print_trace("allocation", cb, size); 548 return cb; 549 } 550 551 void CodeCache::free(CodeBlob* cb) { 552 assert_locked_or_safepoint(CodeCache_lock); 553 CodeHeap* heap = get_code_heap(cb); 554 print_trace("free", cb); 555 if (cb->is_nmethod()) { 556 heap->set_nmethod_count(heap->nmethod_count() - 1); 557 if (((nmethod *)cb)->has_dependencies()) { 558 _number_of_nmethods_with_dependencies--; 559 } 560 } 561 if (cb->is_adapter_blob()) { 562 heap->set_adapter_count(heap->adapter_count() - 1); 563 } 564 565 // Get heap for given CodeBlob and deallocate 566 get_code_heap(cb)->deallocate(cb); 567 568 assert(heap->blob_count() >= 0, "sanity check"); 569 } 570 571 void CodeCache::free_unused_tail(CodeBlob* cb, size_t used) { 572 assert_locked_or_safepoint(CodeCache_lock); 573 guarantee(cb->is_buffer_blob() && strncmp("Interpreter", cb->name(), 11) == 0, "Only possible for interpreter!"); 574 print_trace("free_unused_tail", cb); 575 576 // We also have to account for the extra space (i.e. header) used by the CodeBlob 577 // which provides the memory (see BufferBlob::create() in codeBlob.cpp). 578 used += CodeBlob::align_code_offset(cb->header_size()); 579 580 // Get heap for given CodeBlob and deallocate its unused tail 581 get_code_heap(cb)->deallocate_tail(cb, used); 582 // Adjust the sizes of the CodeBlob 583 cb->adjust_size(used); 584 } 585 586 void CodeCache::commit(CodeBlob* cb) { 587 // this is called by nmethod::nmethod, which must already own CodeCache_lock 588 assert_locked_or_safepoint(CodeCache_lock); 589 CodeHeap* heap = get_code_heap(cb); 590 if (cb->is_nmethod()) { 591 heap->set_nmethod_count(heap->nmethod_count() + 1); 592 if (((nmethod *)cb)->has_dependencies()) { 593 _number_of_nmethods_with_dependencies++; 594 } 595 } 596 if (cb->is_adapter_blob()) { 597 heap->set_adapter_count(heap->adapter_count() + 1); 598 } 599 600 // flush the hardware I-cache 601 ICache::invalidate_range(cb->content_begin(), cb->content_size()); 602 } 603 604 bool CodeCache::contains(void *p) { 605 // S390 uses contains() in current_frame(), which is used before 606 // code cache initialization if NativeMemoryTracking=detail is set. 607 S390_ONLY(if (_heaps == NULL) return false;) 608 // It should be ok to call contains without holding a lock. 609 FOR_ALL_HEAPS(heap) { 610 if ((*heap)->contains(p)) { 611 return true; 612 } 613 } 614 return false; 615 } 616 617 bool CodeCache::contains(nmethod *nm) { 618 return contains((void *)nm); 619 } 620 621 // This method is safe to call without holding the CodeCache_lock, as long as a dead CodeBlob is not 622 // looked up (i.e., one that has been marked for deletion). It only depends on the _segmap to contain 623 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled. 624 CodeBlob* CodeCache::find_blob(void* start) { 625 CodeBlob* result = find_blob_unsafe(start); 626 // We could potentially look up non_entrant methods 627 guarantee(result == NULL || !result->is_zombie() || result->is_locked_by_vm() || VMError::is_error_reported(), "unsafe access to zombie method"); 628 return result; 629 } 630 631 // Lookup that does not fail if you lookup a zombie method (if you call this, be sure to know 632 // what you are doing) 633 CodeBlob* CodeCache::find_blob_unsafe(void* start) { 634 // NMT can walk the stack before code cache is created 635 if (_heaps != NULL) { 636 CodeHeap* heap = get_code_heap_containing(start); 637 if (heap != NULL) { 638 return heap->find_blob_unsafe(start); 639 } 640 } 641 return NULL; 642 } 643 644 nmethod* CodeCache::find_nmethod(void* start) { 645 CodeBlob* cb = find_blob(start); 646 assert(cb->is_nmethod(), "did not find an nmethod"); 647 return (nmethod*)cb; 648 } 649 650 void CodeCache::blobs_do(void f(CodeBlob* nm)) { 651 assert_locked_or_safepoint(CodeCache_lock); 652 FOR_ALL_HEAPS(heap) { 653 FOR_ALL_BLOBS(cb, *heap) { 654 f(cb); 655 } 656 } 657 } 658 659 void CodeCache::nmethods_do(void f(nmethod* nm)) { 660 assert_locked_or_safepoint(CodeCache_lock); 661 NMethodIterator iter; 662 while(iter.next()) { 663 f(iter.method()); 664 } 665 } 666 667 void CodeCache::metadata_do(void f(Metadata* m)) { 668 assert_locked_or_safepoint(CodeCache_lock); 669 NMethodIterator iter; 670 while(iter.next_alive()) { 671 iter.method()->metadata_do(f); 672 } 673 AOTLoader::metadata_do(f); 674 } 675 676 int CodeCache::alignment_unit() { 677 return (int)_heaps->first()->alignment_unit(); 678 } 679 680 int CodeCache::alignment_offset() { 681 return (int)_heaps->first()->alignment_offset(); 682 } 683 684 // Mark nmethods for unloading if they contain otherwise unreachable oops. 685 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) { 686 assert_locked_or_safepoint(CodeCache_lock); 687 UnloadingScope scope(is_alive); 688 CompiledMethodIterator iter; 689 while(iter.next_alive()) { 690 iter.method()->do_unloading(unloading_occurred); 691 } 692 } 693 694 void CodeCache::blobs_do(CodeBlobClosure* f) { 695 assert_locked_or_safepoint(CodeCache_lock); 696 FOR_ALL_ALLOCABLE_HEAPS(heap) { 697 FOR_ALL_BLOBS(cb, *heap) { 698 if (cb->is_alive()) { 699 f->do_code_blob(cb); 700 #ifdef ASSERT 701 if (cb->is_nmethod()) { 702 Universe::heap()->verify_nmethod((nmethod*)cb); 703 } 704 #endif //ASSERT 705 } 706 } 707 } 708 } 709 710 // Walk the list of methods which might contain oops to the java heap. 711 void CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure* f) { 712 assert_locked_or_safepoint(CodeCache_lock); 713 714 const bool fix_relocations = f->fix_relocations(); 715 debug_only(mark_scavenge_root_nmethods()); 716 717 nmethod* prev = NULL; 718 nmethod* cur = scavenge_root_nmethods(); 719 while (cur != NULL) { 720 debug_only(cur->clear_scavenge_root_marked()); 721 assert(cur->scavenge_root_not_marked(), ""); 722 assert(cur->on_scavenge_root_list(), "else shouldn't be on this list"); 723 724 bool is_live = (!cur->is_zombie() && !cur->is_unloaded()); 725 LogTarget(Trace, gc, nmethod) lt; 726 if (lt.is_enabled()) { 727 LogStream ls(lt); 728 CompileTask::print(&ls, cur, 729 is_live ? "scavenge root " : "dead scavenge root", /*short_form:*/ true); 730 } 731 if (is_live) { 732 // Perform cur->oops_do(f), maybe just once per nmethod. 733 f->do_code_blob(cur); 734 } 735 nmethod* const next = cur->scavenge_root_link(); 736 // The scavengable nmethod list must contain all methods with scavengable 737 // oops. It is safe to include more nmethod on the list, but we do not 738 // expect any live non-scavengable nmethods on the list. 739 if (fix_relocations) { 740 if (!is_live || !cur->detect_scavenge_root_oops()) { 741 unlink_scavenge_root_nmethod(cur, prev); 742 } else { 743 prev = cur; 744 } 745 } 746 cur = next; 747 } 748 749 // Check for stray marks. 750 debug_only(verify_perm_nmethods(NULL)); 751 } 752 753 void CodeCache::register_scavenge_root_nmethod(nmethod* nm) { 754 assert_locked_or_safepoint(CodeCache_lock); 755 if (!nm->on_scavenge_root_list() && nm->detect_scavenge_root_oops()) { 756 add_scavenge_root_nmethod(nm); 757 } 758 } 759 760 void CodeCache::verify_scavenge_root_nmethod(nmethod* nm) { 761 nm->verify_scavenge_root_oops(); 762 } 763 764 void CodeCache::add_scavenge_root_nmethod(nmethod* nm) { 765 assert_locked_or_safepoint(CodeCache_lock); 766 767 nm->set_on_scavenge_root_list(); 768 nm->set_scavenge_root_link(_scavenge_root_nmethods); 769 set_scavenge_root_nmethods(nm); 770 print_trace("add_scavenge_root", nm); 771 } 772 773 void CodeCache::unlink_scavenge_root_nmethod(nmethod* nm, nmethod* prev) { 774 assert_locked_or_safepoint(CodeCache_lock); 775 776 assert((prev == NULL && scavenge_root_nmethods() == nm) || 777 (prev != NULL && prev->scavenge_root_link() == nm), "precondition"); 778 779 print_trace("unlink_scavenge_root", nm); 780 if (prev == NULL) { 781 set_scavenge_root_nmethods(nm->scavenge_root_link()); 782 } else { 783 prev->set_scavenge_root_link(nm->scavenge_root_link()); 784 } 785 nm->set_scavenge_root_link(NULL); 786 nm->clear_on_scavenge_root_list(); 787 } 788 789 void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) { 790 assert_locked_or_safepoint(CodeCache_lock); 791 792 print_trace("drop_scavenge_root", nm); 793 nmethod* prev = NULL; 794 for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) { 795 if (cur == nm) { 796 unlink_scavenge_root_nmethod(cur, prev); 797 return; 798 } 799 prev = cur; 800 } 801 assert(false, "should have been on list"); 802 } 803 804 void CodeCache::prune_scavenge_root_nmethods() { 805 assert_locked_or_safepoint(CodeCache_lock); 806 807 debug_only(mark_scavenge_root_nmethods()); 808 809 nmethod* last = NULL; 810 nmethod* cur = scavenge_root_nmethods(); 811 while (cur != NULL) { 812 nmethod* next = cur->scavenge_root_link(); 813 debug_only(cur->clear_scavenge_root_marked()); 814 assert(cur->scavenge_root_not_marked(), ""); 815 assert(cur->on_scavenge_root_list(), "else shouldn't be on this list"); 816 817 if (!cur->is_zombie() && !cur->is_unloaded() 818 && cur->detect_scavenge_root_oops()) { 819 // Keep it. Advance 'last' to prevent deletion. 820 last = cur; 821 } else { 822 // Prune it from the list, so we don't have to look at it any more. 823 print_trace("prune_scavenge_root", cur); 824 unlink_scavenge_root_nmethod(cur, last); 825 } 826 cur = next; 827 } 828 829 // Check for stray marks. 830 debug_only(verify_perm_nmethods(NULL)); 831 } 832 833 #ifndef PRODUCT 834 void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) { 835 // While we are here, verify the integrity of the list. 836 mark_scavenge_root_nmethods(); 837 for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) { 838 assert(cur->on_scavenge_root_list(), "else shouldn't be on this list"); 839 cur->clear_scavenge_root_marked(); 840 } 841 verify_perm_nmethods(f); 842 } 843 844 // Temporarily mark nmethods that are claimed to be on the scavenge list. 845 void CodeCache::mark_scavenge_root_nmethods() { 846 NMethodIterator iter; 847 while(iter.next_alive()) { 848 nmethod* nm = iter.method(); 849 assert(nm->scavenge_root_not_marked(), "clean state"); 850 if (nm->on_scavenge_root_list()) 851 nm->set_scavenge_root_marked(); 852 } 853 } 854 855 // If the closure is given, run it on the unlisted nmethods. 856 // Also make sure that the effects of mark_scavenge_root_nmethods is gone. 857 void CodeCache::verify_perm_nmethods(CodeBlobClosure* f_or_null) { 858 NMethodIterator iter; 859 while(iter.next_alive()) { 860 nmethod* nm = iter.method(); 861 bool call_f = (f_or_null != NULL); 862 assert(nm->scavenge_root_not_marked(), "must be already processed"); 863 if (nm->on_scavenge_root_list()) 864 call_f = false; // don't show this one to the client 865 Universe::heap()->verify_nmethod(nm); 866 if (call_f) f_or_null->do_code_blob(nm); 867 } 868 } 869 #endif //PRODUCT 870 871 void CodeCache::verify_clean_inline_caches() { 872 #ifdef ASSERT 873 NMethodIterator iter; 874 while(iter.next_alive()) { 875 nmethod* nm = iter.method(); 876 assert(!nm->is_unloaded(), "Tautology"); 877 nm->verify_clean_inline_caches(); 878 nm->verify(); 879 } 880 #endif 881 } 882 883 void CodeCache::verify_icholder_relocations() { 884 #ifdef ASSERT 885 // make sure that we aren't leaking icholders 886 int count = 0; 887 FOR_ALL_HEAPS(heap) { 888 FOR_ALL_BLOBS(cb, *heap) { 889 CompiledMethod *nm = cb->as_compiled_method_or_null(); 890 if (nm != NULL) { 891 count += nm->verify_icholder_relocations(); 892 } 893 } 894 } 895 assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() == 896 CompiledICHolder::live_count(), "must agree"); 897 #endif 898 } 899 900 // Defer freeing of concurrently cleaned ExceptionCache entries until 901 // after a global handshake operation. 902 void CodeCache::release_exception_cache(ExceptionCache* entry) { 903 if (SafepointSynchronize::is_at_safepoint()) { 904 delete entry; 905 } else { 906 for (;;) { 907 ExceptionCache* purge_list_head = Atomic::load(&_exception_cache_purge_list); 908 entry->set_purge_list_next(purge_list_head); 909 if (Atomic::cmpxchg(entry, &_exception_cache_purge_list, purge_list_head) == purge_list_head) { 910 break; 911 } 912 } 913 } 914 } 915 916 // Delete exception caches that have been concurrently unlinked, 917 // followed by a global handshake operation. 918 void CodeCache::purge_exception_caches() { 919 ExceptionCache* curr = _exception_cache_purge_list; 920 while (curr != NULL) { 921 ExceptionCache* next = curr->purge_list_next(); 922 delete curr; 923 curr = next; 924 } 925 _exception_cache_purge_list = NULL; 926 } 927 928 void CodeCache::gc_prologue() { } 929 930 void CodeCache::gc_epilogue() { 931 prune_scavenge_root_nmethods(); 932 } 933 934 uint8_t CodeCache::_unloading_cycle = 1; 935 936 void CodeCache::increment_unloading_cycle() { 937 if (_unloading_cycle == 1) { 938 _unloading_cycle = 2; 939 } else { 940 _unloading_cycle = 1; 941 } 942 } 943 944 CodeCache::UnloadingScope::UnloadingScope(BoolObjectClosure* is_alive) 945 : _is_unloading_behaviour(is_alive) 946 { 947 IsUnloadingBehaviour::set_current(&_is_unloading_behaviour); 948 increment_unloading_cycle(); 949 DependencyContext::gc_prologue(); 950 } 951 952 CodeCache::UnloadingScope::~UnloadingScope() { 953 IsUnloadingBehaviour::set_current(NULL); 954 DependencyContext::gc_epilogue(); 955 } 956 957 void CodeCache::verify_oops() { 958 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 959 VerifyOopClosure voc; 960 NMethodIterator iter; 961 while(iter.next_alive()) { 962 nmethod* nm = iter.method(); 963 nm->oops_do(&voc); 964 nm->verify_oop_relocations(); 965 } 966 } 967 968 int CodeCache::blob_count(int code_blob_type) { 969 CodeHeap* heap = get_code_heap(code_blob_type); 970 return (heap != NULL) ? heap->blob_count() : 0; 971 } 972 973 int CodeCache::blob_count() { 974 int count = 0; 975 FOR_ALL_HEAPS(heap) { 976 count += (*heap)->blob_count(); 977 } 978 return count; 979 } 980 981 int CodeCache::nmethod_count(int code_blob_type) { 982 CodeHeap* heap = get_code_heap(code_blob_type); 983 return (heap != NULL) ? heap->nmethod_count() : 0; 984 } 985 986 int CodeCache::nmethod_count() { 987 int count = 0; 988 FOR_ALL_NMETHOD_HEAPS(heap) { 989 count += (*heap)->nmethod_count(); 990 } 991 return count; 992 } 993 994 int CodeCache::adapter_count(int code_blob_type) { 995 CodeHeap* heap = get_code_heap(code_blob_type); 996 return (heap != NULL) ? heap->adapter_count() : 0; 997 } 998 999 int CodeCache::adapter_count() { 1000 int count = 0; 1001 FOR_ALL_HEAPS(heap) { 1002 count += (*heap)->adapter_count(); 1003 } 1004 return count; 1005 } 1006 1007 address CodeCache::low_bound(int code_blob_type) { 1008 CodeHeap* heap = get_code_heap(code_blob_type); 1009 return (heap != NULL) ? (address)heap->low_boundary() : NULL; 1010 } 1011 1012 address CodeCache::high_bound(int code_blob_type) { 1013 CodeHeap* heap = get_code_heap(code_blob_type); 1014 return (heap != NULL) ? (address)heap->high_boundary() : NULL; 1015 } 1016 1017 size_t CodeCache::capacity() { 1018 size_t cap = 0; 1019 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1020 cap += (*heap)->capacity(); 1021 } 1022 return cap; 1023 } 1024 1025 size_t CodeCache::unallocated_capacity(int code_blob_type) { 1026 CodeHeap* heap = get_code_heap(code_blob_type); 1027 return (heap != NULL) ? heap->unallocated_capacity() : 0; 1028 } 1029 1030 size_t CodeCache::unallocated_capacity() { 1031 size_t unallocated_cap = 0; 1032 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1033 unallocated_cap += (*heap)->unallocated_capacity(); 1034 } 1035 return unallocated_cap; 1036 } 1037 1038 size_t CodeCache::max_capacity() { 1039 size_t max_cap = 0; 1040 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1041 max_cap += (*heap)->max_capacity(); 1042 } 1043 return max_cap; 1044 } 1045 1046 /** 1047 * Returns the reverse free ratio. E.g., if 25% (1/4) of the code heap 1048 * is free, reverse_free_ratio() returns 4. 1049 */ 1050 double CodeCache::reverse_free_ratio(int code_blob_type) { 1051 CodeHeap* heap = get_code_heap(code_blob_type); 1052 if (heap == NULL) { 1053 return 0; 1054 } 1055 1056 double unallocated_capacity = MAX2((double)heap->unallocated_capacity(), 1.0); // Avoid division by 0; 1057 double max_capacity = (double)heap->max_capacity(); 1058 double result = max_capacity / unallocated_capacity; 1059 assert (max_capacity >= unallocated_capacity, "Must be"); 1060 assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result); 1061 return result; 1062 } 1063 1064 size_t CodeCache::bytes_allocated_in_freelists() { 1065 size_t allocated_bytes = 0; 1066 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1067 allocated_bytes += (*heap)->allocated_in_freelist(); 1068 } 1069 return allocated_bytes; 1070 } 1071 1072 int CodeCache::allocated_segments() { 1073 int number_of_segments = 0; 1074 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1075 number_of_segments += (*heap)->allocated_segments(); 1076 } 1077 return number_of_segments; 1078 } 1079 1080 size_t CodeCache::freelists_length() { 1081 size_t length = 0; 1082 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1083 length += (*heap)->freelist_length(); 1084 } 1085 return length; 1086 } 1087 1088 void icache_init(); 1089 1090 void CodeCache::initialize() { 1091 assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points"); 1092 #ifdef COMPILER2 1093 assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment, "CodeCacheSegmentSize must be large enough to align inner loops"); 1094 #endif 1095 assert(CodeCacheSegmentSize >= sizeof(jdouble), "CodeCacheSegmentSize must be large enough to align constants"); 1096 // This was originally just a check of the alignment, causing failure, instead, round 1097 // the code cache to the page size. In particular, Solaris is moving to a larger 1098 // default page size. 1099 CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size()); 1100 1101 if (SegmentedCodeCache) { 1102 // Use multiple code heaps 1103 initialize_heaps(); 1104 } else { 1105 // Use a single code heap 1106 FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, 0); 1107 FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, 0); 1108 FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, 0); 1109 ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize); 1110 add_heap(rs, "CodeCache", CodeBlobType::All); 1111 } 1112 1113 // Initialize ICache flush mechanism 1114 // This service is needed for os::register_code_area 1115 icache_init(); 1116 1117 // Give OS a chance to register generated code area. 1118 // This is used on Windows 64 bit platforms to register 1119 // Structured Exception Handlers for our generated code. 1120 os::register_code_area((char*)low_bound(), (char*)high_bound()); 1121 } 1122 1123 void codeCache_init() { 1124 CodeCache::initialize(); 1125 // Load AOT libraries and add AOT code heaps. 1126 AOTLoader::initialize(); 1127 } 1128 1129 //------------------------------------------------------------------------------------------------ 1130 1131 int CodeCache::number_of_nmethods_with_dependencies() { 1132 return _number_of_nmethods_with_dependencies; 1133 } 1134 1135 void CodeCache::clear_inline_caches() { 1136 assert_locked_or_safepoint(CodeCache_lock); 1137 CompiledMethodIterator iter; 1138 while(iter.next_alive()) { 1139 iter.method()->clear_inline_caches(); 1140 } 1141 } 1142 1143 void CodeCache::cleanup_inline_caches() { 1144 assert_locked_or_safepoint(CodeCache_lock); 1145 NMethodIterator iter; 1146 while(iter.next_alive()) { 1147 iter.method()->cleanup_inline_caches(/*clean_all=*/true); 1148 } 1149 } 1150 1151 // Keeps track of time spent for checking dependencies 1152 NOT_PRODUCT(static elapsedTimer dependentCheckTime;) 1153 1154 int CodeCache::mark_for_deoptimization(KlassDepChange& changes) { 1155 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1156 int number_of_marked_CodeBlobs = 0; 1157 1158 // search the hierarchy looking for nmethods which are affected by the loading of this class 1159 1160 // then search the interfaces this class implements looking for nmethods 1161 // which might be dependent of the fact that an interface only had one 1162 // implementor. 1163 // nmethod::check_all_dependencies works only correctly, if no safepoint 1164 // can happen 1165 NoSafepointVerifier nsv; 1166 for (DepChange::ContextStream str(changes, nsv); str.next(); ) { 1167 Klass* d = str.klass(); 1168 number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes); 1169 } 1170 1171 #ifndef PRODUCT 1172 if (VerifyDependencies) { 1173 // Object pointers are used as unique identifiers for dependency arguments. This 1174 // is only possible if no safepoint, i.e., GC occurs during the verification code. 1175 dependentCheckTime.start(); 1176 nmethod::check_all_dependencies(changes); 1177 dependentCheckTime.stop(); 1178 } 1179 #endif 1180 1181 return number_of_marked_CodeBlobs; 1182 } 1183 1184 CompiledMethod* CodeCache::find_compiled(void* start) { 1185 CodeBlob *cb = find_blob(start); 1186 assert(cb == NULL || cb->is_compiled(), "did not find an compiled_method"); 1187 return (CompiledMethod*)cb; 1188 } 1189 1190 bool CodeCache::is_far_target(address target) { 1191 #if INCLUDE_AOT 1192 return NativeCall::is_far_call(_low_bound, target) || 1193 NativeCall::is_far_call(_high_bound, target); 1194 #else 1195 return false; 1196 #endif 1197 } 1198 1199 #ifdef HOTSWAP 1200 int CodeCache::mark_for_evol_deoptimization(InstanceKlass* dependee) { 1201 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1202 int number_of_marked_CodeBlobs = 0; 1203 1204 // Deoptimize all methods of the evolving class itself 1205 Array<Method*>* old_methods = dependee->methods(); 1206 for (int i = 0; i < old_methods->length(); i++) { 1207 ResourceMark rm; 1208 Method* old_method = old_methods->at(i); 1209 CompiledMethod* nm = old_method->code(); 1210 if (nm != NULL) { 1211 nm->mark_for_deoptimization(); 1212 number_of_marked_CodeBlobs++; 1213 } 1214 } 1215 1216 CompiledMethodIterator iter; 1217 while(iter.next_alive()) { 1218 CompiledMethod* nm = iter.method(); 1219 if (nm->is_marked_for_deoptimization()) { 1220 // ...Already marked in the previous pass; don't count it again. 1221 } else if (nm->is_evol_dependent_on(dependee)) { 1222 ResourceMark rm; 1223 nm->mark_for_deoptimization(); 1224 number_of_marked_CodeBlobs++; 1225 } else { 1226 // flush caches in case they refer to a redefined Method* 1227 nm->clear_inline_caches(); 1228 } 1229 } 1230 1231 return number_of_marked_CodeBlobs; 1232 } 1233 #endif // HOTSWAP 1234 1235 1236 // Deoptimize all methods 1237 void CodeCache::mark_all_nmethods_for_deoptimization() { 1238 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1239 CompiledMethodIterator iter; 1240 while(iter.next_alive()) { 1241 CompiledMethod* nm = iter.method(); 1242 if (!nm->method()->is_method_handle_intrinsic()) { 1243 nm->mark_for_deoptimization(); 1244 } 1245 } 1246 } 1247 1248 int CodeCache::mark_for_deoptimization(Method* dependee) { 1249 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1250 int number_of_marked_CodeBlobs = 0; 1251 1252 CompiledMethodIterator iter; 1253 while(iter.next_alive()) { 1254 CompiledMethod* nm = iter.method(); 1255 if (nm->is_dependent_on_method(dependee)) { 1256 ResourceMark rm; 1257 nm->mark_for_deoptimization(); 1258 number_of_marked_CodeBlobs++; 1259 } 1260 } 1261 1262 return number_of_marked_CodeBlobs; 1263 } 1264 1265 void CodeCache::make_marked_nmethods_not_entrant() { 1266 assert_locked_or_safepoint(CodeCache_lock); 1267 CompiledMethodIterator iter; 1268 while(iter.next_alive()) { 1269 CompiledMethod* nm = iter.method(); 1270 if (nm->is_marked_for_deoptimization() && !nm->is_not_entrant()) { 1271 nm->make_not_entrant(); 1272 } 1273 } 1274 } 1275 1276 // Flushes compiled methods dependent on dependee. 1277 void CodeCache::flush_dependents_on(InstanceKlass* dependee) { 1278 assert_lock_strong(Compile_lock); 1279 1280 if (number_of_nmethods_with_dependencies() == 0) return; 1281 1282 // CodeCache can only be updated by a thread_in_VM and they will all be 1283 // stopped during the safepoint so CodeCache will be safe to update without 1284 // holding the CodeCache_lock. 1285 1286 KlassDepChange changes(dependee); 1287 1288 // Compute the dependent nmethods 1289 if (mark_for_deoptimization(changes) > 0) { 1290 // At least one nmethod has been marked for deoptimization 1291 VM_Deoptimize op; 1292 VMThread::execute(&op); 1293 } 1294 } 1295 1296 #ifdef HOTSWAP 1297 // Flushes compiled methods dependent on dependee in the evolutionary sense 1298 void CodeCache::flush_evol_dependents_on(InstanceKlass* ev_k) { 1299 // --- Compile_lock is not held. However we are at a safepoint. 1300 assert_locked_or_safepoint(Compile_lock); 1301 if (number_of_nmethods_with_dependencies() == 0 && !UseAOT) return; 1302 1303 // CodeCache can only be updated by a thread_in_VM and they will all be 1304 // stopped during the safepoint so CodeCache will be safe to update without 1305 // holding the CodeCache_lock. 1306 1307 // Compute the dependent nmethods 1308 if (mark_for_evol_deoptimization(ev_k) > 0) { 1309 // At least one nmethod has been marked for deoptimization 1310 1311 // All this already happens inside a VM_Operation, so we'll do all the work here. 1312 // Stuff copied from VM_Deoptimize and modified slightly. 1313 1314 // We do not want any GCs to happen while we are in the middle of this VM operation 1315 ResourceMark rm; 1316 DeoptimizationMarker dm; 1317 1318 // Deoptimize all activations depending on marked nmethods 1319 Deoptimization::deoptimize_dependents(); 1320 1321 // Make the dependent methods not entrant 1322 make_marked_nmethods_not_entrant(); 1323 } 1324 } 1325 #endif // HOTSWAP 1326 1327 1328 // Flushes compiled methods dependent on dependee 1329 void CodeCache::flush_dependents_on_method(const methodHandle& m_h) { 1330 // --- Compile_lock is not held. However we are at a safepoint. 1331 assert_locked_or_safepoint(Compile_lock); 1332 1333 // CodeCache can only be updated by a thread_in_VM and they will all be 1334 // stopped dring the safepoint so CodeCache will be safe to update without 1335 // holding the CodeCache_lock. 1336 1337 // Compute the dependent nmethods 1338 if (mark_for_deoptimization(m_h()) > 0) { 1339 // At least one nmethod has been marked for deoptimization 1340 1341 // All this already happens inside a VM_Operation, so we'll do all the work here. 1342 // Stuff copied from VM_Deoptimize and modified slightly. 1343 1344 // We do not want any GCs to happen while we are in the middle of this VM operation 1345 ResourceMark rm; 1346 DeoptimizationMarker dm; 1347 1348 // Deoptimize all activations depending on marked nmethods 1349 Deoptimization::deoptimize_dependents(); 1350 1351 // Make the dependent methods not entrant 1352 make_marked_nmethods_not_entrant(); 1353 } 1354 } 1355 1356 void CodeCache::verify() { 1357 assert_locked_or_safepoint(CodeCache_lock); 1358 FOR_ALL_HEAPS(heap) { 1359 (*heap)->verify(); 1360 FOR_ALL_BLOBS(cb, *heap) { 1361 if (cb->is_alive()) { 1362 cb->verify(); 1363 } 1364 } 1365 } 1366 } 1367 1368 // A CodeHeap is full. Print out warning and report event. 1369 PRAGMA_DIAG_PUSH 1370 PRAGMA_FORMAT_NONLITERAL_IGNORED 1371 void CodeCache::report_codemem_full(int code_blob_type, bool print) { 1372 // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event 1373 CodeHeap* heap = get_code_heap(code_blob_type); 1374 assert(heap != NULL, "heap is null"); 1375 1376 if ((heap->full_count() == 0) || print) { 1377 // Not yet reported for this heap, report 1378 if (SegmentedCodeCache) { 1379 ResourceMark rm; 1380 stringStream msg1_stream, msg2_stream; 1381 msg1_stream.print("%s is full. Compiler has been disabled.", 1382 get_code_heap_name(code_blob_type)); 1383 msg2_stream.print("Try increasing the code heap size using -XX:%s=", 1384 get_code_heap_flag_name(code_blob_type)); 1385 const char *msg1 = msg1_stream.as_string(); 1386 const char *msg2 = msg2_stream.as_string(); 1387 1388 log_warning(codecache)("%s", msg1); 1389 log_warning(codecache)("%s", msg2); 1390 warning("%s", msg1); 1391 warning("%s", msg2); 1392 } else { 1393 const char *msg1 = "CodeCache is full. Compiler has been disabled."; 1394 const char *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize="; 1395 1396 log_warning(codecache)("%s", msg1); 1397 log_warning(codecache)("%s", msg2); 1398 warning("%s", msg1); 1399 warning("%s", msg2); 1400 } 1401 ResourceMark rm; 1402 stringStream s; 1403 // Dump code cache into a buffer before locking the tty. 1404 { 1405 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1406 print_summary(&s); 1407 } 1408 { 1409 ttyLocker ttyl; 1410 tty->print("%s", s.as_string()); 1411 } 1412 1413 if (heap->full_count() == 0) { 1414 LogTarget(Debug, codecache) lt; 1415 if (lt.is_enabled()) { 1416 CompileBroker::print_heapinfo(tty, "all", "4096"); // details, may be a lot! 1417 } 1418 } 1419 } 1420 1421 heap->report_full(); 1422 1423 EventCodeCacheFull event; 1424 if (event.should_commit()) { 1425 event.set_codeBlobType((u1)code_blob_type); 1426 event.set_startAddress((u8)heap->low_boundary()); 1427 event.set_commitedTopAddress((u8)heap->high()); 1428 event.set_reservedTopAddress((u8)heap->high_boundary()); 1429 event.set_entryCount(heap->blob_count()); 1430 event.set_methodCount(heap->nmethod_count()); 1431 event.set_adaptorCount(heap->adapter_count()); 1432 event.set_unallocatedCapacity(heap->unallocated_capacity()); 1433 event.set_fullCount(heap->full_count()); 1434 event.commit(); 1435 } 1436 } 1437 PRAGMA_DIAG_POP 1438 1439 void CodeCache::print_memory_overhead() { 1440 size_t wasted_bytes = 0; 1441 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1442 CodeHeap* curr_heap = *heap; 1443 for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) { 1444 HeapBlock* heap_block = ((HeapBlock*)cb) - 1; 1445 wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size(); 1446 } 1447 } 1448 // Print bytes that are allocated in the freelist 1449 ttyLocker ttl; 1450 tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT, freelists_length()); 1451 tty->print_cr("Allocated in freelist: " SSIZE_FORMAT "kB", bytes_allocated_in_freelists()/K); 1452 tty->print_cr("Unused bytes in CodeBlobs: " SSIZE_FORMAT "kB", (wasted_bytes/K)); 1453 tty->print_cr("Segment map size: " SSIZE_FORMAT "kB", allocated_segments()/K); // 1 byte per segment 1454 } 1455 1456 //------------------------------------------------------------------------------------------------ 1457 // Non-product version 1458 1459 #ifndef PRODUCT 1460 1461 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) { 1462 if (PrintCodeCache2) { // Need to add a new flag 1463 ResourceMark rm; 1464 if (size == 0) size = cb->size(); 1465 tty->print_cr("CodeCache %s: addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size); 1466 } 1467 } 1468 1469 void CodeCache::print_internals() { 1470 int nmethodCount = 0; 1471 int runtimeStubCount = 0; 1472 int adapterCount = 0; 1473 int deoptimizationStubCount = 0; 1474 int uncommonTrapStubCount = 0; 1475 int bufferBlobCount = 0; 1476 int total = 0; 1477 int nmethodAlive = 0; 1478 int nmethodNotEntrant = 0; 1479 int nmethodZombie = 0; 1480 int nmethodUnloaded = 0; 1481 int nmethodJava = 0; 1482 int nmethodNative = 0; 1483 int max_nm_size = 0; 1484 ResourceMark rm; 1485 1486 int i = 0; 1487 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1488 if ((_nmethod_heaps->length() >= 1) && Verbose) { 1489 tty->print_cr("-- %s --", (*heap)->name()); 1490 } 1491 FOR_ALL_BLOBS(cb, *heap) { 1492 total++; 1493 if (cb->is_nmethod()) { 1494 nmethod* nm = (nmethod*)cb; 1495 1496 if (Verbose && nm->method() != NULL) { 1497 ResourceMark rm; 1498 char *method_name = nm->method()->name_and_sig_as_C_string(); 1499 tty->print("%s", method_name); 1500 if(nm->is_alive()) { tty->print_cr(" alive"); } 1501 if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); } 1502 if(nm->is_zombie()) { tty->print_cr(" zombie"); } 1503 } 1504 1505 nmethodCount++; 1506 1507 if(nm->is_alive()) { nmethodAlive++; } 1508 if(nm->is_not_entrant()) { nmethodNotEntrant++; } 1509 if(nm->is_zombie()) { nmethodZombie++; } 1510 if(nm->is_unloaded()) { nmethodUnloaded++; } 1511 if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; } 1512 1513 if(nm->method() != NULL && nm->is_java_method()) { 1514 nmethodJava++; 1515 max_nm_size = MAX2(max_nm_size, nm->size()); 1516 } 1517 } else if (cb->is_runtime_stub()) { 1518 runtimeStubCount++; 1519 } else if (cb->is_deoptimization_stub()) { 1520 deoptimizationStubCount++; 1521 } else if (cb->is_uncommon_trap_stub()) { 1522 uncommonTrapStubCount++; 1523 } else if (cb->is_adapter_blob()) { 1524 adapterCount++; 1525 } else if (cb->is_buffer_blob()) { 1526 bufferBlobCount++; 1527 } 1528 } 1529 } 1530 1531 int bucketSize = 512; 1532 int bucketLimit = max_nm_size / bucketSize + 1; 1533 int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode); 1534 memset(buckets, 0, sizeof(int) * bucketLimit); 1535 1536 NMethodIterator iter; 1537 while(iter.next()) { 1538 nmethod* nm = iter.method(); 1539 if(nm->method() != NULL && nm->is_java_method()) { 1540 buckets[nm->size() / bucketSize]++; 1541 } 1542 } 1543 1544 tty->print_cr("Code Cache Entries (total of %d)",total); 1545 tty->print_cr("-------------------------------------------------"); 1546 tty->print_cr("nmethods: %d",nmethodCount); 1547 tty->print_cr("\talive: %d",nmethodAlive); 1548 tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant); 1549 tty->print_cr("\tzombie: %d",nmethodZombie); 1550 tty->print_cr("\tunloaded: %d",nmethodUnloaded); 1551 tty->print_cr("\tjava: %d",nmethodJava); 1552 tty->print_cr("\tnative: %d",nmethodNative); 1553 tty->print_cr("runtime_stubs: %d",runtimeStubCount); 1554 tty->print_cr("adapters: %d",adapterCount); 1555 tty->print_cr("buffer blobs: %d",bufferBlobCount); 1556 tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount); 1557 tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount); 1558 tty->print_cr("\nnmethod size distribution (non-zombie java)"); 1559 tty->print_cr("-------------------------------------------------"); 1560 1561 for(int i=0; i<bucketLimit; i++) { 1562 if(buckets[i] != 0) { 1563 tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize); 1564 tty->fill_to(40); 1565 tty->print_cr("%d",buckets[i]); 1566 } 1567 } 1568 1569 FREE_C_HEAP_ARRAY(int, buckets); 1570 print_memory_overhead(); 1571 } 1572 1573 #endif // !PRODUCT 1574 1575 void CodeCache::print() { 1576 print_summary(tty); 1577 1578 #ifndef PRODUCT 1579 if (!Verbose) return; 1580 1581 CodeBlob_sizes live; 1582 CodeBlob_sizes dead; 1583 1584 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1585 FOR_ALL_BLOBS(cb, *heap) { 1586 if (!cb->is_alive()) { 1587 dead.add(cb); 1588 } else { 1589 live.add(cb); 1590 } 1591 } 1592 } 1593 1594 tty->print_cr("CodeCache:"); 1595 tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds()); 1596 1597 if (!live.is_empty()) { 1598 live.print("live"); 1599 } 1600 if (!dead.is_empty()) { 1601 dead.print("dead"); 1602 } 1603 1604 if (WizardMode) { 1605 // print the oop_map usage 1606 int code_size = 0; 1607 int number_of_blobs = 0; 1608 int number_of_oop_maps = 0; 1609 int map_size = 0; 1610 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1611 FOR_ALL_BLOBS(cb, *heap) { 1612 if (cb->is_alive()) { 1613 number_of_blobs++; 1614 code_size += cb->code_size(); 1615 ImmutableOopMapSet* set = cb->oop_maps(); 1616 if (set != NULL) { 1617 number_of_oop_maps += set->count(); 1618 map_size += set->nr_of_bytes(); 1619 } 1620 } 1621 } 1622 } 1623 tty->print_cr("OopMaps"); 1624 tty->print_cr(" #blobs = %d", number_of_blobs); 1625 tty->print_cr(" code size = %d", code_size); 1626 tty->print_cr(" #oop_maps = %d", number_of_oop_maps); 1627 tty->print_cr(" map size = %d", map_size); 1628 } 1629 1630 #endif // !PRODUCT 1631 } 1632 1633 void CodeCache::print_summary(outputStream* st, bool detailed) { 1634 int full_count = 0; 1635 FOR_ALL_HEAPS(heap_iterator) { 1636 CodeHeap* heap = (*heap_iterator); 1637 size_t total = (heap->high_boundary() - heap->low_boundary()); 1638 if (_heaps->length() >= 1) { 1639 st->print("%s:", heap->name()); 1640 } else { 1641 st->print("CodeCache:"); 1642 } 1643 st->print_cr(" size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT 1644 "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb", 1645 total/K, (total - heap->unallocated_capacity())/K, 1646 heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K); 1647 1648 if (detailed) { 1649 st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]", 1650 p2i(heap->low_boundary()), 1651 p2i(heap->high()), 1652 p2i(heap->high_boundary())); 1653 1654 full_count += get_codemem_full_count(heap->code_blob_type()); 1655 } 1656 } 1657 1658 if (detailed) { 1659 st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT 1660 " adapters=" UINT32_FORMAT, 1661 blob_count(), nmethod_count(), adapter_count()); 1662 st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ? 1663 "enabled" : Arguments::mode() == Arguments::_int ? 1664 "disabled (interpreter mode)" : 1665 "disabled (not enough contiguous free space left)"); 1666 st->print_cr(" stopped_count=%d, restarted_count=%d", 1667 CompileBroker::get_total_compiler_stopped_count(), 1668 CompileBroker::get_total_compiler_restarted_count()); 1669 st->print_cr(" full_count=%d", full_count); 1670 } 1671 } 1672 1673 void CodeCache::print_codelist(outputStream* st) { 1674 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1675 1676 CompiledMethodIterator iter; 1677 while (iter.next_alive()) { 1678 CompiledMethod* cm = iter.method(); 1679 ResourceMark rm; 1680 char* method_name = cm->method()->name_and_sig_as_C_string(); 1681 st->print_cr("%d %d %d %s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]", 1682 cm->compile_id(), cm->comp_level(), cm->get_state(), 1683 method_name, 1684 (intptr_t)cm->header_begin(), (intptr_t)cm->code_begin(), (intptr_t)cm->code_end()); 1685 } 1686 } 1687 1688 void CodeCache::print_layout(outputStream* st) { 1689 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1690 ResourceMark rm; 1691 print_summary(st, true); 1692 } 1693 1694 void CodeCache::log_state(outputStream* st) { 1695 st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'" 1696 " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'", 1697 blob_count(), nmethod_count(), adapter_count(), 1698 unallocated_capacity()); 1699 } 1700 1701 //---< BEGIN >--- CodeHeap State Analytics. 1702 1703 void CodeCache::aggregate(outputStream *out, const char* granularity) { 1704 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1705 CodeHeapState::aggregate(out, (*heap), granularity); 1706 } 1707 } 1708 1709 void CodeCache::discard(outputStream *out) { 1710 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1711 CodeHeapState::discard(out, (*heap)); 1712 } 1713 } 1714 1715 void CodeCache::print_usedSpace(outputStream *out) { 1716 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1717 CodeHeapState::print_usedSpace(out, (*heap)); 1718 } 1719 } 1720 1721 void CodeCache::print_freeSpace(outputStream *out) { 1722 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1723 CodeHeapState::print_freeSpace(out, (*heap)); 1724 } 1725 } 1726 1727 void CodeCache::print_count(outputStream *out) { 1728 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1729 CodeHeapState::print_count(out, (*heap)); 1730 } 1731 } 1732 1733 void CodeCache::print_space(outputStream *out) { 1734 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1735 CodeHeapState::print_space(out, (*heap)); 1736 } 1737 } 1738 1739 void CodeCache::print_age(outputStream *out) { 1740 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1741 CodeHeapState::print_age(out, (*heap)); 1742 } 1743 } 1744 1745 void CodeCache::print_names(outputStream *out) { 1746 FOR_ALL_ALLOCABLE_HEAPS(heap) { 1747 CodeHeapState::print_names(out, (*heap)); 1748 } 1749 } 1750 //---< END >--- CodeHeap State Analytics.