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