1 /* 2 * Copyright (c) 1997, 2014, 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 "asm/assembler.hpp" 27 #include "classfile/systemDictionary.hpp" 28 #include "code/exceptionHandlerTable.hpp" 29 #include "code/nmethod.hpp" 30 #include "compiler/compileLog.hpp" 31 #include "compiler/oopMap.hpp" 32 #include "opto/addnode.hpp" 33 #include "opto/block.hpp" 34 #include "opto/c2compiler.hpp" 35 #include "opto/callGenerator.hpp" 36 #include "opto/callnode.hpp" 37 #include "opto/cfgnode.hpp" 38 #include "opto/chaitin.hpp" 39 #include "opto/compile.hpp" 40 #include "opto/connode.hpp" 41 #include "opto/divnode.hpp" 42 #include "opto/escape.hpp" 43 #include "opto/idealGraphPrinter.hpp" 44 #include "opto/loopnode.hpp" 45 #include "opto/machnode.hpp" 46 #include "opto/macro.hpp" 47 #include "opto/matcher.hpp" 48 #include "opto/memnode.hpp" 49 #include "opto/mulnode.hpp" 50 #include "opto/node.hpp" 51 #include "opto/opcodes.hpp" 52 #include "opto/output.hpp" 53 #include "opto/parse.hpp" 54 #include "opto/phaseX.hpp" 55 #include "opto/rootnode.hpp" 56 #include "opto/runtime.hpp" 57 #include "opto/stringopts.hpp" 58 #include "opto/type.hpp" 59 #include "opto/vectornode.hpp" 60 #include "runtime/arguments.hpp" 61 #include "runtime/signature.hpp" 62 #include "runtime/stubRoutines.hpp" 63 #include "runtime/timer.hpp" 64 #include "trace/tracing.hpp" 65 #include "utilities/copy.hpp" 66 #ifdef TARGET_ARCH_MODEL_x86_32 67 # include "adfiles/ad_x86_32.hpp" 68 #endif 69 #ifdef TARGET_ARCH_MODEL_x86_64 70 # include "adfiles/ad_x86_64.hpp" 71 #endif 72 #ifdef TARGET_ARCH_MODEL_sparc 73 # include "adfiles/ad_sparc.hpp" 74 #endif 75 #ifdef TARGET_ARCH_MODEL_zero 76 # include "adfiles/ad_zero.hpp" 77 #endif 78 #ifdef TARGET_ARCH_MODEL_arm 79 # include "adfiles/ad_arm.hpp" 80 #endif 81 #ifdef TARGET_ARCH_MODEL_ppc_32 82 # include "adfiles/ad_ppc_32.hpp" 83 #endif 84 #ifdef TARGET_ARCH_MODEL_ppc_64 85 # include "adfiles/ad_ppc_64.hpp" 86 #endif 87 #ifdef TARGET_ARCH_x86 88 # include "compile_x86.hpp" 89 #endif 90 #ifdef TARGET_ARCH_sparc 91 # include "compile_sparc.hpp" 92 #endif 93 #ifdef TARGET_ARCH_zero 94 # include "compile_zero.hpp" 95 #endif 96 #ifdef TARGET_ARCH_ppc 97 # include "compile_ppc.hpp" 98 #endif 99 100 101 // -------------------- Compile::mach_constant_base_node ----------------------- 102 // Constant table base node singleton. 103 MachConstantBaseNode* Compile::mach_constant_base_node() { 104 if (_mach_constant_base_node == NULL) { 105 _mach_constant_base_node = new (C) MachConstantBaseNode(); 106 _mach_constant_base_node->add_req(C->root()); 107 } 108 return _mach_constant_base_node; 109 } 110 111 112 /// Support for intrinsics. 113 114 // Return the index at which m must be inserted (or already exists). 115 // The sort order is by the address of the ciMethod, with is_virtual as minor key. 116 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual) { 117 #ifdef ASSERT 118 for (int i = 1; i < _intrinsics->length(); i++) { 119 CallGenerator* cg1 = _intrinsics->at(i-1); 120 CallGenerator* cg2 = _intrinsics->at(i); 121 assert(cg1->method() != cg2->method() 122 ? cg1->method() < cg2->method() 123 : cg1->is_virtual() < cg2->is_virtual(), 124 "compiler intrinsics list must stay sorted"); 125 } 126 #endif 127 // Binary search sorted list, in decreasing intervals [lo, hi]. 128 int lo = 0, hi = _intrinsics->length()-1; 129 while (lo <= hi) { 130 int mid = (uint)(hi + lo) / 2; 131 ciMethod* mid_m = _intrinsics->at(mid)->method(); 132 if (m < mid_m) { 133 hi = mid-1; 134 } else if (m > mid_m) { 135 lo = mid+1; 136 } else { 137 // look at minor sort key 138 bool mid_virt = _intrinsics->at(mid)->is_virtual(); 139 if (is_virtual < mid_virt) { 140 hi = mid-1; 141 } else if (is_virtual > mid_virt) { 142 lo = mid+1; 143 } else { 144 return mid; // exact match 145 } 146 } 147 } 148 return lo; // inexact match 149 } 150 151 void Compile::register_intrinsic(CallGenerator* cg) { 152 if (_intrinsics == NULL) { 153 _intrinsics = new (comp_arena())GrowableArray<CallGenerator*>(comp_arena(), 60, 0, NULL); 154 } 155 // This code is stolen from ciObjectFactory::insert. 156 // Really, GrowableArray should have methods for 157 // insert_at, remove_at, and binary_search. 158 int len = _intrinsics->length(); 159 int index = intrinsic_insertion_index(cg->method(), cg->is_virtual()); 160 if (index == len) { 161 _intrinsics->append(cg); 162 } else { 163 #ifdef ASSERT 164 CallGenerator* oldcg = _intrinsics->at(index); 165 assert(oldcg->method() != cg->method() || oldcg->is_virtual() != cg->is_virtual(), "don't register twice"); 166 #endif 167 _intrinsics->append(_intrinsics->at(len-1)); 168 int pos; 169 for (pos = len-2; pos >= index; pos--) { 170 _intrinsics->at_put(pos+1,_intrinsics->at(pos)); 171 } 172 _intrinsics->at_put(index, cg); 173 } 174 assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked"); 175 } 176 177 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) { 178 assert(m->is_loaded(), "don't try this on unloaded methods"); 179 if (_intrinsics != NULL) { 180 int index = intrinsic_insertion_index(m, is_virtual); 181 if (index < _intrinsics->length() 182 && _intrinsics->at(index)->method() == m 183 && _intrinsics->at(index)->is_virtual() == is_virtual) { 184 return _intrinsics->at(index); 185 } 186 } 187 // Lazily create intrinsics for intrinsic IDs well-known in the runtime. 188 if (m->intrinsic_id() != vmIntrinsics::_none && 189 m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) { 190 CallGenerator* cg = make_vm_intrinsic(m, is_virtual); 191 if (cg != NULL) { 192 // Save it for next time: 193 register_intrinsic(cg); 194 return cg; 195 } else { 196 gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled); 197 } 198 } 199 return NULL; 200 } 201 202 // Compile:: register_library_intrinsics and make_vm_intrinsic are defined 203 // in library_call.cpp. 204 205 206 #ifndef PRODUCT 207 // statistics gathering... 208 209 juint Compile::_intrinsic_hist_count[vmIntrinsics::ID_LIMIT] = {0}; 210 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::ID_LIMIT] = {0}; 211 212 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) { 213 assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob"); 214 int oflags = _intrinsic_hist_flags[id]; 215 assert(flags != 0, "what happened?"); 216 if (is_virtual) { 217 flags |= _intrinsic_virtual; 218 } 219 bool changed = (flags != oflags); 220 if ((flags & _intrinsic_worked) != 0) { 221 juint count = (_intrinsic_hist_count[id] += 1); 222 if (count == 1) { 223 changed = true; // first time 224 } 225 // increment the overall count also: 226 _intrinsic_hist_count[vmIntrinsics::_none] += 1; 227 } 228 if (changed) { 229 if (((oflags ^ flags) & _intrinsic_virtual) != 0) { 230 // Something changed about the intrinsic's virtuality. 231 if ((flags & _intrinsic_virtual) != 0) { 232 // This is the first use of this intrinsic as a virtual call. 233 if (oflags != 0) { 234 // We already saw it as a non-virtual, so note both cases. 235 flags |= _intrinsic_both; 236 } 237 } else if ((oflags & _intrinsic_both) == 0) { 238 // This is the first use of this intrinsic as a non-virtual 239 flags |= _intrinsic_both; 240 } 241 } 242 _intrinsic_hist_flags[id] = (jubyte) (oflags | flags); 243 } 244 // update the overall flags also: 245 _intrinsic_hist_flags[vmIntrinsics::_none] |= (jubyte) flags; 246 return changed; 247 } 248 249 static char* format_flags(int flags, char* buf) { 250 buf[0] = 0; 251 if ((flags & Compile::_intrinsic_worked) != 0) strcat(buf, ",worked"); 252 if ((flags & Compile::_intrinsic_failed) != 0) strcat(buf, ",failed"); 253 if ((flags & Compile::_intrinsic_disabled) != 0) strcat(buf, ",disabled"); 254 if ((flags & Compile::_intrinsic_virtual) != 0) strcat(buf, ",virtual"); 255 if ((flags & Compile::_intrinsic_both) != 0) strcat(buf, ",nonvirtual"); 256 if (buf[0] == 0) strcat(buf, ","); 257 assert(buf[0] == ',', "must be"); 258 return &buf[1]; 259 } 260 261 void Compile::print_intrinsic_statistics() { 262 char flagsbuf[100]; 263 ttyLocker ttyl; 264 if (xtty != NULL) xtty->head("statistics type='intrinsic'"); 265 tty->print_cr("Compiler intrinsic usage:"); 266 juint total = _intrinsic_hist_count[vmIntrinsics::_none]; 267 if (total == 0) total = 1; // avoid div0 in case of no successes 268 #define PRINT_STAT_LINE(name, c, f) \ 269 tty->print_cr(" %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f); 270 for (int index = 1 + (int)vmIntrinsics::_none; index < (int)vmIntrinsics::ID_LIMIT; index++) { 271 vmIntrinsics::ID id = (vmIntrinsics::ID) index; 272 int flags = _intrinsic_hist_flags[id]; 273 juint count = _intrinsic_hist_count[id]; 274 if ((flags | count) != 0) { 275 PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf)); 276 } 277 } 278 PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[vmIntrinsics::_none], flagsbuf)); 279 if (xtty != NULL) xtty->tail("statistics"); 280 } 281 282 void Compile::print_statistics() { 283 { ttyLocker ttyl; 284 if (xtty != NULL) xtty->head("statistics type='opto'"); 285 Parse::print_statistics(); 286 PhaseCCP::print_statistics(); 287 PhaseRegAlloc::print_statistics(); 288 Scheduling::print_statistics(); 289 PhasePeephole::print_statistics(); 290 PhaseIdealLoop::print_statistics(); 291 if (xtty != NULL) xtty->tail("statistics"); 292 } 293 if (_intrinsic_hist_flags[vmIntrinsics::_none] != 0) { 294 // put this under its own <statistics> element. 295 print_intrinsic_statistics(); 296 } 297 } 298 #endif //PRODUCT 299 300 // Support for bundling info 301 Bundle* Compile::node_bundling(const Node *n) { 302 assert(valid_bundle_info(n), "oob"); 303 return &_node_bundling_base[n->_idx]; 304 } 305 306 bool Compile::valid_bundle_info(const Node *n) { 307 return (_node_bundling_limit > n->_idx); 308 } 309 310 311 void Compile::gvn_replace_by(Node* n, Node* nn) { 312 for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) { 313 Node* use = n->last_out(i); 314 bool is_in_table = initial_gvn()->hash_delete(use); 315 uint uses_found = 0; 316 for (uint j = 0; j < use->len(); j++) { 317 if (use->in(j) == n) { 318 if (j < use->req()) 319 use->set_req(j, nn); 320 else 321 use->set_prec(j, nn); 322 uses_found++; 323 } 324 } 325 if (is_in_table) { 326 // reinsert into table 327 initial_gvn()->hash_find_insert(use); 328 } 329 record_for_igvn(use); 330 i -= uses_found; // we deleted 1 or more copies of this edge 331 } 332 } 333 334 335 static inline bool not_a_node(const Node* n) { 336 if (n == NULL) return true; 337 if (((intptr_t)n & 1) != 0) return true; // uninitialized, etc. 338 if (*(address*)n == badAddress) return true; // kill by Node::destruct 339 return false; 340 } 341 342 // Identify all nodes that are reachable from below, useful. 343 // Use breadth-first pass that records state in a Unique_Node_List, 344 // recursive traversal is slower. 345 void Compile::identify_useful_nodes(Unique_Node_List &useful) { 346 int estimated_worklist_size = unique(); 347 useful.map( estimated_worklist_size, NULL ); // preallocate space 348 349 // Initialize worklist 350 if (root() != NULL) { useful.push(root()); } 351 // If 'top' is cached, declare it useful to preserve cached node 352 if( cached_top_node() ) { useful.push(cached_top_node()); } 353 354 // Push all useful nodes onto the list, breadthfirst 355 for( uint next = 0; next < useful.size(); ++next ) { 356 assert( next < unique(), "Unique useful nodes < total nodes"); 357 Node *n = useful.at(next); 358 uint max = n->len(); 359 for( uint i = 0; i < max; ++i ) { 360 Node *m = n->in(i); 361 if (not_a_node(m)) continue; 362 useful.push(m); 363 } 364 } 365 } 366 367 // Update dead_node_list with any missing dead nodes using useful 368 // list. Consider all non-useful nodes to be useless i.e., dead nodes. 369 void Compile::update_dead_node_list(Unique_Node_List &useful) { 370 uint max_idx = unique(); 371 VectorSet& useful_node_set = useful.member_set(); 372 373 for (uint node_idx = 0; node_idx < max_idx; node_idx++) { 374 // If node with index node_idx is not in useful set, 375 // mark it as dead in dead node list. 376 if (! useful_node_set.test(node_idx) ) { 377 record_dead_node(node_idx); 378 } 379 } 380 } 381 382 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) { 383 int shift = 0; 384 for (int i = 0; i < inlines->length(); i++) { 385 CallGenerator* cg = inlines->at(i); 386 CallNode* call = cg->call_node(); 387 if (shift > 0) { 388 inlines->at_put(i-shift, cg); 389 } 390 if (!useful.member(call)) { 391 shift++; 392 } 393 } 394 inlines->trunc_to(inlines->length()-shift); 395 } 396 397 // Disconnect all useless nodes by disconnecting those at the boundary. 398 void Compile::remove_useless_nodes(Unique_Node_List &useful) { 399 uint next = 0; 400 while (next < useful.size()) { 401 Node *n = useful.at(next++); 402 // Use raw traversal of out edges since this code removes out edges 403 int max = n->outcnt(); 404 for (int j = 0; j < max; ++j) { 405 Node* child = n->raw_out(j); 406 if (! useful.member(child)) { 407 assert(!child->is_top() || child != top(), 408 "If top is cached in Compile object it is in useful list"); 409 // Only need to remove this out-edge to the useless node 410 n->raw_del_out(j); 411 --j; 412 --max; 413 } 414 } 415 if (n->outcnt() == 1 && n->has_special_unique_user()) { 416 record_for_igvn(n->unique_out()); 417 } 418 } 419 // Remove useless macro and predicate opaq nodes 420 for (int i = C->macro_count()-1; i >= 0; i--) { 421 Node* n = C->macro_node(i); 422 if (!useful.member(n)) { 423 remove_macro_node(n); 424 } 425 } 426 // Remove useless expensive node 427 for (int i = C->expensive_count()-1; i >= 0; i--) { 428 Node* n = C->expensive_node(i); 429 if (!useful.member(n)) { 430 remove_expensive_node(n); 431 } 432 } 433 // clean up the late inline lists 434 remove_useless_late_inlines(&_string_late_inlines, useful); 435 remove_useless_late_inlines(&_late_inlines, useful); 436 debug_only(verify_graph_edges(true/*check for no_dead_code*/);) 437 } 438 439 //------------------------------frame_size_in_words----------------------------- 440 // frame_slots in units of words 441 int Compile::frame_size_in_words() const { 442 // shift is 0 in LP32 and 1 in LP64 443 const int shift = (LogBytesPerWord - LogBytesPerInt); 444 int words = _frame_slots >> shift; 445 assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" ); 446 return words; 447 } 448 449 // ============================================================================ 450 //------------------------------CompileWrapper--------------------------------- 451 class CompileWrapper : public StackObj { 452 Compile *const _compile; 453 public: 454 CompileWrapper(Compile* compile); 455 456 ~CompileWrapper(); 457 }; 458 459 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) { 460 // the Compile* pointer is stored in the current ciEnv: 461 ciEnv* env = compile->env(); 462 assert(env == ciEnv::current(), "must already be a ciEnv active"); 463 assert(env->compiler_data() == NULL, "compile already active?"); 464 env->set_compiler_data(compile); 465 assert(compile == Compile::current(), "sanity"); 466 467 compile->set_type_dict(NULL); 468 compile->set_type_hwm(NULL); 469 compile->set_type_last_size(0); 470 compile->set_last_tf(NULL, NULL); 471 compile->set_indexSet_arena(NULL); 472 compile->set_indexSet_free_block_list(NULL); 473 compile->init_type_arena(); 474 Type::Initialize(compile); 475 _compile->set_scratch_buffer_blob(NULL); 476 _compile->begin_method(); 477 } 478 CompileWrapper::~CompileWrapper() { 479 _compile->end_method(); 480 if (_compile->scratch_buffer_blob() != NULL) 481 BufferBlob::free(_compile->scratch_buffer_blob()); 482 _compile->env()->set_compiler_data(NULL); 483 } 484 485 486 //----------------------------print_compile_messages--------------------------- 487 void Compile::print_compile_messages() { 488 #ifndef PRODUCT 489 // Check if recompiling 490 if (_subsume_loads == false && PrintOpto) { 491 // Recompiling without allowing machine instructions to subsume loads 492 tty->print_cr("*********************************************************"); 493 tty->print_cr("** Bailout: Recompile without subsuming loads **"); 494 tty->print_cr("*********************************************************"); 495 } 496 if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) { 497 // Recompiling without escape analysis 498 tty->print_cr("*********************************************************"); 499 tty->print_cr("** Bailout: Recompile without escape analysis **"); 500 tty->print_cr("*********************************************************"); 501 } 502 if (env()->break_at_compile()) { 503 // Open the debugger when compiling this method. 504 tty->print("### Breaking when compiling: "); 505 method()->print_short_name(); 506 tty->cr(); 507 BREAKPOINT; 508 } 509 510 if( PrintOpto ) { 511 if (is_osr_compilation()) { 512 tty->print("[OSR]%3d", _compile_id); 513 } else { 514 tty->print("%3d", _compile_id); 515 } 516 } 517 #endif 518 } 519 520 521 //-----------------------init_scratch_buffer_blob------------------------------ 522 // Construct a temporary BufferBlob and cache it for this compile. 523 void Compile::init_scratch_buffer_blob(int const_size) { 524 // If there is already a scratch buffer blob allocated and the 525 // constant section is big enough, use it. Otherwise free the 526 // current and allocate a new one. 527 BufferBlob* blob = scratch_buffer_blob(); 528 if ((blob != NULL) && (const_size <= _scratch_const_size)) { 529 // Use the current blob. 530 } else { 531 if (blob != NULL) { 532 BufferBlob::free(blob); 533 } 534 535 ResourceMark rm; 536 _scratch_const_size = const_size; 537 int size = (MAX_inst_size + MAX_stubs_size + _scratch_const_size); 538 blob = BufferBlob::create("Compile::scratch_buffer", size); 539 // Record the buffer blob for next time. 540 set_scratch_buffer_blob(blob); 541 // Have we run out of code space? 542 if (scratch_buffer_blob() == NULL) { 543 // Let CompilerBroker disable further compilations. 544 record_failure("Not enough space for scratch buffer in CodeCache"); 545 return; 546 } 547 } 548 549 // Initialize the relocation buffers 550 relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size; 551 set_scratch_locs_memory(locs_buf); 552 } 553 554 555 //-----------------------scratch_emit_size------------------------------------- 556 // Helper function that computes size by emitting code 557 uint Compile::scratch_emit_size(const Node* n) { 558 // Start scratch_emit_size section. 559 set_in_scratch_emit_size(true); 560 561 // Emit into a trash buffer and count bytes emitted. 562 // This is a pretty expensive way to compute a size, 563 // but it works well enough if seldom used. 564 // All common fixed-size instructions are given a size 565 // method by the AD file. 566 // Note that the scratch buffer blob and locs memory are 567 // allocated at the beginning of the compile task, and 568 // may be shared by several calls to scratch_emit_size. 569 // The allocation of the scratch buffer blob is particularly 570 // expensive, since it has to grab the code cache lock. 571 BufferBlob* blob = this->scratch_buffer_blob(); 572 assert(blob != NULL, "Initialize BufferBlob at start"); 573 assert(blob->size() > MAX_inst_size, "sanity"); 574 relocInfo* locs_buf = scratch_locs_memory(); 575 address blob_begin = blob->content_begin(); 576 address blob_end = (address)locs_buf; 577 assert(blob->content_contains(blob_end), "sanity"); 578 CodeBuffer buf(blob_begin, blob_end - blob_begin); 579 buf.initialize_consts_size(_scratch_const_size); 580 buf.initialize_stubs_size(MAX_stubs_size); 581 assert(locs_buf != NULL, "sanity"); 582 int lsize = MAX_locs_size / 3; 583 buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize); 584 buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize); 585 buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize); 586 buf.consts()->set_scratch_emit(); 587 buf.insts() ->set_scratch_emit(); 588 buf.stubs() ->set_scratch_emit(); 589 590 // Do the emission. 591 592 Label fakeL; // Fake label for branch instructions. 593 Label* saveL = NULL; 594 uint save_bnum = 0; 595 bool is_branch = n->is_MachBranch(); 596 if (is_branch) { 597 MacroAssembler masm(&buf); 598 masm.bind(fakeL); 599 n->as_MachBranch()->save_label(&saveL, &save_bnum); 600 n->as_MachBranch()->label_set(&fakeL, 0); 601 } 602 n->emit(buf, this->regalloc()); 603 if (is_branch) // Restore label. 604 n->as_MachBranch()->label_set(saveL, save_bnum); 605 606 // End scratch_emit_size section. 607 set_in_scratch_emit_size(false); 608 609 return buf.insts_size(); 610 } 611 612 613 // ============================================================================ 614 //------------------------------Compile standard------------------------------- 615 debug_only( int Compile::_debug_idx = 100000; ) 616 617 // Compile a method. entry_bci is -1 for normal compilations and indicates 618 // the continuation bci for on stack replacement. 619 620 621 Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr_bci, bool subsume_loads, bool do_escape_analysis ) 622 : Phase(Compiler), 623 _env(ci_env), 624 _log(ci_env->log()), 625 _compile_id(ci_env->compile_id()), 626 _save_argument_registers(false), 627 _stub_name(NULL), 628 _stub_function(NULL), 629 _stub_entry_point(NULL), 630 _method(target), 631 _entry_bci(osr_bci), 632 _initial_gvn(NULL), 633 _for_igvn(NULL), 634 _warm_calls(NULL), 635 _subsume_loads(subsume_loads), 636 _do_escape_analysis(do_escape_analysis), 637 _failure_reason(NULL), 638 _code_buffer("Compile::Fill_buffer"), 639 _orig_pc_slot(0), 640 _orig_pc_slot_offset_in_bytes(0), 641 _has_method_handle_invokes(false), 642 _mach_constant_base_node(NULL), 643 _node_bundling_limit(0), 644 _node_bundling_base(NULL), 645 _java_calls(0), 646 _inner_loops(0), 647 _scratch_const_size(-1), 648 _in_scratch_emit_size(false), 649 _dead_node_list(comp_arena()), 650 _dead_node_count(0), 651 #ifndef PRODUCT 652 _trace_opto_output(TraceOptoOutput || method()->has_option("TraceOptoOutput")), 653 _in_dump_cnt(0), 654 _printer(IdealGraphPrinter::printer()), 655 #endif 656 _congraph(NULL), 657 _late_inlines(comp_arena(), 2, 0, NULL), 658 _string_late_inlines(comp_arena(), 2, 0, NULL), 659 _late_inlines_pos(0), 660 _number_of_mh_late_inlines(0), 661 _inlining_progress(false), 662 _inlining_incrementally(false), 663 _print_inlining_list(NULL), 664 _print_inlining_idx(0) { 665 C = this; 666 667 CompileWrapper cw(this); 668 #ifndef PRODUCT 669 if (TimeCompiler2) { 670 tty->print(" "); 671 target->holder()->name()->print(); 672 tty->print("."); 673 target->print_short_name(); 674 tty->print(" "); 675 } 676 TraceTime t1("Total compilation time", &_t_totalCompilation, TimeCompiler, TimeCompiler2); 677 TraceTime t2(NULL, &_t_methodCompilation, TimeCompiler, false); 678 bool print_opto_assembly = PrintOptoAssembly || _method->has_option("PrintOptoAssembly"); 679 if (!print_opto_assembly) { 680 bool print_assembly = (PrintAssembly || _method->should_print_assembly()); 681 if (print_assembly && !Disassembler::can_decode()) { 682 tty->print_cr("PrintAssembly request changed to PrintOptoAssembly"); 683 print_opto_assembly = true; 684 } 685 } 686 set_print_assembly(print_opto_assembly); 687 set_parsed_irreducible_loop(false); 688 #endif 689 set_print_inlining(PrintInlining || method()->has_option("PrintInlining") NOT_PRODUCT( || PrintOptoInlining)); 690 set_print_intrinsics(PrintIntrinsics || method()->has_option("PrintIntrinsics")); 691 set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it 692 693 if (ProfileTraps) { 694 // Make sure the method being compiled gets its own MDO, 695 // so we can at least track the decompile_count(). 696 method()->ensure_method_data(); 697 } 698 699 Init(::AliasLevel); 700 701 702 print_compile_messages(); 703 704 if (UseOldInlining || PrintCompilation NOT_PRODUCT( || PrintOpto) ) 705 _ilt = InlineTree::build_inline_tree_root(); 706 else 707 _ilt = NULL; 708 709 // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice 710 assert(num_alias_types() >= AliasIdxRaw, ""); 711 712 #define MINIMUM_NODE_HASH 1023 713 // Node list that Iterative GVN will start with 714 Unique_Node_List for_igvn(comp_arena()); 715 set_for_igvn(&for_igvn); 716 717 // GVN that will be run immediately on new nodes 718 uint estimated_size = method()->code_size()*4+64; 719 estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size); 720 PhaseGVN gvn(node_arena(), estimated_size); 721 set_initial_gvn(&gvn); 722 723 if (print_inlining() || print_intrinsics()) { 724 _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer>(comp_arena(), 1, 1, PrintInliningBuffer()); 725 } 726 { // Scope for timing the parser 727 TracePhase t3("parse", &_t_parser, true); 728 729 // Put top into the hash table ASAP. 730 initial_gvn()->transform_no_reclaim(top()); 731 732 // Set up tf(), start(), and find a CallGenerator. 733 CallGenerator* cg = NULL; 734 if (is_osr_compilation()) { 735 const TypeTuple *domain = StartOSRNode::osr_domain(); 736 const TypeTuple *range = TypeTuple::make_range(method()->signature()); 737 init_tf(TypeFunc::make(domain, range)); 738 StartNode* s = new (this) StartOSRNode(root(), domain); 739 initial_gvn()->set_type_bottom(s); 740 init_start(s); 741 cg = CallGenerator::for_osr(method(), entry_bci()); 742 } else { 743 // Normal case. 744 init_tf(TypeFunc::make(method())); 745 StartNode* s = new (this) StartNode(root(), tf()->domain()); 746 initial_gvn()->set_type_bottom(s); 747 init_start(s); 748 if (method()->intrinsic_id() == vmIntrinsics::_Reference_get && UseG1GC) { 749 // With java.lang.ref.reference.get() we must go through the 750 // intrinsic when G1 is enabled - even when get() is the root 751 // method of the compile - so that, if necessary, the value in 752 // the referent field of the reference object gets recorded by 753 // the pre-barrier code. 754 // Specifically, if G1 is enabled, the value in the referent 755 // field is recorded by the G1 SATB pre barrier. This will 756 // result in the referent being marked live and the reference 757 // object removed from the list of discovered references during 758 // reference processing. 759 cg = find_intrinsic(method(), false); 760 } 761 if (cg == NULL) { 762 float past_uses = method()->interpreter_invocation_count(); 763 float expected_uses = past_uses; 764 cg = CallGenerator::for_inline(method(), expected_uses); 765 } 766 } 767 if (failing()) return; 768 if (cg == NULL) { 769 record_method_not_compilable_all_tiers("cannot parse method"); 770 return; 771 } 772 JVMState* jvms = build_start_state(start(), tf()); 773 if ((jvms = cg->generate(jvms)) == NULL) { 774 record_method_not_compilable("method parse failed"); 775 return; 776 } 777 GraphKit kit(jvms); 778 779 if (!kit.stopped()) { 780 // Accept return values, and transfer control we know not where. 781 // This is done by a special, unique ReturnNode bound to root. 782 return_values(kit.jvms()); 783 } 784 785 if (kit.has_exceptions()) { 786 // Any exceptions that escape from this call must be rethrown 787 // to whatever caller is dynamically above us on the stack. 788 // This is done by a special, unique RethrowNode bound to root. 789 rethrow_exceptions(kit.transfer_exceptions_into_jvms()); 790 } 791 792 assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off"); 793 794 if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) { 795 inline_string_calls(true); 796 } 797 798 if (failing()) return; 799 800 print_method(PHASE_BEFORE_REMOVEUSELESS, 3); 801 802 // Remove clutter produced by parsing. 803 if (!failing()) { 804 ResourceMark rm; 805 PhaseRemoveUseless pru(initial_gvn(), &for_igvn); 806 } 807 } 808 809 // Note: Large methods are capped off in do_one_bytecode(). 810 if (failing()) return; 811 812 // After parsing, node notes are no longer automagic. 813 // They must be propagated by register_new_node_with_optimizer(), 814 // clone(), or the like. 815 set_default_node_notes(NULL); 816 817 for (;;) { 818 int successes = Inline_Warm(); 819 if (failing()) return; 820 if (successes == 0) break; 821 } 822 823 // Drain the list. 824 Finish_Warm(); 825 #ifndef PRODUCT 826 if (_printer) { 827 _printer->print_inlining(this); 828 } 829 #endif 830 831 if (failing()) return; 832 NOT_PRODUCT( verify_graph_edges(); ) 833 834 // Now optimize 835 Optimize(); 836 if (failing()) return; 837 NOT_PRODUCT( verify_graph_edges(); ) 838 839 #ifndef PRODUCT 840 if (PrintIdeal) { 841 ttyLocker ttyl; // keep the following output all in one block 842 // This output goes directly to the tty, not the compiler log. 843 // To enable tools to match it up with the compilation activity, 844 // be sure to tag this tty output with the compile ID. 845 if (xtty != NULL) { 846 xtty->head("ideal compile_id='%d'%s", compile_id(), 847 is_osr_compilation() ? " compile_kind='osr'" : 848 ""); 849 } 850 root()->dump(9999); 851 if (xtty != NULL) { 852 xtty->tail("ideal"); 853 } 854 } 855 #endif 856 857 NOT_PRODUCT( verify_barriers(); ) 858 // Now that we know the size of all the monitors we can add a fixed slot 859 // for the original deopt pc. 860 861 _orig_pc_slot = fixed_slots(); 862 int next_slot = _orig_pc_slot + (sizeof(address) / VMRegImpl::stack_slot_size); 863 set_fixed_slots(next_slot); 864 865 // Now generate code 866 Code_Gen(); 867 if (failing()) return; 868 869 // Check if we want to skip execution of all compiled code. 870 { 871 #ifndef PRODUCT 872 if (OptoNoExecute) { 873 record_method_not_compilable("+OptoNoExecute"); // Flag as failed 874 return; 875 } 876 TracePhase t2("install_code", &_t_registerMethod, TimeCompiler); 877 #endif 878 879 if (is_osr_compilation()) { 880 _code_offsets.set_value(CodeOffsets::Verified_Entry, 0); 881 _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size); 882 } else { 883 _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size); 884 _code_offsets.set_value(CodeOffsets::OSR_Entry, 0); 885 } 886 887 env()->register_method(_method, _entry_bci, 888 &_code_offsets, 889 _orig_pc_slot_offset_in_bytes, 890 code_buffer(), 891 frame_size_in_words(), _oop_map_set, 892 &_handler_table, &_inc_table, 893 compiler, 894 env()->comp_level(), 895 has_unsafe_access(), 896 SharedRuntime::is_wide_vector(max_vector_size()) 897 ); 898 899 if (log() != NULL) // Print code cache state into compiler log 900 log()->code_cache_state(); 901 } 902 } 903 904 //------------------------------Compile---------------------------------------- 905 // Compile a runtime stub 906 Compile::Compile( ciEnv* ci_env, 907 TypeFunc_generator generator, 908 address stub_function, 909 const char *stub_name, 910 int is_fancy_jump, 911 bool pass_tls, 912 bool save_arg_registers, 913 bool return_pc ) 914 : Phase(Compiler), 915 _env(ci_env), 916 _log(ci_env->log()), 917 _compile_id(0), 918 _save_argument_registers(save_arg_registers), 919 _method(NULL), 920 _stub_name(stub_name), 921 _stub_function(stub_function), 922 _stub_entry_point(NULL), 923 _entry_bci(InvocationEntryBci), 924 _initial_gvn(NULL), 925 _for_igvn(NULL), 926 _warm_calls(NULL), 927 _orig_pc_slot(0), 928 _orig_pc_slot_offset_in_bytes(0), 929 _subsume_loads(true), 930 _do_escape_analysis(false), 931 _failure_reason(NULL), 932 _code_buffer("Compile::Fill_buffer"), 933 _has_method_handle_invokes(false), 934 _mach_constant_base_node(NULL), 935 _node_bundling_limit(0), 936 _node_bundling_base(NULL), 937 _java_calls(0), 938 _inner_loops(0), 939 #ifndef PRODUCT 940 _trace_opto_output(TraceOptoOutput), 941 _in_dump_cnt(0), 942 _printer(NULL), 943 #endif 944 _dead_node_list(comp_arena()), 945 _dead_node_count(0), 946 _congraph(NULL), 947 _number_of_mh_late_inlines(0), 948 _inlining_progress(false), 949 _inlining_incrementally(false), 950 _print_inlining_list(NULL), 951 _print_inlining_idx(0) { 952 C = this; 953 954 #ifndef PRODUCT 955 TraceTime t1(NULL, &_t_totalCompilation, TimeCompiler, false); 956 TraceTime t2(NULL, &_t_stubCompilation, TimeCompiler, false); 957 set_print_assembly(PrintFrameConverterAssembly); 958 set_parsed_irreducible_loop(false); 959 #endif 960 set_has_irreducible_loop(false); // no loops 961 962 CompileWrapper cw(this); 963 Init(/*AliasLevel=*/ 0); 964 init_tf((*generator)()); 965 966 { 967 // The following is a dummy for the sake of GraphKit::gen_stub 968 Unique_Node_List for_igvn(comp_arena()); 969 set_for_igvn(&for_igvn); // not used, but some GraphKit guys push on this 970 PhaseGVN gvn(Thread::current()->resource_area(),255); 971 set_initial_gvn(&gvn); // not significant, but GraphKit guys use it pervasively 972 gvn.transform_no_reclaim(top()); 973 974 GraphKit kit; 975 kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc); 976 } 977 978 NOT_PRODUCT( verify_graph_edges(); ) 979 Code_Gen(); 980 if (failing()) return; 981 982 983 // Entry point will be accessed using compile->stub_entry_point(); 984 if (code_buffer() == NULL) { 985 Matcher::soft_match_failure(); 986 } else { 987 if (PrintAssembly && (WizardMode || Verbose)) 988 tty->print_cr("### Stub::%s", stub_name); 989 990 if (!failing()) { 991 assert(_fixed_slots == 0, "no fixed slots used for runtime stubs"); 992 993 // Make the NMethod 994 // For now we mark the frame as never safe for profile stackwalking 995 RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name, 996 code_buffer(), 997 CodeOffsets::frame_never_safe, 998 // _code_offsets.value(CodeOffsets::Frame_Complete), 999 frame_size_in_words(), 1000 _oop_map_set, 1001 save_arg_registers); 1002 assert(rs != NULL && rs->is_runtime_stub(), "sanity check"); 1003 1004 _stub_entry_point = rs->entry_point(); 1005 } 1006 } 1007 } 1008 1009 #ifndef PRODUCT 1010 void print_opto_verbose_signature( const TypeFunc *j_sig, const char *stub_name ) { 1011 if(PrintOpto && Verbose) { 1012 tty->print("%s ", stub_name); j_sig->print_flattened(); tty->cr(); 1013 } 1014 } 1015 #endif 1016 1017 void Compile::print_codes() { 1018 } 1019 1020 //------------------------------Init------------------------------------------- 1021 // Prepare for a single compilation 1022 void Compile::Init(int aliaslevel) { 1023 _unique = 0; 1024 _regalloc = NULL; 1025 1026 _tf = NULL; // filled in later 1027 _top = NULL; // cached later 1028 _matcher = NULL; // filled in later 1029 _cfg = NULL; // filled in later 1030 1031 set_24_bit_selection_and_mode(Use24BitFP, false); 1032 1033 _node_note_array = NULL; 1034 _default_node_notes = NULL; 1035 1036 _immutable_memory = NULL; // filled in at first inquiry 1037 1038 // Globally visible Nodes 1039 // First set TOP to NULL to give safe behavior during creation of RootNode 1040 set_cached_top_node(NULL); 1041 set_root(new (this) RootNode()); 1042 // Now that you have a Root to point to, create the real TOP 1043 set_cached_top_node( new (this) ConNode(Type::TOP) ); 1044 set_recent_alloc(NULL, NULL); 1045 1046 // Create Debug Information Recorder to record scopes, oopmaps, etc. 1047 env()->set_oop_recorder(new OopRecorder(comp_arena())); 1048 env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder())); 1049 env()->set_dependencies(new Dependencies(env())); 1050 1051 _fixed_slots = 0; 1052 set_has_split_ifs(false); 1053 set_has_loops(has_method() && method()->has_loops()); // first approximation 1054 set_has_stringbuilder(false); 1055 _trap_can_recompile = false; // no traps emitted yet 1056 _major_progress = true; // start out assuming good things will happen 1057 set_has_unsafe_access(false); 1058 set_max_vector_size(0); 1059 Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist)); 1060 set_decompile_count(0); 1061 1062 // Compute when not to trap. Used by matching trap based nodes and 1063 // NullCheck optimization. 1064 _allowed_reasons = 0; 1065 for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) { 1066 assert(rs < BitsPerInt, "recode bit map"); 1067 if (!C->too_many_traps((Deoptimization::DeoptReason) rs)) 1068 _allowed_reasons |= nth_bit(rs); 1069 } 1070 1071 set_do_freq_based_layout(BlockLayoutByFrequency || method_has_option("BlockLayoutByFrequency")); 1072 set_num_loop_opts(LoopOptsCount); 1073 set_do_inlining(Inline); 1074 set_max_inline_size(MaxInlineSize); 1075 set_freq_inline_size(FreqInlineSize); 1076 set_do_scheduling(OptoScheduling); 1077 set_do_count_invocations(false); 1078 set_do_method_data_update(false); 1079 1080 if (debug_info()->recording_non_safepoints()) { 1081 set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*> 1082 (comp_arena(), 8, 0, NULL)); 1083 set_default_node_notes(Node_Notes::make(this)); 1084 } 1085 1086 // // -- Initialize types before each compile -- 1087 // // Update cached type information 1088 // if( _method && _method->constants() ) 1089 // Type::update_loaded_types(_method, _method->constants()); 1090 1091 // Init alias_type map. 1092 if (!_do_escape_analysis && aliaslevel == 3) 1093 aliaslevel = 2; // No unique types without escape analysis 1094 _AliasLevel = aliaslevel; 1095 const int grow_ats = 16; 1096 _max_alias_types = grow_ats; 1097 _alias_types = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats); 1098 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, grow_ats); 1099 Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats); 1100 { 1101 for (int i = 0; i < grow_ats; i++) _alias_types[i] = &ats[i]; 1102 } 1103 // Initialize the first few types. 1104 _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL); 1105 _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM); 1106 _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM); 1107 _num_alias_types = AliasIdxRaw+1; 1108 // Zero out the alias type cache. 1109 Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache)); 1110 // A NULL adr_type hits in the cache right away. Preload the right answer. 1111 probe_alias_cache(NULL)->_index = AliasIdxTop; 1112 1113 _intrinsics = NULL; 1114 _macro_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL); 1115 _predicate_opaqs = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL); 1116 _expensive_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL); 1117 register_library_intrinsics(); 1118 } 1119 1120 //---------------------------init_start---------------------------------------- 1121 // Install the StartNode on this compile object. 1122 void Compile::init_start(StartNode* s) { 1123 if (failing()) 1124 return; // already failing 1125 assert(s == start(), ""); 1126 } 1127 1128 StartNode* Compile::start() const { 1129 assert(!failing(), ""); 1130 for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) { 1131 Node* start = root()->fast_out(i); 1132 if( start->is_Start() ) 1133 return start->as_Start(); 1134 } 1135 fatal("Did not find Start node!"); 1136 return NULL; 1137 } 1138 1139 //-------------------------------immutable_memory------------------------------------- 1140 // Access immutable memory 1141 Node* Compile::immutable_memory() { 1142 if (_immutable_memory != NULL) { 1143 return _immutable_memory; 1144 } 1145 StartNode* s = start(); 1146 for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) { 1147 Node *p = s->fast_out(i); 1148 if (p != s && p->as_Proj()->_con == TypeFunc::Memory) { 1149 _immutable_memory = p; 1150 return _immutable_memory; 1151 } 1152 } 1153 ShouldNotReachHere(); 1154 return NULL; 1155 } 1156 1157 //----------------------set_cached_top_node------------------------------------ 1158 // Install the cached top node, and make sure Node::is_top works correctly. 1159 void Compile::set_cached_top_node(Node* tn) { 1160 if (tn != NULL) verify_top(tn); 1161 Node* old_top = _top; 1162 _top = tn; 1163 // Calling Node::setup_is_top allows the nodes the chance to adjust 1164 // their _out arrays. 1165 if (_top != NULL) _top->setup_is_top(); 1166 if (old_top != NULL) old_top->setup_is_top(); 1167 assert(_top == NULL || top()->is_top(), ""); 1168 } 1169 1170 #ifdef ASSERT 1171 uint Compile::count_live_nodes_by_graph_walk() { 1172 Unique_Node_List useful(comp_arena()); 1173 // Get useful node list by walking the graph. 1174 identify_useful_nodes(useful); 1175 return useful.size(); 1176 } 1177 1178 void Compile::print_missing_nodes() { 1179 1180 // Return if CompileLog is NULL and PrintIdealNodeCount is false. 1181 if ((_log == NULL) && (! PrintIdealNodeCount)) { 1182 return; 1183 } 1184 1185 // This is an expensive function. It is executed only when the user 1186 // specifies VerifyIdealNodeCount option or otherwise knows the 1187 // additional work that needs to be done to identify reachable nodes 1188 // by walking the flow graph and find the missing ones using 1189 // _dead_node_list. 1190 1191 Unique_Node_List useful(comp_arena()); 1192 // Get useful node list by walking the graph. 1193 identify_useful_nodes(useful); 1194 1195 uint l_nodes = C->live_nodes(); 1196 uint l_nodes_by_walk = useful.size(); 1197 1198 if (l_nodes != l_nodes_by_walk) { 1199 if (_log != NULL) { 1200 _log->begin_head("mismatched_nodes count='%d'", abs((int) (l_nodes - l_nodes_by_walk))); 1201 _log->stamp(); 1202 _log->end_head(); 1203 } 1204 VectorSet& useful_member_set = useful.member_set(); 1205 int last_idx = l_nodes_by_walk; 1206 for (int i = 0; i < last_idx; i++) { 1207 if (useful_member_set.test(i)) { 1208 if (_dead_node_list.test(i)) { 1209 if (_log != NULL) { 1210 _log->elem("mismatched_node_info node_idx='%d' type='both live and dead'", i); 1211 } 1212 if (PrintIdealNodeCount) { 1213 // Print the log message to tty 1214 tty->print_cr("mismatched_node idx='%d' both live and dead'", i); 1215 useful.at(i)->dump(); 1216 } 1217 } 1218 } 1219 else if (! _dead_node_list.test(i)) { 1220 if (_log != NULL) { 1221 _log->elem("mismatched_node_info node_idx='%d' type='neither live nor dead'", i); 1222 } 1223 if (PrintIdealNodeCount) { 1224 // Print the log message to tty 1225 tty->print_cr("mismatched_node idx='%d' type='neither live nor dead'", i); 1226 } 1227 } 1228 } 1229 if (_log != NULL) { 1230 _log->tail("mismatched_nodes"); 1231 } 1232 } 1233 } 1234 #endif 1235 1236 #ifndef PRODUCT 1237 void Compile::verify_top(Node* tn) const { 1238 if (tn != NULL) { 1239 assert(tn->is_Con(), "top node must be a constant"); 1240 assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type"); 1241 assert(tn->in(0) != NULL, "must have live top node"); 1242 } 1243 } 1244 #endif 1245 1246 1247 ///-------------------Managing Per-Node Debug & Profile Info------------------- 1248 1249 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) { 1250 guarantee(arr != NULL, ""); 1251 int num_blocks = arr->length(); 1252 if (grow_by < num_blocks) grow_by = num_blocks; 1253 int num_notes = grow_by * _node_notes_block_size; 1254 Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes); 1255 Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes)); 1256 while (num_notes > 0) { 1257 arr->append(notes); 1258 notes += _node_notes_block_size; 1259 num_notes -= _node_notes_block_size; 1260 } 1261 assert(num_notes == 0, "exact multiple, please"); 1262 } 1263 1264 bool Compile::copy_node_notes_to(Node* dest, Node* source) { 1265 if (source == NULL || dest == NULL) return false; 1266 1267 if (dest->is_Con()) 1268 return false; // Do not push debug info onto constants. 1269 1270 #ifdef ASSERT 1271 // Leave a bread crumb trail pointing to the original node: 1272 if (dest != NULL && dest != source && dest->debug_orig() == NULL) { 1273 dest->set_debug_orig(source); 1274 } 1275 #endif 1276 1277 if (node_note_array() == NULL) 1278 return false; // Not collecting any notes now. 1279 1280 // This is a copy onto a pre-existing node, which may already have notes. 1281 // If both nodes have notes, do not overwrite any pre-existing notes. 1282 Node_Notes* source_notes = node_notes_at(source->_idx); 1283 if (source_notes == NULL || source_notes->is_clear()) return false; 1284 Node_Notes* dest_notes = node_notes_at(dest->_idx); 1285 if (dest_notes == NULL || dest_notes->is_clear()) { 1286 return set_node_notes_at(dest->_idx, source_notes); 1287 } 1288 1289 Node_Notes merged_notes = (*source_notes); 1290 // The order of operations here ensures that dest notes will win... 1291 merged_notes.update_from(dest_notes); 1292 return set_node_notes_at(dest->_idx, &merged_notes); 1293 } 1294 1295 1296 //--------------------------allow_range_check_smearing------------------------- 1297 // Gating condition for coalescing similar range checks. 1298 // Sometimes we try 'speculatively' replacing a series of a range checks by a 1299 // single covering check that is at least as strong as any of them. 1300 // If the optimization succeeds, the simplified (strengthened) range check 1301 // will always succeed. If it fails, we will deopt, and then give up 1302 // on the optimization. 1303 bool Compile::allow_range_check_smearing() const { 1304 // If this method has already thrown a range-check, 1305 // assume it was because we already tried range smearing 1306 // and it failed. 1307 uint already_trapped = trap_count(Deoptimization::Reason_range_check); 1308 return !already_trapped; 1309 } 1310 1311 1312 //------------------------------flatten_alias_type----------------------------- 1313 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { 1314 int offset = tj->offset(); 1315 TypePtr::PTR ptr = tj->ptr(); 1316 1317 // Known instance (scalarizable allocation) alias only with itself. 1318 bool is_known_inst = tj->isa_oopptr() != NULL && 1319 tj->is_oopptr()->is_known_instance(); 1320 1321 // Process weird unsafe references. 1322 if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) { 1323 assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops"); 1324 assert(!is_known_inst, "scalarizable allocation should not have unsafe references"); 1325 tj = TypeOopPtr::BOTTOM; 1326 ptr = tj->ptr(); 1327 offset = tj->offset(); 1328 } 1329 1330 // Array pointers need some flattening 1331 const TypeAryPtr *ta = tj->isa_aryptr(); 1332 if( ta && is_known_inst ) { 1333 if ( offset != Type::OffsetBot && 1334 offset > arrayOopDesc::length_offset_in_bytes() ) { 1335 offset = Type::OffsetBot; // Flatten constant access into array body only 1336 tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id()); 1337 } 1338 } else if( ta && _AliasLevel >= 2 ) { 1339 // For arrays indexed by constant indices, we flatten the alias 1340 // space to include all of the array body. Only the header, klass 1341 // and array length can be accessed un-aliased. 1342 if( offset != Type::OffsetBot ) { 1343 if( ta->const_oop() ) { // methodDataOop or methodOop 1344 offset = Type::OffsetBot; // Flatten constant access into array body 1345 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset); 1346 } else if( offset == arrayOopDesc::length_offset_in_bytes() ) { 1347 // range is OK as-is. 1348 tj = ta = TypeAryPtr::RANGE; 1349 } else if( offset == oopDesc::klass_offset_in_bytes() ) { 1350 tj = TypeInstPtr::KLASS; // all klass loads look alike 1351 ta = TypeAryPtr::RANGE; // generic ignored junk 1352 ptr = TypePtr::BotPTR; 1353 } else if( offset == oopDesc::mark_offset_in_bytes() ) { 1354 tj = TypeInstPtr::MARK; 1355 ta = TypeAryPtr::RANGE; // generic ignored junk 1356 ptr = TypePtr::BotPTR; 1357 } else { // Random constant offset into array body 1358 offset = Type::OffsetBot; // Flatten constant access into array body 1359 tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset); 1360 } 1361 } 1362 // Arrays of fixed size alias with arrays of unknown size. 1363 if (ta->size() != TypeInt::POS) { 1364 const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS); 1365 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset); 1366 } 1367 // Arrays of known objects become arrays of unknown objects. 1368 if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) { 1369 const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size()); 1370 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset); 1371 } 1372 if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) { 1373 const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size()); 1374 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset); 1375 } 1376 // Arrays of bytes and of booleans both use 'bastore' and 'baload' so 1377 // cannot be distinguished by bytecode alone. 1378 if (ta->elem() == TypeInt::BOOL) { 1379 const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size()); 1380 ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE); 1381 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset); 1382 } 1383 // During the 2nd round of IterGVN, NotNull castings are removed. 1384 // Make sure the Bottom and NotNull variants alias the same. 1385 // Also, make sure exact and non-exact variants alias the same. 1386 if( ptr == TypePtr::NotNull || ta->klass_is_exact() ) { 1387 tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset); 1388 } 1389 } 1390 1391 // Oop pointers need some flattening 1392 const TypeInstPtr *to = tj->isa_instptr(); 1393 if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) { 1394 ciInstanceKlass *k = to->klass()->as_instance_klass(); 1395 if( ptr == TypePtr::Constant ) { 1396 if (to->klass() != ciEnv::current()->Class_klass() || 1397 offset < k->size_helper() * wordSize) { 1398 // No constant oop pointers (such as Strings); they alias with 1399 // unknown strings. 1400 assert(!is_known_inst, "not scalarizable allocation"); 1401 tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset); 1402 } 1403 } else if( is_known_inst ) { 1404 tj = to; // Keep NotNull and klass_is_exact for instance type 1405 } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) { 1406 // During the 2nd round of IterGVN, NotNull castings are removed. 1407 // Make sure the Bottom and NotNull variants alias the same. 1408 // Also, make sure exact and non-exact variants alias the same. 1409 tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset); 1410 } 1411 // Canonicalize the holder of this field 1412 if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) { 1413 // First handle header references such as a LoadKlassNode, even if the 1414 // object's klass is unloaded at compile time (4965979). 1415 if (!is_known_inst) { // Do it only for non-instance types 1416 tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset); 1417 } 1418 } else if (offset < 0 || offset >= k->size_helper() * wordSize) { 1419 // Static fields are in the space above the normal instance 1420 // fields in the java.lang.Class instance. 1421 if (to->klass() != ciEnv::current()->Class_klass()) { 1422 to = NULL; 1423 tj = TypeOopPtr::BOTTOM; 1424 offset = tj->offset(); 1425 } 1426 } else { 1427 ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset); 1428 if (!k->equals(canonical_holder) || tj->offset() != offset) { 1429 if( is_known_inst ) { 1430 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id()); 1431 } else { 1432 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset); 1433 } 1434 } 1435 } 1436 } 1437 1438 // Klass pointers to object array klasses need some flattening 1439 const TypeKlassPtr *tk = tj->isa_klassptr(); 1440 if( tk ) { 1441 // If we are referencing a field within a Klass, we need 1442 // to assume the worst case of an Object. Both exact and 1443 // inexact types must flatten to the same alias class so 1444 // use NotNull as the PTR. 1445 if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) { 1446 1447 tj = tk = TypeKlassPtr::make(TypePtr::NotNull, 1448 TypeKlassPtr::OBJECT->klass(), 1449 offset); 1450 } 1451 1452 ciKlass* klass = tk->klass(); 1453 if( klass->is_obj_array_klass() ) { 1454 ciKlass* k = TypeAryPtr::OOPS->klass(); 1455 if( !k || !k->is_loaded() ) // Only fails for some -Xcomp runs 1456 k = TypeInstPtr::BOTTOM->klass(); 1457 tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset ); 1458 } 1459 1460 // Check for precise loads from the primary supertype array and force them 1461 // to the supertype cache alias index. Check for generic array loads from 1462 // the primary supertype array and also force them to the supertype cache 1463 // alias index. Since the same load can reach both, we need to merge 1464 // these 2 disparate memories into the same alias class. Since the 1465 // primary supertype array is read-only, there's no chance of confusion 1466 // where we bypass an array load and an array store. 1467 int primary_supers_offset = in_bytes(Klass::primary_supers_offset()); 1468 if (offset == Type::OffsetBot || 1469 (offset >= primary_supers_offset && 1470 offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) || 1471 offset == (int)in_bytes(Klass::secondary_super_cache_offset())) { 1472 offset = in_bytes(Klass::secondary_super_cache_offset()); 1473 tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset ); 1474 } 1475 } 1476 1477 // Flatten all Raw pointers together. 1478 if (tj->base() == Type::RawPtr) 1479 tj = TypeRawPtr::BOTTOM; 1480 1481 if (tj->base() == Type::AnyPtr) 1482 tj = TypePtr::BOTTOM; // An error, which the caller must check for. 1483 1484 // Flatten all to bottom for now 1485 switch( _AliasLevel ) { 1486 case 0: 1487 tj = TypePtr::BOTTOM; 1488 break; 1489 case 1: // Flatten to: oop, static, field or array 1490 switch (tj->base()) { 1491 //case Type::AryPtr: tj = TypeAryPtr::RANGE; break; 1492 case Type::RawPtr: tj = TypeRawPtr::BOTTOM; break; 1493 case Type::AryPtr: // do not distinguish arrays at all 1494 case Type::InstPtr: tj = TypeInstPtr::BOTTOM; break; 1495 case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break; 1496 case Type::AnyPtr: tj = TypePtr::BOTTOM; break; // caller checks it 1497 default: ShouldNotReachHere(); 1498 } 1499 break; 1500 case 2: // No collapsing at level 2; keep all splits 1501 case 3: // No collapsing at level 3; keep all splits 1502 break; 1503 default: 1504 Unimplemented(); 1505 } 1506 1507 offset = tj->offset(); 1508 assert( offset != Type::OffsetTop, "Offset has fallen from constant" ); 1509 1510 assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) || 1511 (offset == Type::OffsetBot && tj->base() == Type::AryPtr) || 1512 (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) || 1513 (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) || 1514 (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) || 1515 (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) || 1516 (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr) , 1517 "For oops, klasses, raw offset must be constant; for arrays the offset is never known" ); 1518 assert( tj->ptr() != TypePtr::TopPTR && 1519 tj->ptr() != TypePtr::AnyNull && 1520 tj->ptr() != TypePtr::Null, "No imprecise addresses" ); 1521 // assert( tj->ptr() != TypePtr::Constant || 1522 // tj->base() == Type::RawPtr || 1523 // tj->base() == Type::KlassPtr, "No constant oop addresses" ); 1524 1525 return tj; 1526 } 1527 1528 void Compile::AliasType::Init(int i, const TypePtr* at) { 1529 _index = i; 1530 _adr_type = at; 1531 _field = NULL; 1532 _is_rewritable = true; // default 1533 const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL; 1534 if (atoop != NULL && atoop->is_known_instance()) { 1535 const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot); 1536 _general_index = Compile::current()->get_alias_index(gt); 1537 } else { 1538 _general_index = 0; 1539 } 1540 } 1541 1542 //---------------------------------print_on------------------------------------ 1543 #ifndef PRODUCT 1544 void Compile::AliasType::print_on(outputStream* st) { 1545 if (index() < 10) 1546 st->print("@ <%d> ", index()); 1547 else st->print("@ <%d>", index()); 1548 st->print(is_rewritable() ? " " : " RO"); 1549 int offset = adr_type()->offset(); 1550 if (offset == Type::OffsetBot) 1551 st->print(" +any"); 1552 else st->print(" +%-3d", offset); 1553 st->print(" in "); 1554 adr_type()->dump_on(st); 1555 const TypeOopPtr* tjp = adr_type()->isa_oopptr(); 1556 if (field() != NULL && tjp) { 1557 if (tjp->klass() != field()->holder() || 1558 tjp->offset() != field()->offset_in_bytes()) { 1559 st->print(" != "); 1560 field()->print(); 1561 st->print(" ***"); 1562 } 1563 } 1564 } 1565 1566 void print_alias_types() { 1567 Compile* C = Compile::current(); 1568 tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1); 1569 for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) { 1570 C->alias_type(idx)->print_on(tty); 1571 tty->cr(); 1572 } 1573 } 1574 #endif 1575 1576 1577 //----------------------------probe_alias_cache-------------------------------- 1578 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) { 1579 intptr_t key = (intptr_t) adr_type; 1580 key ^= key >> logAliasCacheSize; 1581 return &_alias_cache[key & right_n_bits(logAliasCacheSize)]; 1582 } 1583 1584 1585 //-----------------------------grow_alias_types-------------------------------- 1586 void Compile::grow_alias_types() { 1587 const int old_ats = _max_alias_types; // how many before? 1588 const int new_ats = old_ats; // how many more? 1589 const int grow_ats = old_ats+new_ats; // how many now? 1590 _max_alias_types = grow_ats; 1591 _alias_types = REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats); 1592 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats); 1593 Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats); 1594 for (int i = 0; i < new_ats; i++) _alias_types[old_ats+i] = &ats[i]; 1595 } 1596 1597 1598 //--------------------------------find_alias_type------------------------------ 1599 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) { 1600 if (_AliasLevel == 0) 1601 return alias_type(AliasIdxBot); 1602 1603 AliasCacheEntry* ace = probe_alias_cache(adr_type); 1604 if (ace->_adr_type == adr_type) { 1605 return alias_type(ace->_index); 1606 } 1607 1608 // Handle special cases. 1609 if (adr_type == NULL) return alias_type(AliasIdxTop); 1610 if (adr_type == TypePtr::BOTTOM) return alias_type(AliasIdxBot); 1611 1612 // Do it the slow way. 1613 const TypePtr* flat = flatten_alias_type(adr_type); 1614 1615 #ifdef ASSERT 1616 assert(flat == flatten_alias_type(flat), "idempotent"); 1617 assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr"); 1618 if (flat->isa_oopptr() && !flat->isa_klassptr()) { 1619 const TypeOopPtr* foop = flat->is_oopptr(); 1620 // Scalarizable allocations have exact klass always. 1621 bool exact = !foop->klass_is_exact() || foop->is_known_instance(); 1622 const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr(); 1623 assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type"); 1624 } 1625 assert(flat == flatten_alias_type(flat), "exact bit doesn't matter"); 1626 #endif 1627 1628 int idx = AliasIdxTop; 1629 for (int i = 0; i < num_alias_types(); i++) { 1630 if (alias_type(i)->adr_type() == flat) { 1631 idx = i; 1632 break; 1633 } 1634 } 1635 1636 if (idx == AliasIdxTop) { 1637 if (no_create) return NULL; 1638 // Grow the array if necessary. 1639 if (_num_alias_types == _max_alias_types) grow_alias_types(); 1640 // Add a new alias type. 1641 idx = _num_alias_types++; 1642 _alias_types[idx]->Init(idx, flat); 1643 if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false); 1644 if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false); 1645 if (flat->isa_instptr()) { 1646 if (flat->offset() == java_lang_Class::klass_offset_in_bytes() 1647 && flat->is_instptr()->klass() == env()->Class_klass()) 1648 alias_type(idx)->set_rewritable(false); 1649 } 1650 if (flat->isa_klassptr()) { 1651 if (flat->offset() == in_bytes(Klass::super_check_offset_offset())) 1652 alias_type(idx)->set_rewritable(false); 1653 if (flat->offset() == in_bytes(Klass::modifier_flags_offset())) 1654 alias_type(idx)->set_rewritable(false); 1655 if (flat->offset() == in_bytes(Klass::access_flags_offset())) 1656 alias_type(idx)->set_rewritable(false); 1657 if (flat->offset() == in_bytes(Klass::java_mirror_offset())) 1658 alias_type(idx)->set_rewritable(false); 1659 } 1660 // %%% (We would like to finalize JavaThread::threadObj_offset(), 1661 // but the base pointer type is not distinctive enough to identify 1662 // references into JavaThread.) 1663 1664 // Check for final fields. 1665 const TypeInstPtr* tinst = flat->isa_instptr(); 1666 if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) { 1667 ciField* field; 1668 if (tinst->const_oop() != NULL && 1669 tinst->klass() == ciEnv::current()->Class_klass() && 1670 tinst->offset() >= (tinst->klass()->as_instance_klass()->size_helper() * wordSize)) { 1671 // static field 1672 ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass(); 1673 field = k->get_field_by_offset(tinst->offset(), true); 1674 } else { 1675 ciInstanceKlass *k = tinst->klass()->as_instance_klass(); 1676 field = k->get_field_by_offset(tinst->offset(), false); 1677 } 1678 assert(field == NULL || 1679 original_field == NULL || 1680 (field->holder() == original_field->holder() && 1681 field->offset() == original_field->offset() && 1682 field->is_static() == original_field->is_static()), "wrong field?"); 1683 // Set field() and is_rewritable() attributes. 1684 if (field != NULL) alias_type(idx)->set_field(field); 1685 } 1686 } 1687 1688 // Fill the cache for next time. 1689 ace->_adr_type = adr_type; 1690 ace->_index = idx; 1691 assert(alias_type(adr_type) == alias_type(idx), "type must be installed"); 1692 1693 // Might as well try to fill the cache for the flattened version, too. 1694 AliasCacheEntry* face = probe_alias_cache(flat); 1695 if (face->_adr_type == NULL) { 1696 face->_adr_type = flat; 1697 face->_index = idx; 1698 assert(alias_type(flat) == alias_type(idx), "flat type must work too"); 1699 } 1700 1701 return alias_type(idx); 1702 } 1703 1704 1705 Compile::AliasType* Compile::alias_type(ciField* field) { 1706 const TypeOopPtr* t; 1707 if (field->is_static()) 1708 t = TypeInstPtr::make(field->holder()->java_mirror()); 1709 else 1710 t = TypeOopPtr::make_from_klass_raw(field->holder()); 1711 AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field); 1712 assert(field->is_final() == !atp->is_rewritable(), "must get the rewritable bits correct"); 1713 return atp; 1714 } 1715 1716 1717 //------------------------------have_alias_type-------------------------------- 1718 bool Compile::have_alias_type(const TypePtr* adr_type) { 1719 AliasCacheEntry* ace = probe_alias_cache(adr_type); 1720 if (ace->_adr_type == adr_type) { 1721 return true; 1722 } 1723 1724 // Handle special cases. 1725 if (adr_type == NULL) return true; 1726 if (adr_type == TypePtr::BOTTOM) return true; 1727 1728 return find_alias_type(adr_type, true, NULL) != NULL; 1729 } 1730 1731 //-----------------------------must_alias-------------------------------------- 1732 // True if all values of the given address type are in the given alias category. 1733 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) { 1734 if (alias_idx == AliasIdxBot) return true; // the universal category 1735 if (adr_type == NULL) return true; // NULL serves as TypePtr::TOP 1736 if (alias_idx == AliasIdxTop) return false; // the empty category 1737 if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins 1738 1739 // the only remaining possible overlap is identity 1740 int adr_idx = get_alias_index(adr_type); 1741 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, ""); 1742 assert(adr_idx == alias_idx || 1743 (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM 1744 && adr_type != TypeOopPtr::BOTTOM), 1745 "should not be testing for overlap with an unsafe pointer"); 1746 return adr_idx == alias_idx; 1747 } 1748 1749 //------------------------------can_alias-------------------------------------- 1750 // True if any values of the given address type are in the given alias category. 1751 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) { 1752 if (alias_idx == AliasIdxTop) return false; // the empty category 1753 if (adr_type == NULL) return false; // NULL serves as TypePtr::TOP 1754 if (alias_idx == AliasIdxBot) return true; // the universal category 1755 if (adr_type->base() == Type::AnyPtr) return true; // TypePtr::BOTTOM or its twins 1756 1757 // the only remaining possible overlap is identity 1758 int adr_idx = get_alias_index(adr_type); 1759 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, ""); 1760 return adr_idx == alias_idx; 1761 } 1762 1763 1764 1765 //---------------------------pop_warm_call------------------------------------- 1766 WarmCallInfo* Compile::pop_warm_call() { 1767 WarmCallInfo* wci = _warm_calls; 1768 if (wci != NULL) _warm_calls = wci->remove_from(wci); 1769 return wci; 1770 } 1771 1772 //----------------------------Inline_Warm-------------------------------------- 1773 int Compile::Inline_Warm() { 1774 // If there is room, try to inline some more warm call sites. 1775 // %%% Do a graph index compaction pass when we think we're out of space? 1776 if (!InlineWarmCalls) return 0; 1777 1778 int calls_made_hot = 0; 1779 int room_to_grow = NodeCountInliningCutoff - unique(); 1780 int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep); 1781 int amount_grown = 0; 1782 WarmCallInfo* call; 1783 while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) { 1784 int est_size = (int)call->size(); 1785 if (est_size > (room_to_grow - amount_grown)) { 1786 // This one won't fit anyway. Get rid of it. 1787 call->make_cold(); 1788 continue; 1789 } 1790 call->make_hot(); 1791 calls_made_hot++; 1792 amount_grown += est_size; 1793 amount_to_grow -= est_size; 1794 } 1795 1796 if (calls_made_hot > 0) set_major_progress(); 1797 return calls_made_hot; 1798 } 1799 1800 1801 //----------------------------Finish_Warm-------------------------------------- 1802 void Compile::Finish_Warm() { 1803 if (!InlineWarmCalls) return; 1804 if (failing()) return; 1805 if (warm_calls() == NULL) return; 1806 1807 // Clean up loose ends, if we are out of space for inlining. 1808 WarmCallInfo* call; 1809 while ((call = pop_warm_call()) != NULL) { 1810 call->make_cold(); 1811 } 1812 } 1813 1814 //---------------------cleanup_loop_predicates----------------------- 1815 // Remove the opaque nodes that protect the predicates so that all unused 1816 // checks and uncommon_traps will be eliminated from the ideal graph 1817 void Compile::cleanup_loop_predicates(PhaseIterGVN &igvn) { 1818 if (predicate_count()==0) return; 1819 for (int i = predicate_count(); i > 0; i--) { 1820 Node * n = predicate_opaque1_node(i-1); 1821 assert(n->Opcode() == Op_Opaque1, "must be"); 1822 igvn.replace_node(n, n->in(1)); 1823 } 1824 assert(predicate_count()==0, "should be clean!"); 1825 } 1826 1827 // StringOpts and late inlining of string methods 1828 void Compile::inline_string_calls(bool parse_time) { 1829 { 1830 // remove useless nodes to make the usage analysis simpler 1831 ResourceMark rm; 1832 PhaseRemoveUseless pru(initial_gvn(), for_igvn()); 1833 } 1834 1835 { 1836 ResourceMark rm; 1837 print_method(PHASE_BEFORE_STRINGOPTS, 3); 1838 PhaseStringOpts pso(initial_gvn(), for_igvn()); 1839 print_method(PHASE_AFTER_STRINGOPTS, 3); 1840 } 1841 1842 // now inline anything that we skipped the first time around 1843 if (!parse_time) { 1844 _late_inlines_pos = _late_inlines.length(); 1845 } 1846 1847 while (_string_late_inlines.length() > 0) { 1848 CallGenerator* cg = _string_late_inlines.pop(); 1849 cg->do_late_inline(); 1850 if (failing()) return; 1851 } 1852 _string_late_inlines.trunc_to(0); 1853 } 1854 1855 void Compile::inline_incrementally_one(PhaseIterGVN& igvn) { 1856 assert(IncrementalInline, "incremental inlining should be on"); 1857 PhaseGVN* gvn = initial_gvn(); 1858 1859 set_inlining_progress(false); 1860 for_igvn()->clear(); 1861 gvn->replace_with(&igvn); 1862 1863 int i = 0; 1864 1865 for (; i <_late_inlines.length() && !inlining_progress(); i++) { 1866 CallGenerator* cg = _late_inlines.at(i); 1867 _late_inlines_pos = i+1; 1868 cg->do_late_inline(); 1869 if (failing()) return; 1870 } 1871 int j = 0; 1872 for (; i < _late_inlines.length(); i++, j++) { 1873 _late_inlines.at_put(j, _late_inlines.at(i)); 1874 } 1875 _late_inlines.trunc_to(j); 1876 1877 { 1878 ResourceMark rm; 1879 PhaseRemoveUseless pru(C->initial_gvn(), C->for_igvn()); 1880 } 1881 1882 igvn = PhaseIterGVN(gvn); 1883 } 1884 1885 // Perform incremental inlining until bound on number of live nodes is reached 1886 void Compile::inline_incrementally(PhaseIterGVN& igvn) { 1887 PhaseGVN* gvn = initial_gvn(); 1888 1889 set_inlining_incrementally(true); 1890 set_inlining_progress(true); 1891 uint low_live_nodes = 0; 1892 1893 while(inlining_progress() && _late_inlines.length() > 0) { 1894 1895 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) { 1896 if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) { 1897 // PhaseIdealLoop is expensive so we only try it once we are 1898 // out of loop and we only try it again if the previous helped 1899 // got the number of nodes down significantly 1900 PhaseIdealLoop ideal_loop( igvn, false, true ); 1901 if (failing()) return; 1902 low_live_nodes = live_nodes(); 1903 _major_progress = true; 1904 } 1905 1906 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) { 1907 break; 1908 } 1909 } 1910 1911 inline_incrementally_one(igvn); 1912 1913 if (failing()) return; 1914 1915 igvn.optimize(); 1916 1917 if (failing()) return; 1918 } 1919 1920 assert( igvn._worklist.size() == 0, "should be done with igvn" ); 1921 1922 if (_string_late_inlines.length() > 0) { 1923 assert(has_stringbuilder(), "inconsistent"); 1924 for_igvn()->clear(); 1925 initial_gvn()->replace_with(&igvn); 1926 1927 inline_string_calls(false); 1928 1929 if (failing()) return; 1930 1931 { 1932 ResourceMark rm; 1933 PhaseRemoveUseless pru(initial_gvn(), for_igvn()); 1934 } 1935 1936 igvn = PhaseIterGVN(gvn); 1937 1938 igvn.optimize(); 1939 } 1940 1941 set_inlining_incrementally(false); 1942 } 1943 1944 1945 //------------------------------Optimize--------------------------------------- 1946 // Given a graph, optimize it. 1947 void Compile::Optimize() { 1948 TracePhase t1("optimizer", &_t_optimizer, true); 1949 1950 #ifndef PRODUCT 1951 if (env()->break_at_compile()) { 1952 BREAKPOINT; 1953 } 1954 1955 #endif 1956 1957 ResourceMark rm; 1958 int loop_opts_cnt; 1959 1960 NOT_PRODUCT( verify_graph_edges(); ) 1961 1962 print_method(PHASE_AFTER_PARSING); 1963 1964 { 1965 // Iterative Global Value Numbering, including ideal transforms 1966 // Initialize IterGVN with types and values from parse-time GVN 1967 PhaseIterGVN igvn(initial_gvn()); 1968 { 1969 NOT_PRODUCT( TracePhase t2("iterGVN", &_t_iterGVN, TimeCompiler); ) 1970 igvn.optimize(); 1971 } 1972 1973 print_method(PHASE_ITER_GVN1, 2); 1974 1975 if (failing()) return; 1976 1977 inline_incrementally(igvn); 1978 1979 print_method(PHASE_INCREMENTAL_INLINE, 2); 1980 1981 if (failing()) return; 1982 1983 // No more new expensive nodes will be added to the list from here 1984 // so keep only the actual candidates for optimizations. 1985 cleanup_expensive_nodes(igvn); 1986 1987 // Perform escape analysis 1988 if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) { 1989 if (has_loops()) { 1990 // Cleanup graph (remove dead nodes). 1991 TracePhase t2("idealLoop", &_t_idealLoop, true); 1992 PhaseIdealLoop ideal_loop( igvn, false, true ); 1993 if (major_progress()) print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2); 1994 if (failing()) return; 1995 } 1996 ConnectionGraph::do_analysis(this, &igvn); 1997 1998 if (failing()) return; 1999 2000 // Optimize out fields loads from scalar replaceable allocations. 2001 igvn.optimize(); 2002 print_method(PHASE_ITER_GVN_AFTER_EA, 2); 2003 2004 if (failing()) return; 2005 2006 if (congraph() != NULL && macro_count() > 0) { 2007 NOT_PRODUCT( TracePhase t2("macroEliminate", &_t_macroEliminate, TimeCompiler); ) 2008 PhaseMacroExpand mexp(igvn); 2009 mexp.eliminate_macro_nodes(); 2010 igvn.set_delay_transform(false); 2011 2012 igvn.optimize(); 2013 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2); 2014 2015 if (failing()) return; 2016 } 2017 } 2018 2019 // Loop transforms on the ideal graph. Range Check Elimination, 2020 // peeling, unrolling, etc. 2021 2022 // Set loop opts counter 2023 loop_opts_cnt = num_loop_opts(); 2024 if((loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) { 2025 { 2026 TracePhase t2("idealLoop", &_t_idealLoop, true); 2027 PhaseIdealLoop ideal_loop( igvn, true ); 2028 loop_opts_cnt--; 2029 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2); 2030 if (failing()) return; 2031 } 2032 // Loop opts pass if partial peeling occurred in previous pass 2033 if(PartialPeelLoop && major_progress() && (loop_opts_cnt > 0)) { 2034 TracePhase t3("idealLoop", &_t_idealLoop, true); 2035 PhaseIdealLoop ideal_loop( igvn, false ); 2036 loop_opts_cnt--; 2037 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2); 2038 if (failing()) return; 2039 } 2040 // Loop opts pass for loop-unrolling before CCP 2041 if(major_progress() && (loop_opts_cnt > 0)) { 2042 TracePhase t4("idealLoop", &_t_idealLoop, true); 2043 PhaseIdealLoop ideal_loop( igvn, false ); 2044 loop_opts_cnt--; 2045 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2); 2046 } 2047 if (!failing()) { 2048 // Verify that last round of loop opts produced a valid graph 2049 NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); ) 2050 PhaseIdealLoop::verify(igvn); 2051 } 2052 } 2053 if (failing()) return; 2054 2055 // Conditional Constant Propagation; 2056 PhaseCCP ccp( &igvn ); 2057 assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)"); 2058 { 2059 TracePhase t2("ccp", &_t_ccp, true); 2060 ccp.do_transform(); 2061 } 2062 print_method(PHASE_CPP1, 2); 2063 2064 assert( true, "Break here to ccp.dump_old2new_map()"); 2065 2066 // Iterative Global Value Numbering, including ideal transforms 2067 { 2068 NOT_PRODUCT( TracePhase t2("iterGVN2", &_t_iterGVN2, TimeCompiler); ) 2069 igvn = ccp; 2070 igvn.optimize(); 2071 } 2072 2073 print_method(PHASE_ITER_GVN2, 2); 2074 2075 if (failing()) return; 2076 2077 // Loop transforms on the ideal graph. Range Check Elimination, 2078 // peeling, unrolling, etc. 2079 if(loop_opts_cnt > 0) { 2080 debug_only( int cnt = 0; ); 2081 while(major_progress() && (loop_opts_cnt > 0)) { 2082 TracePhase t2("idealLoop", &_t_idealLoop, true); 2083 assert( cnt++ < 40, "infinite cycle in loop optimization" ); 2084 PhaseIdealLoop ideal_loop( igvn, true); 2085 loop_opts_cnt--; 2086 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2); 2087 if (failing()) return; 2088 } 2089 } 2090 2091 { 2092 // Verify that all previous optimizations produced a valid graph 2093 // at least to this point, even if no loop optimizations were done. 2094 NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); ) 2095 PhaseIdealLoop::verify(igvn); 2096 } 2097 2098 { 2099 NOT_PRODUCT( TracePhase t2("macroExpand", &_t_macroExpand, TimeCompiler); ) 2100 PhaseMacroExpand mex(igvn); 2101 if (mex.expand_macro_nodes()) { 2102 assert(failing(), "must bail out w/ explicit message"); 2103 return; 2104 } 2105 } 2106 2107 } // (End scope of igvn; run destructor if necessary for asserts.) 2108 2109 dump_inlining(); 2110 // A method with only infinite loops has no edges entering loops from root 2111 { 2112 NOT_PRODUCT( TracePhase t2("graphReshape", &_t_graphReshaping, TimeCompiler); ) 2113 if (final_graph_reshaping()) { 2114 assert(failing(), "must bail out w/ explicit message"); 2115 return; 2116 } 2117 } 2118 2119 print_method(PHASE_OPTIMIZE_FINISHED, 2); 2120 } 2121 2122 2123 //------------------------------Code_Gen--------------------------------------- 2124 // Given a graph, generate code for it 2125 void Compile::Code_Gen() { 2126 if (failing()) return; 2127 2128 // Perform instruction selection. You might think we could reclaim Matcher 2129 // memory PDQ, but actually the Matcher is used in generating spill code. 2130 // Internals of the Matcher (including some VectorSets) must remain live 2131 // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage 2132 // set a bit in reclaimed memory. 2133 2134 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine 2135 // nodes. Mapping is only valid at the root of each matched subtree. 2136 NOT_PRODUCT( verify_graph_edges(); ) 2137 2138 Node_List proj_list; 2139 Matcher m(proj_list); 2140 _matcher = &m; 2141 { 2142 TracePhase t2("matcher", &_t_matcher, true); 2143 m.match(); 2144 } 2145 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine 2146 // nodes. Mapping is only valid at the root of each matched subtree. 2147 NOT_PRODUCT( verify_graph_edges(); ) 2148 2149 // If you have too many nodes, or if matching has failed, bail out 2150 check_node_count(0, "out of nodes matching instructions"); 2151 if (failing()) return; 2152 2153 // Platform dependent post matching hook (used on ppc). 2154 PdCompile::pd_post_matching_hook(this); 2155 2156 // Build a proper-looking CFG 2157 PhaseCFG cfg(node_arena(), root(), m); 2158 _cfg = &cfg; 2159 { 2160 NOT_PRODUCT( TracePhase t2("scheduler", &_t_scheduler, TimeCompiler); ) 2161 cfg.Dominators(); 2162 if (failing()) return; 2163 2164 NOT_PRODUCT( verify_graph_edges(); ) 2165 2166 cfg.Estimate_Block_Frequency(); 2167 cfg.GlobalCodeMotion(m,unique(),proj_list); 2168 if (failing()) return; 2169 2170 print_method(PHASE_GLOBAL_CODE_MOTION, 2); 2171 2172 NOT_PRODUCT( verify_graph_edges(); ) 2173 2174 debug_only( cfg.verify(); ) 2175 } 2176 NOT_PRODUCT( verify_graph_edges(); ) 2177 2178 PhaseChaitin regalloc(unique(),cfg,m); 2179 _regalloc = ®alloc; 2180 { 2181 TracePhase t2("regalloc", &_t_registerAllocation, true); 2182 // Perform any platform dependent preallocation actions. This is used, 2183 // for example, to avoid taking an implicit null pointer exception 2184 // using the frame pointer on win95. 2185 _regalloc->pd_preallocate_hook(); 2186 2187 // Perform register allocation. After Chaitin, use-def chains are 2188 // no longer accurate (at spill code) and so must be ignored. 2189 // Node->LRG->reg mappings are still accurate. 2190 _regalloc->Register_Allocate(); 2191 2192 // Bail out if the allocator builds too many nodes 2193 if (failing()) return; 2194 } 2195 2196 // Prior to register allocation we kept empty basic blocks in case the 2197 // the allocator needed a place to spill. After register allocation we 2198 // are not adding any new instructions. If any basic block is empty, we 2199 // can now safely remove it. 2200 { 2201 NOT_PRODUCT( TracePhase t2("blockOrdering", &_t_blockOrdering, TimeCompiler); ) 2202 cfg.remove_empty(); 2203 if (do_freq_based_layout()) { 2204 PhaseBlockLayout layout(cfg); 2205 } else { 2206 cfg.set_loop_alignment(); 2207 } 2208 cfg.fixup_flow(); 2209 } 2210 2211 // Perform any platform dependent postallocation verifications. 2212 debug_only( _regalloc->pd_postallocate_verify_hook(); ) 2213 2214 // Apply peephole optimizations 2215 if( OptoPeephole ) { 2216 NOT_PRODUCT( TracePhase t2("peephole", &_t_peephole, TimeCompiler); ) 2217 PhasePeephole peep( _regalloc, cfg); 2218 peep.do_transform(); 2219 } 2220 2221 // Do late expand if CPU requires this. 2222 if (Matcher::require_late_expand) { 2223 cfg.LateExpand(_regalloc); 2224 } 2225 2226 // Convert Nodes to instruction bits in a buffer 2227 { 2228 // %%%% workspace merge brought two timers together for one job 2229 TracePhase t2a("output", &_t_output, true); 2230 NOT_PRODUCT( TraceTime t2b(NULL, &_t_codeGeneration, TimeCompiler, false); ) 2231 Output(); 2232 } 2233 2234 print_method(PHASE_FINAL_CODE); 2235 2236 // He's dead, Jim. 2237 _cfg = (PhaseCFG*)0xdeadbeef; 2238 _regalloc = (PhaseChaitin*)0xdeadbeef; 2239 } 2240 2241 2242 //------------------------------dump_asm--------------------------------------- 2243 // Dump formatted assembly 2244 #ifndef PRODUCT 2245 void Compile::dump_asm(int *pcs, uint pc_limit) { 2246 bool cut_short = false; 2247 tty->print_cr("#"); 2248 tty->print("# "); _tf->dump(); tty->cr(); 2249 tty->print_cr("#"); 2250 2251 // For all blocks 2252 int pc = 0x0; // Program counter 2253 char starts_bundle = ' '; 2254 _regalloc->dump_frame(); 2255 2256 Node *n = NULL; 2257 for( uint i=0; i<_cfg->_num_blocks; i++ ) { 2258 if (VMThread::should_terminate()) { cut_short = true; break; } 2259 Block *b = _cfg->_blocks[i]; 2260 if (b->is_connector() && !Verbose) continue; 2261 n = b->_nodes[0]; 2262 if (pcs && n->_idx < pc_limit) 2263 tty->print("%3.3x ", pcs[n->_idx]); 2264 else 2265 tty->print(" "); 2266 b->dump_head( &_cfg->_bbs ); 2267 if (b->is_connector()) { 2268 tty->print_cr(" # Empty connector block"); 2269 } else if (b->num_preds() == 2 && b->pred(1)->is_CatchProj() && b->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) { 2270 tty->print_cr(" # Block is sole successor of call"); 2271 } 2272 2273 // For all instructions 2274 Node *delay = NULL; 2275 for( uint j = 0; j<b->_nodes.size(); j++ ) { 2276 if (VMThread::should_terminate()) { cut_short = true; break; } 2277 n = b->_nodes[j]; 2278 if (valid_bundle_info(n)) { 2279 Bundle *bundle = node_bundling(n); 2280 if (bundle->used_in_unconditional_delay()) { 2281 delay = n; 2282 continue; 2283 } 2284 if (bundle->starts_bundle()) 2285 starts_bundle = '+'; 2286 } 2287 2288 if (WizardMode) n->dump(); 2289 2290 if( !n->is_Region() && // Dont print in the Assembly 2291 !n->is_Phi() && // a few noisely useless nodes 2292 !n->is_Proj() && 2293 !n->is_MachTemp() && 2294 !n->is_SafePointScalarObject() && 2295 !n->is_Catch() && // Would be nice to print exception table targets 2296 !n->is_MergeMem() && // Not very interesting 2297 !n->is_top() && // Debug info table constants 2298 !(n->is_Con() && !n->is_Mach())// Debug info table constants 2299 ) { 2300 if (pcs && n->_idx < pc_limit) 2301 tty->print("%3.3x", pcs[n->_idx]); 2302 else 2303 tty->print(" "); 2304 tty->print(" %c ", starts_bundle); 2305 starts_bundle = ' '; 2306 tty->print("\t"); 2307 n->format(_regalloc, tty); 2308 tty->cr(); 2309 } 2310 2311 // If we have an instruction with a delay slot, and have seen a delay, 2312 // then back up and print it 2313 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) { 2314 assert(delay != NULL, "no unconditional delay instruction"); 2315 if (WizardMode) delay->dump(); 2316 2317 if (node_bundling(delay)->starts_bundle()) 2318 starts_bundle = '+'; 2319 if (pcs && n->_idx < pc_limit) 2320 tty->print("%3.3x", pcs[n->_idx]); 2321 else 2322 tty->print(" "); 2323 tty->print(" %c ", starts_bundle); 2324 starts_bundle = ' '; 2325 tty->print("\t"); 2326 delay->format(_regalloc, tty); 2327 tty->print_cr(""); 2328 delay = NULL; 2329 } 2330 2331 // Dump the exception table as well 2332 if( n->is_Catch() && (Verbose || WizardMode) ) { 2333 // Print the exception table for this offset 2334 _handler_table.print_subtable_for(pc); 2335 } 2336 } 2337 2338 if (pcs && n->_idx < pc_limit) 2339 tty->print_cr("%3.3x", pcs[n->_idx]); 2340 else 2341 tty->print_cr(""); 2342 2343 assert(cut_short || delay == NULL, "no unconditional delay branch"); 2344 2345 } // End of per-block dump 2346 tty->print_cr(""); 2347 2348 if (cut_short) tty->print_cr("*** disassembly is cut short ***"); 2349 } 2350 #endif 2351 2352 //------------------------------Final_Reshape_Counts--------------------------- 2353 // This class defines counters to help identify when a method 2354 // may/must be executed using hardware with only 24-bit precision. 2355 struct Final_Reshape_Counts : public StackObj { 2356 int _call_count; // count non-inlined 'common' calls 2357 int _float_count; // count float ops requiring 24-bit precision 2358 int _double_count; // count double ops requiring more precision 2359 int _java_call_count; // count non-inlined 'java' calls 2360 int _inner_loop_count; // count loops which need alignment 2361 VectorSet _visited; // Visitation flags 2362 Node_List _tests; // Set of IfNodes & PCTableNodes 2363 2364 Final_Reshape_Counts() : 2365 _call_count(0), _float_count(0), _double_count(0), 2366 _java_call_count(0), _inner_loop_count(0), 2367 _visited( Thread::current()->resource_area() ) { } 2368 2369 void inc_call_count () { _call_count ++; } 2370 void inc_float_count () { _float_count ++; } 2371 void inc_double_count() { _double_count++; } 2372 void inc_java_call_count() { _java_call_count++; } 2373 void inc_inner_loop_count() { _inner_loop_count++; } 2374 2375 int get_call_count () const { return _call_count ; } 2376 int get_float_count () const { return _float_count ; } 2377 int get_double_count() const { return _double_count; } 2378 int get_java_call_count() const { return _java_call_count; } 2379 int get_inner_loop_count() const { return _inner_loop_count; } 2380 }; 2381 2382 static bool oop_offset_is_sane(const TypeInstPtr* tp) { 2383 ciInstanceKlass *k = tp->klass()->as_instance_klass(); 2384 // Make sure the offset goes inside the instance layout. 2385 return k->contains_field_offset(tp->offset()); 2386 // Note that OffsetBot and OffsetTop are very negative. 2387 } 2388 2389 // Eliminate trivially redundant StoreCMs and accumulate their 2390 // precedence edges. 2391 void Compile::eliminate_redundant_card_marks(Node* n) { 2392 assert(n->Opcode() == Op_StoreCM, "expected StoreCM"); 2393 if (n->in(MemNode::Address)->outcnt() > 1) { 2394 // There are multiple users of the same address so it might be 2395 // possible to eliminate some of the StoreCMs 2396 Node* mem = n->in(MemNode::Memory); 2397 Node* adr = n->in(MemNode::Address); 2398 Node* val = n->in(MemNode::ValueIn); 2399 Node* prev = n; 2400 bool done = false; 2401 // Walk the chain of StoreCMs eliminating ones that match. As 2402 // long as it's a chain of single users then the optimization is 2403 // safe. Eliminating partially redundant StoreCMs would require 2404 // cloning copies down the other paths. 2405 while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) { 2406 if (adr == mem->in(MemNode::Address) && 2407 val == mem->in(MemNode::ValueIn)) { 2408 // redundant StoreCM 2409 if (mem->req() > MemNode::OopStore) { 2410 // Hasn't been processed by this code yet. 2411 n->add_prec(mem->in(MemNode::OopStore)); 2412 } else { 2413 // Already converted to precedence edge 2414 for (uint i = mem->req(); i < mem->len(); i++) { 2415 // Accumulate any precedence edges 2416 if (mem->in(i) != NULL) { 2417 n->add_prec(mem->in(i)); 2418 } 2419 } 2420 // Everything above this point has been processed. 2421 done = true; 2422 } 2423 // Eliminate the previous StoreCM 2424 prev->set_req(MemNode::Memory, mem->in(MemNode::Memory)); 2425 assert(mem->outcnt() == 0, "should be dead"); 2426 mem->disconnect_inputs(NULL, this); 2427 } else { 2428 prev = mem; 2429 } 2430 mem = prev->in(MemNode::Memory); 2431 } 2432 } 2433 } 2434 2435 //------------------------------final_graph_reshaping_impl---------------------- 2436 // Implement items 1-5 from final_graph_reshaping below. 2437 void Compile::final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &frc) { 2438 2439 if ( n->outcnt() == 0 ) return; // dead node 2440 uint nop = n->Opcode(); 2441 2442 // Check for 2-input instruction with "last use" on right input. 2443 // Swap to left input. Implements item (2). 2444 if( n->req() == 3 && // two-input instruction 2445 n->in(1)->outcnt() > 1 && // left use is NOT a last use 2446 (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop 2447 n->in(2)->outcnt() == 1 &&// right use IS a last use 2448 !n->in(2)->is_Con() ) { // right use is not a constant 2449 // Check for commutative opcode 2450 switch( nop ) { 2451 case Op_AddI: case Op_AddF: case Op_AddD: case Op_AddL: 2452 case Op_MaxI: case Op_MinI: 2453 case Op_MulI: case Op_MulF: case Op_MulD: case Op_MulL: 2454 case Op_AndL: case Op_XorL: case Op_OrL: 2455 case Op_AndI: case Op_XorI: case Op_OrI: { 2456 // Move "last use" input to left by swapping inputs 2457 n->swap_edges(1, 2); 2458 break; 2459 } 2460 default: 2461 break; 2462 } 2463 } 2464 2465 #ifdef ASSERT 2466 if( n->is_Mem() ) { 2467 int alias_idx = get_alias_index(n->as_Mem()->adr_type()); 2468 assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw || 2469 // oop will be recorded in oop map if load crosses safepoint 2470 n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() || 2471 LoadNode::is_immutable_value(n->in(MemNode::Address))), 2472 "raw memory operations should have control edge"); 2473 } 2474 #endif 2475 // Count FPU ops and common calls, implements item (3) 2476 switch( nop ) { 2477 // Count all float operations that may use FPU 2478 case Op_AddF: 2479 case Op_SubF: 2480 case Op_MulF: 2481 case Op_DivF: 2482 case Op_NegF: 2483 case Op_ModF: 2484 case Op_ConvI2F: 2485 case Op_ConF: 2486 case Op_CmpF: 2487 case Op_CmpF3: 2488 // case Op_ConvL2F: // longs are split into 32-bit halves 2489 frc.inc_float_count(); 2490 break; 2491 2492 case Op_ConvF2D: 2493 case Op_ConvD2F: 2494 frc.inc_float_count(); 2495 frc.inc_double_count(); 2496 break; 2497 2498 // Count all double operations that may use FPU 2499 case Op_AddD: 2500 case Op_SubD: 2501 case Op_MulD: 2502 case Op_DivD: 2503 case Op_NegD: 2504 case Op_ModD: 2505 case Op_ConvI2D: 2506 case Op_ConvD2I: 2507 // case Op_ConvL2D: // handled by leaf call 2508 // case Op_ConvD2L: // handled by leaf call 2509 case Op_ConD: 2510 case Op_CmpD: 2511 case Op_CmpD3: 2512 frc.inc_double_count(); 2513 break; 2514 case Op_Opaque1: // Remove Opaque Nodes before matching 2515 case Op_Opaque2: // Remove Opaque Nodes before matching 2516 n->subsume_by(n->in(1), this); 2517 break; 2518 case Op_CallStaticJava: 2519 case Op_CallJava: 2520 case Op_CallDynamicJava: 2521 frc.inc_java_call_count(); // Count java call site; 2522 case Op_CallRuntime: 2523 case Op_CallLeaf: 2524 case Op_CallLeafNoFP: { 2525 assert( n->is_Call(), "" ); 2526 CallNode *call = n->as_Call(); 2527 // Count call sites where the FP mode bit would have to be flipped. 2528 // Do not count uncommon runtime calls: 2529 // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking, 2530 // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ... 2531 if( !call->is_CallStaticJava() || !call->as_CallStaticJava()->_name ) { 2532 frc.inc_call_count(); // Count the call site 2533 } else { // See if uncommon argument is shared 2534 Node *n = call->in(TypeFunc::Parms); 2535 int nop = n->Opcode(); 2536 // Clone shared simple arguments to uncommon calls, item (1). 2537 if( n->outcnt() > 1 && 2538 !n->is_Proj() && 2539 nop != Op_CreateEx && 2540 nop != Op_CheckCastPP && 2541 nop != Op_DecodeN && 2542 !n->is_Mem() ) { 2543 Node *x = n->clone(); 2544 call->set_req( TypeFunc::Parms, x ); 2545 } 2546 } 2547 break; 2548 } 2549 2550 case Op_StoreD: 2551 case Op_LoadD: 2552 case Op_LoadD_unaligned: 2553 frc.inc_double_count(); 2554 goto handle_mem; 2555 case Op_StoreF: 2556 case Op_LoadF: 2557 frc.inc_float_count(); 2558 goto handle_mem; 2559 2560 case Op_StoreCM: 2561 { 2562 // Convert OopStore dependence into precedence edge 2563 Node* prec = n->in(MemNode::OopStore); 2564 n->del_req(MemNode::OopStore); 2565 n->add_prec(prec); 2566 eliminate_redundant_card_marks(n); 2567 } 2568 2569 // fall through 2570 2571 case Op_StoreB: 2572 case Op_StoreC: 2573 case Op_StorePConditional: 2574 case Op_StoreI: 2575 case Op_StoreL: 2576 case Op_StoreIConditional: 2577 case Op_StoreLConditional: 2578 case Op_CompareAndSwapI: 2579 case Op_CompareAndSwapL: 2580 case Op_CompareAndSwapP: 2581 case Op_CompareAndSwapN: 2582 case Op_GetAndAddI: 2583 case Op_GetAndAddL: 2584 case Op_GetAndSetI: 2585 case Op_GetAndSetL: 2586 case Op_GetAndSetP: 2587 case Op_GetAndSetN: 2588 case Op_StoreP: 2589 case Op_StoreN: 2590 case Op_LoadB: 2591 case Op_LoadUB: 2592 case Op_LoadUS: 2593 case Op_LoadI: 2594 case Op_LoadKlass: 2595 case Op_LoadNKlass: 2596 case Op_LoadL: 2597 case Op_LoadL_unaligned: 2598 case Op_LoadPLocked: 2599 case Op_LoadP: 2600 case Op_LoadN: 2601 case Op_LoadRange: 2602 case Op_LoadS: { 2603 handle_mem: 2604 #ifdef ASSERT 2605 if( VerifyOptoOopOffsets ) { 2606 assert( n->is_Mem(), "" ); 2607 MemNode *mem = (MemNode*)n; 2608 // Check to see if address types have grounded out somehow. 2609 const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr(); 2610 assert( !tp || oop_offset_is_sane(tp), "" ); 2611 } 2612 #endif 2613 break; 2614 } 2615 2616 case Op_AddP: { // Assert sane base pointers 2617 Node *addp = n->in(AddPNode::Address); 2618 assert( !addp->is_AddP() || 2619 addp->in(AddPNode::Base)->is_top() || // Top OK for allocation 2620 addp->in(AddPNode::Base) == n->in(AddPNode::Base), 2621 "Base pointers must match" ); 2622 #ifdef _LP64 2623 if (UseCompressedOops && 2624 addp->Opcode() == Op_ConP && 2625 addp == n->in(AddPNode::Base) && 2626 n->in(AddPNode::Offset)->is_Con()) { 2627 // Use addressing with narrow klass to load with offset on x86. 2628 // On sparc loading 32-bits constant and decoding it have less 2629 // instructions (4) then load 64-bits constant (7). 2630 // Do this transformation here since IGVN will convert ConN back to ConP. 2631 const Type* t = addp->bottom_type(); 2632 if (t->isa_oopptr()) { 2633 Node* nn = NULL; 2634 2635 // Look for existing ConN node of the same exact type. 2636 Node* r = root(); 2637 uint cnt = r->outcnt(); 2638 for (uint i = 0; i < cnt; i++) { 2639 Node* m = r->raw_out(i); 2640 if (m!= NULL && m->Opcode() == Op_ConN && 2641 m->bottom_type()->make_ptr() == t) { 2642 nn = m; 2643 break; 2644 } 2645 } 2646 if (nn != NULL) { 2647 // Decode a narrow oop to match address 2648 // [R12 + narrow_oop_reg<<3 + offset] 2649 nn = new (this) DecodeNNode(nn, t); 2650 n->set_req(AddPNode::Base, nn); 2651 n->set_req(AddPNode::Address, nn); 2652 if (addp->outcnt() == 0) { 2653 addp->disconnect_inputs(NULL, this); 2654 } 2655 } 2656 } 2657 } 2658 #endif 2659 break; 2660 } 2661 2662 #ifdef _LP64 2663 case Op_CastPP: 2664 if (n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) { 2665 Node* in1 = n->in(1); 2666 const Type* t = n->bottom_type(); 2667 Node* new_in1 = in1->clone(); 2668 new_in1->as_DecodeN()->set_type(t); 2669 2670 if (!Matcher::narrow_oop_use_complex_address()) { 2671 // 2672 // x86, ARM and friends can handle 2 adds in addressing mode 2673 // and Matcher can fold a DecodeN node into address by using 2674 // a narrow oop directly and do implicit NULL check in address: 2675 // 2676 // [R12 + narrow_oop_reg<<3 + offset] 2677 // NullCheck narrow_oop_reg 2678 // 2679 // On other platforms (Sparc) we have to keep new DecodeN node and 2680 // use it to do implicit NULL check in address: 2681 // 2682 // decode_not_null narrow_oop_reg, base_reg 2683 // [base_reg + offset] 2684 // NullCheck base_reg 2685 // 2686 // Pin the new DecodeN node to non-null path on these platform (Sparc) 2687 // to keep the information to which NULL check the new DecodeN node 2688 // corresponds to use it as value in implicit_null_check(). 2689 // 2690 new_in1->set_req(0, n->in(0)); 2691 } 2692 2693 n->subsume_by(new_in1, this); 2694 if (in1->outcnt() == 0) { 2695 in1->disconnect_inputs(NULL, this); 2696 } 2697 } 2698 break; 2699 2700 case Op_CmpP: 2701 // Do this transformation here to preserve CmpPNode::sub() and 2702 // other TypePtr related Ideal optimizations (for example, ptr nullness). 2703 if (n->in(1)->is_DecodeN() || n->in(2)->is_DecodeN()) { 2704 Node* in1 = n->in(1); 2705 Node* in2 = n->in(2); 2706 if (!in1->is_DecodeN()) { 2707 in2 = in1; 2708 in1 = n->in(2); 2709 } 2710 assert(in1->is_DecodeN(), "sanity"); 2711 2712 Node* new_in2 = NULL; 2713 if (in2->is_DecodeN()) { 2714 new_in2 = in2->in(1); 2715 } else if (in2->Opcode() == Op_ConP) { 2716 const Type* t = in2->bottom_type(); 2717 if (t == TypePtr::NULL_PTR) { 2718 // Don't convert CmpP null check into CmpN if compressed 2719 // oops implicit null check is not generated. 2720 // This will allow to generate normal oop implicit null check. 2721 if (Matcher::gen_narrow_oop_implicit_null_checks()) 2722 new_in2 = ConNode::make(this, TypeNarrowOop::NULL_PTR); 2723 // 2724 // This transformation together with CastPP transformation above 2725 // will generated code for implicit NULL checks for compressed oops. 2726 // 2727 // The original code after Optimize() 2728 // 2729 // LoadN memory, narrow_oop_reg 2730 // decode narrow_oop_reg, base_reg 2731 // CmpP base_reg, NULL 2732 // CastPP base_reg // NotNull 2733 // Load [base_reg + offset], val_reg 2734 // 2735 // after these transformations will be 2736 // 2737 // LoadN memory, narrow_oop_reg 2738 // CmpN narrow_oop_reg, NULL 2739 // decode_not_null narrow_oop_reg, base_reg 2740 // Load [base_reg + offset], val_reg 2741 // 2742 // and the uncommon path (== NULL) will use narrow_oop_reg directly 2743 // since narrow oops can be used in debug info now (see the code in 2744 // final_graph_reshaping_walk()). 2745 // 2746 // At the end the code will be matched to 2747 // on x86: 2748 // 2749 // Load_narrow_oop memory, narrow_oop_reg 2750 // Load [R12 + narrow_oop_reg<<3 + offset], val_reg 2751 // NullCheck narrow_oop_reg 2752 // 2753 // and on sparc: 2754 // 2755 // Load_narrow_oop memory, narrow_oop_reg 2756 // decode_not_null narrow_oop_reg, base_reg 2757 // Load [base_reg + offset], val_reg 2758 // NullCheck base_reg 2759 // 2760 } else if (t->isa_oopptr()) { 2761 new_in2 = ConNode::make(this, t->make_narrowoop()); 2762 } 2763 } 2764 if (new_in2 != NULL) { 2765 Node* cmpN = new (this) CmpNNode(in1->in(1), new_in2); 2766 n->subsume_by(cmpN, this); 2767 if (in1->outcnt() == 0) { 2768 in1->disconnect_inputs(NULL, this); 2769 } 2770 if (in2->outcnt() == 0) { 2771 in2->disconnect_inputs(NULL, this); 2772 } 2773 } 2774 } 2775 break; 2776 2777 case Op_DecodeN: 2778 assert(!n->in(1)->is_EncodeP(), "should be optimized out"); 2779 // DecodeN could be pinned when it can't be fold into 2780 // an address expression, see the code for Op_CastPP above. 2781 assert(n->in(0) == NULL || !Matcher::narrow_oop_use_complex_address(), "no control"); 2782 break; 2783 2784 case Op_EncodeP: { 2785 Node* in1 = n->in(1); 2786 if (in1->is_DecodeN()) { 2787 n->subsume_by(in1->in(1), this); 2788 } else if (in1->Opcode() == Op_ConP) { 2789 const Type* t = in1->bottom_type(); 2790 if (t == TypePtr::NULL_PTR) { 2791 n->subsume_by(ConNode::make(this, TypeNarrowOop::NULL_PTR), this); 2792 } else if (t->isa_oopptr()) { 2793 n->subsume_by(ConNode::make(this, t->make_narrowoop()), this); 2794 } 2795 } 2796 if (in1->outcnt() == 0) { 2797 in1->disconnect_inputs(NULL, this); 2798 } 2799 break; 2800 } 2801 2802 case Op_Proj: { 2803 if (OptimizeStringConcat) { 2804 ProjNode* p = n->as_Proj(); 2805 if (p->_is_io_use) { 2806 // Separate projections were used for the exception path which 2807 // are normally removed by a late inline. If it wasn't inlined 2808 // then they will hang around and should just be replaced with 2809 // the original one. 2810 Node* proj = NULL; 2811 // Replace with just one 2812 for (SimpleDUIterator i(p->in(0)); i.has_next(); i.next()) { 2813 Node *use = i.get(); 2814 if (use->is_Proj() && p != use && use->as_Proj()->_con == p->_con) { 2815 proj = use; 2816 break; 2817 } 2818 } 2819 assert(proj != NULL, "must be found"); 2820 p->subsume_by(proj, this); 2821 } 2822 } 2823 break; 2824 } 2825 2826 case Op_Phi: 2827 if (n->as_Phi()->bottom_type()->isa_narrowoop()) { 2828 // The EncodeP optimization may create Phi with the same edges 2829 // for all paths. It is not handled well by Register Allocator. 2830 Node* unique_in = n->in(1); 2831 assert(unique_in != NULL, ""); 2832 uint cnt = n->req(); 2833 for (uint i = 2; i < cnt; i++) { 2834 Node* m = n->in(i); 2835 assert(m != NULL, ""); 2836 if (unique_in != m) 2837 unique_in = NULL; 2838 } 2839 if (unique_in != NULL) { 2840 n->subsume_by(unique_in, this); 2841 } 2842 } 2843 break; 2844 2845 #endif 2846 2847 case Op_ModI: 2848 if (UseDivMod) { 2849 // Check if a%b and a/b both exist 2850 Node* d = n->find_similar(Op_DivI); 2851 if (d) { 2852 // Replace them with a fused divmod if supported 2853 if (Matcher::has_match_rule(Op_DivModI)) { 2854 DivModINode* divmod = DivModINode::make(this, n); 2855 d->subsume_by(divmod->div_proj(), this); 2856 n->subsume_by(divmod->mod_proj(), this); 2857 } else { 2858 // replace a%b with a-((a/b)*b) 2859 Node* mult = new (this) MulINode(d, d->in(2)); 2860 Node* sub = new (this) SubINode(d->in(1), mult); 2861 n->subsume_by(sub, this); 2862 } 2863 } 2864 } 2865 break; 2866 2867 case Op_ModL: 2868 if (UseDivMod) { 2869 // Check if a%b and a/b both exist 2870 Node* d = n->find_similar(Op_DivL); 2871 if (d) { 2872 // Replace them with a fused divmod if supported 2873 if (Matcher::has_match_rule(Op_DivModL)) { 2874 DivModLNode* divmod = DivModLNode::make(this, n); 2875 d->subsume_by(divmod->div_proj(), this); 2876 n->subsume_by(divmod->mod_proj(), this); 2877 } else { 2878 // replace a%b with a-((a/b)*b) 2879 Node* mult = new (this) MulLNode(d, d->in(2)); 2880 Node* sub = new (this) SubLNode(d->in(1), mult); 2881 n->subsume_by(sub, this); 2882 } 2883 } 2884 } 2885 break; 2886 2887 case Op_LoadVector: 2888 case Op_StoreVector: 2889 break; 2890 2891 case Op_PackB: 2892 case Op_PackS: 2893 case Op_PackI: 2894 case Op_PackF: 2895 case Op_PackL: 2896 case Op_PackD: 2897 if (n->req()-1 > 2) { 2898 // Replace many operand PackNodes with a binary tree for matching 2899 PackNode* p = (PackNode*) n; 2900 Node* btp = p->binary_tree_pack(this, 1, n->req()); 2901 n->subsume_by(btp, this); 2902 } 2903 break; 2904 case Op_Loop: 2905 case Op_CountedLoop: 2906 if (n->as_Loop()->is_inner_loop()) { 2907 frc.inc_inner_loop_count(); 2908 } 2909 break; 2910 case Op_LShiftI: 2911 case Op_RShiftI: 2912 case Op_URShiftI: 2913 case Op_LShiftL: 2914 case Op_RShiftL: 2915 case Op_URShiftL: 2916 if (Matcher::need_masked_shift_count) { 2917 // The cpu's shift instructions don't restrict the count to the 2918 // lower 5/6 bits. We need to do the masking ourselves. 2919 Node* in2 = n->in(2); 2920 juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1); 2921 const TypeInt* t = in2->find_int_type(); 2922 if (t != NULL && t->is_con()) { 2923 juint shift = t->get_con(); 2924 if (shift > mask) { // Unsigned cmp 2925 n->set_req(2, ConNode::make(this, TypeInt::make(shift & mask))); 2926 } 2927 } else { 2928 if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) { 2929 Node* shift = new (this) AndINode(in2, ConNode::make(this, TypeInt::make(mask))); 2930 n->set_req(2, shift); 2931 } 2932 } 2933 if (in2->outcnt() == 0) { // Remove dead node 2934 in2->disconnect_inputs(NULL, this); 2935 } 2936 } 2937 break; 2938 case Op_MemBarStoreStore: 2939 // Break the link with AllocateNode: it is no longer useful and 2940 // confuses register allocation. 2941 if (n->req() > MemBarNode::Precedent) { 2942 n->set_req(MemBarNode::Precedent, top()); 2943 } 2944 break; 2945 default: 2946 assert( !n->is_Call(), "" ); 2947 assert( !n->is_Mem(), "" ); 2948 break; 2949 } 2950 2951 // Collect CFG split points 2952 if (n->is_MultiBranch()) 2953 frc._tests.push(n); 2954 } 2955 2956 //------------------------------final_graph_reshaping_walk--------------------- 2957 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(), 2958 // requires that the walk visits a node's inputs before visiting the node. 2959 void Compile::final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &frc ) { 2960 ResourceArea *area = Thread::current()->resource_area(); 2961 Unique_Node_List sfpt(area); 2962 2963 frc._visited.set(root->_idx); // first, mark node as visited 2964 uint cnt = root->req(); 2965 Node *n = root; 2966 uint i = 0; 2967 while (true) { 2968 if (i < cnt) { 2969 // Place all non-visited non-null inputs onto stack 2970 Node* m = n->in(i); 2971 ++i; 2972 if (m != NULL && !frc._visited.test_set(m->_idx)) { 2973 if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL) 2974 sfpt.push(m); 2975 cnt = m->req(); 2976 nstack.push(n, i); // put on stack parent and next input's index 2977 n = m; 2978 i = 0; 2979 } 2980 } else { 2981 // Now do post-visit work 2982 final_graph_reshaping_impl( n, frc ); 2983 if (nstack.is_empty()) 2984 break; // finished 2985 n = nstack.node(); // Get node from stack 2986 cnt = n->req(); 2987 i = nstack.index(); 2988 nstack.pop(); // Shift to the next node on stack 2989 } 2990 } 2991 2992 // Skip next transformation if compressed oops are not used. 2993 if (!UseCompressedOops || !Matcher::gen_narrow_oop_implicit_null_checks()) 2994 return; 2995 2996 // Go over safepoints nodes to skip DecodeN nodes for debug edges. 2997 // It could be done for an uncommon traps or any safepoints/calls 2998 // if the DecodeN node is referenced only in a debug info. 2999 while (sfpt.size() > 0) { 3000 n = sfpt.pop(); 3001 JVMState *jvms = n->as_SafePoint()->jvms(); 3002 assert(jvms != NULL, "sanity"); 3003 int start = jvms->debug_start(); 3004 int end = n->req(); 3005 bool is_uncommon = (n->is_CallStaticJava() && 3006 n->as_CallStaticJava()->uncommon_trap_request() != 0); 3007 for (int j = start; j < end; j++) { 3008 Node* in = n->in(j); 3009 if (in->is_DecodeN()) { 3010 bool safe_to_skip = true; 3011 if (!is_uncommon ) { 3012 // Is it safe to skip? 3013 for (uint i = 0; i < in->outcnt(); i++) { 3014 Node* u = in->raw_out(i); 3015 if (!u->is_SafePoint() || 3016 u->is_Call() && u->as_Call()->has_non_debug_use(n)) { 3017 safe_to_skip = false; 3018 } 3019 } 3020 } 3021 if (safe_to_skip) { 3022 n->set_req(j, in->in(1)); 3023 } 3024 if (in->outcnt() == 0) { 3025 in->disconnect_inputs(NULL, this); 3026 } 3027 } 3028 } 3029 } 3030 } 3031 3032 //------------------------------final_graph_reshaping-------------------------- 3033 // Final Graph Reshaping. 3034 // 3035 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late 3036 // and not commoned up and forced early. Must come after regular 3037 // optimizations to avoid GVN undoing the cloning. Clone constant 3038 // inputs to Loop Phis; these will be split by the allocator anyways. 3039 // Remove Opaque nodes. 3040 // (2) Move last-uses by commutative operations to the left input to encourage 3041 // Intel update-in-place two-address operations and better register usage 3042 // on RISCs. Must come after regular optimizations to avoid GVN Ideal 3043 // calls canonicalizing them back. 3044 // (3) Count the number of double-precision FP ops, single-precision FP ops 3045 // and call sites. On Intel, we can get correct rounding either by 3046 // forcing singles to memory (requires extra stores and loads after each 3047 // FP bytecode) or we can set a rounding mode bit (requires setting and 3048 // clearing the mode bit around call sites). The mode bit is only used 3049 // if the relative frequency of single FP ops to calls is low enough. 3050 // This is a key transform for SPEC mpeg_audio. 3051 // (4) Detect infinite loops; blobs of code reachable from above but not 3052 // below. Several of the Code_Gen algorithms fail on such code shapes, 3053 // so we simply bail out. Happens a lot in ZKM.jar, but also happens 3054 // from time to time in other codes (such as -Xcomp finalizer loops, etc). 3055 // Detection is by looking for IfNodes where only 1 projection is 3056 // reachable from below or CatchNodes missing some targets. 3057 // (5) Assert for insane oop offsets in debug mode. 3058 3059 bool Compile::final_graph_reshaping() { 3060 // an infinite loop may have been eliminated by the optimizer, 3061 // in which case the graph will be empty. 3062 if (root()->req() == 1) { 3063 record_method_not_compilable("trivial infinite loop"); 3064 return true; 3065 } 3066 3067 // Expensive nodes have their control input set to prevent the GVN 3068 // from freely commoning them. There's no GVN beyond this point so 3069 // no need to keep the control input. We want the expensive nodes to 3070 // be freely moved to the least frequent code path by gcm. 3071 assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?"); 3072 for (int i = 0; i < expensive_count(); i++) { 3073 _expensive_nodes->at(i)->set_req(0, NULL); 3074 } 3075 3076 Final_Reshape_Counts frc; 3077 3078 // Visit everybody reachable! 3079 // Allocate stack of size C->unique()/2 to avoid frequent realloc 3080 Node_Stack nstack(unique() >> 1); 3081 final_graph_reshaping_walk(nstack, root(), frc); 3082 3083 // Check for unreachable (from below) code (i.e., infinite loops). 3084 for( uint i = 0; i < frc._tests.size(); i++ ) { 3085 MultiBranchNode *n = frc._tests[i]->as_MultiBranch(); 3086 // Get number of CFG targets. 3087 // Note that PCTables include exception targets after calls. 3088 uint required_outcnt = n->required_outcnt(); 3089 if (n->outcnt() != required_outcnt) { 3090 // Check for a few special cases. Rethrow Nodes never take the 3091 // 'fall-thru' path, so expected kids is 1 less. 3092 if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) { 3093 if (n->in(0)->in(0)->is_Call()) { 3094 CallNode *call = n->in(0)->in(0)->as_Call(); 3095 if (call->entry_point() == OptoRuntime::rethrow_stub()) { 3096 required_outcnt--; // Rethrow always has 1 less kid 3097 } else if (call->req() > TypeFunc::Parms && 3098 call->is_CallDynamicJava()) { 3099 // Check for null receiver. In such case, the optimizer has 3100 // detected that the virtual call will always result in a null 3101 // pointer exception. The fall-through projection of this CatchNode 3102 // will not be populated. 3103 Node *arg0 = call->in(TypeFunc::Parms); 3104 if (arg0->is_Type() && 3105 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) { 3106 required_outcnt--; 3107 } 3108 } else if (call->entry_point() == OptoRuntime::new_array_Java() && 3109 call->req() > TypeFunc::Parms+1 && 3110 call->is_CallStaticJava()) { 3111 // Check for negative array length. In such case, the optimizer has 3112 // detected that the allocation attempt will always result in an 3113 // exception. There is no fall-through projection of this CatchNode . 3114 Node *arg1 = call->in(TypeFunc::Parms+1); 3115 if (arg1->is_Type() && 3116 arg1->as_Type()->type()->join(TypeInt::POS)->empty()) { 3117 required_outcnt--; 3118 } 3119 } 3120 } 3121 } 3122 // Recheck with a better notion of 'required_outcnt' 3123 if (n->outcnt() != required_outcnt) { 3124 record_method_not_compilable("malformed control flow"); 3125 return true; // Not all targets reachable! 3126 } 3127 } 3128 // Check that I actually visited all kids. Unreached kids 3129 // must be infinite loops. 3130 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) 3131 if (!frc._visited.test(n->fast_out(j)->_idx)) { 3132 record_method_not_compilable("infinite loop"); 3133 return true; // Found unvisited kid; must be unreach 3134 } 3135 } 3136 3137 // If original bytecodes contained a mixture of floats and doubles 3138 // check if the optimizer has made it homogenous, item (3). 3139 if( Use24BitFPMode && Use24BitFP && UseSSE == 0 && 3140 frc.get_float_count() > 32 && 3141 frc.get_double_count() == 0 && 3142 (10 * frc.get_call_count() < frc.get_float_count()) ) { 3143 set_24_bit_selection_and_mode( false, true ); 3144 } 3145 3146 set_java_calls(frc.get_java_call_count()); 3147 set_inner_loops(frc.get_inner_loop_count()); 3148 3149 // No infinite loops, no reason to bail out. 3150 return false; 3151 } 3152 3153 //-----------------------------too_many_traps---------------------------------- 3154 // Report if there are too many traps at the current method and bci. 3155 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded. 3156 bool Compile::too_many_traps(ciMethod* method, 3157 int bci, 3158 Deoptimization::DeoptReason reason) { 3159 ciMethodData* md = method->method_data(); 3160 if (md->is_empty()) { 3161 // Assume the trap has not occurred, or that it occurred only 3162 // because of a transient condition during start-up in the interpreter. 3163 return false; 3164 } 3165 if (md->has_trap_at(bci, reason) != 0) { 3166 // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic. 3167 // Also, if there are multiple reasons, or if there is no per-BCI record, 3168 // assume the worst. 3169 if (log()) 3170 log()->elem("observe trap='%s' count='%d'", 3171 Deoptimization::trap_reason_name(reason), 3172 md->trap_count(reason)); 3173 return true; 3174 } else { 3175 // Ignore method/bci and see if there have been too many globally. 3176 return too_many_traps(reason, md); 3177 } 3178 } 3179 3180 // Less-accurate variant which does not require a method and bci. 3181 bool Compile::too_many_traps(Deoptimization::DeoptReason reason, 3182 ciMethodData* logmd) { 3183 if (trap_count(reason) >= (uint)PerMethodTrapLimit) { 3184 // Too many traps globally. 3185 // Note that we use cumulative trap_count, not just md->trap_count. 3186 if (log()) { 3187 int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason); 3188 log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'", 3189 Deoptimization::trap_reason_name(reason), 3190 mcount, trap_count(reason)); 3191 } 3192 return true; 3193 } else { 3194 // The coast is clear. 3195 return false; 3196 } 3197 } 3198 3199 //--------------------------too_many_recompiles-------------------------------- 3200 // Report if there are too many recompiles at the current method and bci. 3201 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff. 3202 // Is not eager to return true, since this will cause the compiler to use 3203 // Action_none for a trap point, to avoid too many recompilations. 3204 bool Compile::too_many_recompiles(ciMethod* method, 3205 int bci, 3206 Deoptimization::DeoptReason reason) { 3207 ciMethodData* md = method->method_data(); 3208 if (md->is_empty()) { 3209 // Assume the trap has not occurred, or that it occurred only 3210 // because of a transient condition during start-up in the interpreter. 3211 return false; 3212 } 3213 // Pick a cutoff point well within PerBytecodeRecompilationCutoff. 3214 uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8; 3215 uint m_cutoff = (uint) PerMethodRecompilationCutoff / 2 + 1; // not zero 3216 Deoptimization::DeoptReason per_bc_reason 3217 = Deoptimization::reason_recorded_per_bytecode_if_any(reason); 3218 if ((per_bc_reason == Deoptimization::Reason_none 3219 || md->has_trap_at(bci, reason) != 0) 3220 // The trap frequency measure we care about is the recompile count: 3221 && md->trap_recompiled_at(bci) 3222 && md->overflow_recompile_count() >= bc_cutoff) { 3223 // Do not emit a trap here if it has already caused recompilations. 3224 // Also, if there are multiple reasons, or if there is no per-BCI record, 3225 // assume the worst. 3226 if (log()) 3227 log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'", 3228 Deoptimization::trap_reason_name(reason), 3229 md->trap_count(reason), 3230 md->overflow_recompile_count()); 3231 return true; 3232 } else if (trap_count(reason) != 0 3233 && decompile_count() >= m_cutoff) { 3234 // Too many recompiles globally, and we have seen this sort of trap. 3235 // Use cumulative decompile_count, not just md->decompile_count. 3236 if (log()) 3237 log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'", 3238 Deoptimization::trap_reason_name(reason), 3239 md->trap_count(reason), trap_count(reason), 3240 md->decompile_count(), decompile_count()); 3241 return true; 3242 } else { 3243 // The coast is clear. 3244 return false; 3245 } 3246 } 3247 3248 3249 #ifndef PRODUCT 3250 //------------------------------verify_graph_edges--------------------------- 3251 // Walk the Graph and verify that there is a one-to-one correspondence 3252 // between Use-Def edges and Def-Use edges in the graph. 3253 void Compile::verify_graph_edges(bool no_dead_code) { 3254 if (VerifyGraphEdges) { 3255 ResourceArea *area = Thread::current()->resource_area(); 3256 Unique_Node_List visited(area); 3257 // Call recursive graph walk to check edges 3258 _root->verify_edges(visited); 3259 if (no_dead_code) { 3260 // Now make sure that no visited node is used by an unvisited node. 3261 bool dead_nodes = 0; 3262 Unique_Node_List checked(area); 3263 while (visited.size() > 0) { 3264 Node* n = visited.pop(); 3265 checked.push(n); 3266 for (uint i = 0; i < n->outcnt(); i++) { 3267 Node* use = n->raw_out(i); 3268 if (checked.member(use)) continue; // already checked 3269 if (visited.member(use)) continue; // already in the graph 3270 if (use->is_Con()) continue; // a dead ConNode is OK 3271 // At this point, we have found a dead node which is DU-reachable. 3272 if (dead_nodes++ == 0) 3273 tty->print_cr("*** Dead nodes reachable via DU edges:"); 3274 use->dump(2); 3275 tty->print_cr("---"); 3276 checked.push(use); // No repeats; pretend it is now checked. 3277 } 3278 } 3279 assert(dead_nodes == 0, "using nodes must be reachable from root"); 3280 } 3281 } 3282 } 3283 3284 // Verify GC barriers consistency 3285 // Currently supported: 3286 // - G1 pre-barriers (see GraphKit::g1_write_barrier_pre()) 3287 void Compile::verify_barriers() { 3288 if (UseG1GC) { 3289 // Verify G1 pre-barriers 3290 const int marking_offset = in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active()); 3291 3292 ResourceArea *area = Thread::current()->resource_area(); 3293 Unique_Node_List visited(area); 3294 Node_List worklist(area); 3295 // We're going to walk control flow backwards starting from the Root 3296 worklist.push(_root); 3297 while (worklist.size() > 0) { 3298 Node* x = worklist.pop(); 3299 if (x == NULL || x == top()) continue; 3300 if (visited.member(x)) { 3301 continue; 3302 } else { 3303 visited.push(x); 3304 } 3305 3306 if (x->is_Region()) { 3307 for (uint i = 1; i < x->req(); i++) { 3308 worklist.push(x->in(i)); 3309 } 3310 } else { 3311 worklist.push(x->in(0)); 3312 // We are looking for the pattern: 3313 // /->ThreadLocal 3314 // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset) 3315 // \->ConI(0) 3316 // We want to verify that the If and the LoadB have the same control 3317 // See GraphKit::g1_write_barrier_pre() 3318 if (x->is_If()) { 3319 IfNode *iff = x->as_If(); 3320 if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) { 3321 CmpNode *cmp = iff->in(1)->in(1)->as_Cmp(); 3322 if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0 3323 && cmp->in(1)->is_Load()) { 3324 LoadNode* load = cmp->in(1)->as_Load(); 3325 if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal 3326 && load->in(2)->in(3)->is_Con() 3327 && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) { 3328 3329 Node* if_ctrl = iff->in(0); 3330 Node* load_ctrl = load->in(0); 3331 3332 if (if_ctrl != load_ctrl) { 3333 // Skip possible CProj->NeverBranch in infinite loops 3334 if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj) 3335 && (if_ctrl->in(0)->is_MultiBranch() && if_ctrl->in(0)->Opcode() == Op_NeverBranch)) { 3336 if_ctrl = if_ctrl->in(0)->in(0); 3337 } 3338 } 3339 assert(load_ctrl != NULL && if_ctrl == load_ctrl, "controls must match"); 3340 } 3341 } 3342 } 3343 } 3344 } 3345 } 3346 } 3347 } 3348 3349 #endif 3350 3351 // The Compile object keeps track of failure reasons separately from the ciEnv. 3352 // This is required because there is not quite a 1-1 relation between the 3353 // ciEnv and its compilation task and the Compile object. Note that one 3354 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides 3355 // to backtrack and retry without subsuming loads. Other than this backtracking 3356 // behavior, the Compile's failure reason is quietly copied up to the ciEnv 3357 // by the logic in C2Compiler. 3358 void Compile::record_failure(const char* reason) { 3359 if (log() != NULL) { 3360 log()->elem("failure reason='%s' phase='compile'", reason); 3361 } 3362 if (_failure_reason == NULL) { 3363 // Record the first failure reason. 3364 _failure_reason = reason; 3365 } 3366 3367 EventCompilerFailure event; 3368 if (event.should_commit()) { 3369 event.set_compileID(Compile::compile_id()); 3370 event.set_failure(reason); 3371 event.commit(); 3372 } 3373 3374 if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) { 3375 C->print_method(PHASE_FAILURE); 3376 } 3377 _root = NULL; // flush the graph, too 3378 } 3379 3380 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator, bool dolog) 3381 : TraceTime(NULL, accumulator, false NOT_PRODUCT( || TimeCompiler ), false), 3382 _phase_name(name), _dolog(dolog) 3383 { 3384 if (dolog) { 3385 C = Compile::current(); 3386 _log = C->log(); 3387 } else { 3388 C = NULL; 3389 _log = NULL; 3390 } 3391 if (_log != NULL) { 3392 _log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes()); 3393 _log->stamp(); 3394 _log->end_head(); 3395 } 3396 } 3397 3398 Compile::TracePhase::~TracePhase() { 3399 3400 C = Compile::current(); 3401 if (_dolog) { 3402 _log = C->log(); 3403 } else { 3404 _log = NULL; 3405 } 3406 3407 #ifdef ASSERT 3408 if (PrintIdealNodeCount) { 3409 tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'", 3410 _phase_name, C->unique(), C->live_nodes(), C->count_live_nodes_by_graph_walk()); 3411 } 3412 3413 if (VerifyIdealNodeCount) { 3414 Compile::current()->print_missing_nodes(); 3415 } 3416 #endif 3417 3418 if (_log != NULL) { 3419 _log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes()); 3420 } 3421 } 3422 3423 //============================================================================= 3424 // Two Constant's are equal when the type and the value are equal. 3425 bool Compile::Constant::operator==(const Constant& other) { 3426 if (type() != other.type() ) return false; 3427 if (can_be_reused() != other.can_be_reused()) return false; 3428 // For floating point values we compare the bit pattern. 3429 switch (type()) { 3430 case T_FLOAT: return (_value.i == other._value.i); 3431 case T_LONG: 3432 case T_DOUBLE: return (_value.j == other._value.j); 3433 case T_OBJECT: 3434 case T_ADDRESS: return (_value.l == other._value.l); 3435 case T_VOID: return (_value.l == other._value.l); // jump-table entries 3436 default: ShouldNotReachHere(); 3437 } 3438 return false; 3439 } 3440 3441 static int type_to_size_in_bytes(BasicType t) { 3442 switch (t) { 3443 case T_LONG: return sizeof(jlong ); 3444 case T_FLOAT: return sizeof(jfloat ); 3445 case T_DOUBLE: return sizeof(jdouble); 3446 // We use T_VOID as marker for jump-table entries (labels) which 3447 // need an internal word relocation. 3448 case T_VOID: 3449 case T_ADDRESS: 3450 case T_OBJECT: return sizeof(jobject); 3451 } 3452 3453 ShouldNotReachHere(); 3454 return -1; 3455 } 3456 3457 int Compile::ConstantTable::qsort_comparator(Constant* a, Constant* b) { 3458 // sort descending 3459 if (a->freq() > b->freq()) return -1; 3460 if (a->freq() < b->freq()) return 1; 3461 return 0; 3462 } 3463 3464 void Compile::ConstantTable::calculate_offsets_and_size() { 3465 // First, sort the array by frequencies. 3466 _constants.sort(qsort_comparator); 3467 3468 #ifdef ASSERT 3469 // Make sure all jump-table entries were sorted to the end of the 3470 // array (they have a negative frequency). 3471 bool found_void = false; 3472 for (int i = 0; i < _constants.length(); i++) { 3473 Constant con = _constants.at(i); 3474 if (con.type() == T_VOID) 3475 found_void = true; // jump-tables 3476 else 3477 assert(!found_void, "wrong sorting"); 3478 } 3479 #endif 3480 3481 int offset = 0; 3482 for (int i = 0; i < _constants.length(); i++) { 3483 Constant* con = _constants.adr_at(i); 3484 3485 // Align offset for type. 3486 int typesize = type_to_size_in_bytes(con->type()); 3487 offset = align_size_up(offset, typesize); 3488 con->set_offset(offset); // set constant's offset 3489 3490 if (con->type() == T_VOID) { 3491 MachConstantNode* n = (MachConstantNode*) con->get_jobject(); 3492 offset = offset + typesize * n->outcnt(); // expand jump-table 3493 } else { 3494 offset = offset + typesize; 3495 } 3496 } 3497 3498 // Align size up to the next section start (which is insts; see 3499 // CodeBuffer::align_at_start). 3500 assert(_size == -1, "already set?"); 3501 _size = align_size_up(offset, CodeEntryAlignment); 3502 } 3503 3504 void Compile::ConstantTable::emit(CodeBuffer& cb) { 3505 MacroAssembler _masm(&cb); 3506 for (int i = 0; i < _constants.length(); i++) { 3507 Constant con = _constants.at(i); 3508 address constant_addr; 3509 switch (con.type()) { 3510 case T_LONG: constant_addr = _masm.long_constant( con.get_jlong() ); break; 3511 case T_FLOAT: constant_addr = _masm.float_constant( con.get_jfloat() ); break; 3512 case T_DOUBLE: constant_addr = _masm.double_constant(con.get_jdouble()); break; 3513 case T_OBJECT: { 3514 jobject obj = con.get_jobject(); 3515 int oop_index = _masm.oop_recorder()->find_index(obj); 3516 constant_addr = _masm.address_constant((address) obj, oop_Relocation::spec(oop_index)); 3517 break; 3518 } 3519 case T_ADDRESS: { 3520 address addr = (address) con.get_jobject(); 3521 constant_addr = _masm.address_constant(addr); 3522 break; 3523 } 3524 // We use T_VOID as marker for jump-table entries (labels) which 3525 // need an internal word relocation. 3526 case T_VOID: { 3527 MachConstantNode* n = (MachConstantNode*) con.get_jobject(); 3528 // Fill the jump-table with a dummy word. The real value is 3529 // filled in later in fill_jump_table. 3530 address dummy = (address) n; 3531 constant_addr = _masm.address_constant(dummy); 3532 // Expand jump-table 3533 for (uint i = 1; i < n->outcnt(); i++) { 3534 address temp_addr = _masm.address_constant(dummy + i); 3535 assert(temp_addr, "consts section too small"); 3536 } 3537 break; 3538 } 3539 default: ShouldNotReachHere(); 3540 } 3541 assert(constant_addr, "consts section too small"); 3542 assert((constant_addr - _masm.code()->consts()->start()) == con.offset(), err_msg_res("must be: %d == %d", constant_addr - _masm.code()->consts()->start(), con.offset())); 3543 } 3544 } 3545 3546 int Compile::ConstantTable::find_offset(Constant& con) const { 3547 int idx = _constants.find(con); 3548 assert(idx != -1, "constant must be in constant table"); 3549 int offset = _constants.at(idx).offset(); 3550 assert(offset != -1, "constant table not emitted yet?"); 3551 return offset; 3552 } 3553 3554 void Compile::ConstantTable::add(Constant& con) { 3555 if (con.can_be_reused()) { 3556 int idx = _constants.find(con); 3557 if (idx != -1 && _constants.at(idx).can_be_reused()) { 3558 _constants.adr_at(idx)->inc_freq(con.freq()); // increase the frequency by the current value 3559 return; 3560 } 3561 } 3562 (void) _constants.append(con); 3563 } 3564 3565 Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, BasicType type, jvalue value) { 3566 Block* b = Compile::current()->cfg()->_bbs[n->_idx]; 3567 Constant con(type, value, b->_freq); 3568 add(con); 3569 return con; 3570 } 3571 3572 Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, MachOper* oper) { 3573 jvalue value; 3574 BasicType type = oper->type()->basic_type(); 3575 switch (type) { 3576 case T_LONG: value.j = oper->constantL(); break; 3577 case T_FLOAT: value.f = oper->constantF(); break; 3578 case T_DOUBLE: value.d = oper->constantD(); break; 3579 case T_OBJECT: 3580 case T_ADDRESS: value.l = (jobject) oper->constant(); break; 3581 default: ShouldNotReachHere(); 3582 } 3583 return add(n, type, value); 3584 } 3585 3586 Compile::Constant Compile::ConstantTable::add_jump_table(MachConstantNode* n) { 3587 jvalue value; 3588 // We can use the node pointer here to identify the right jump-table 3589 // as this method is called from Compile::Fill_buffer right before 3590 // the MachNodes are emitted and the jump-table is filled (means the 3591 // MachNode pointers do not change anymore). 3592 value.l = (jobject) n; 3593 Constant con(T_VOID, value, next_jump_table_freq(), false); // Labels of a jump-table cannot be reused. 3594 add(con); 3595 return con; 3596 } 3597 3598 void Compile::ConstantTable::fill_jump_table(CodeBuffer& cb, MachConstantNode* n, GrowableArray<Label*> labels) const { 3599 // If called from Compile::scratch_emit_size do nothing. 3600 if (Compile::current()->in_scratch_emit_size()) return; 3601 3602 assert(labels.is_nonempty(), "must be"); 3603 assert((uint) labels.length() == n->outcnt(), err_msg_res("must be equal: %d == %d", labels.length(), n->outcnt())); 3604 3605 // Since MachConstantNode::constant_offset() also contains 3606 // table_base_offset() we need to subtract the table_base_offset() 3607 // to get the plain offset into the constant table. 3608 int offset = n->constant_offset() - table_base_offset(); 3609 3610 MacroAssembler _masm(&cb); 3611 address* jump_table_base = (address*) (_masm.code()->consts()->start() + offset); 3612 3613 for (uint i = 0; i < n->outcnt(); i++) { 3614 address* constant_addr = &jump_table_base[i]; 3615 assert(*constant_addr == (((address) n) + i), err_msg_res("all jump-table entries must contain adjusted node pointer: " INTPTR_FORMAT " == " INTPTR_FORMAT, *constant_addr, (((address) n) + i))); 3616 *constant_addr = cb.consts()->target(*labels.at(i), (address) constant_addr); 3617 cb.consts()->relocate((address) constant_addr, relocInfo::internal_word_type); 3618 } 3619 } 3620 3621 void Compile::dump_inlining() { 3622 if (print_inlining() || print_intrinsics()) { 3623 // Print inlining message for candidates that we couldn't inline 3624 // for lack of space or non constant receiver 3625 for (int i = 0; i < _late_inlines.length(); i++) { 3626 CallGenerator* cg = _late_inlines.at(i); 3627 cg->print_inlining_late("live nodes > LiveNodeCountInliningCutoff"); 3628 } 3629 Unique_Node_List useful; 3630 useful.push(root()); 3631 for (uint next = 0; next < useful.size(); ++next) { 3632 Node* n = useful.at(next); 3633 if (n->is_Call() && n->as_Call()->generator() != NULL && n->as_Call()->generator()->call_node() == n) { 3634 CallNode* call = n->as_Call(); 3635 CallGenerator* cg = call->generator(); 3636 cg->print_inlining_late("receiver not constant"); 3637 } 3638 uint max = n->len(); 3639 for ( uint i = 0; i < max; ++i ) { 3640 Node *m = n->in(i); 3641 if ( m == NULL ) continue; 3642 useful.push(m); 3643 } 3644 } 3645 for (int i = 0; i < _print_inlining_list->length(); i++) { 3646 tty->print(_print_inlining_list->adr_at(i)->ss()->as_string()); 3647 } 3648 } 3649 } 3650 3651 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) { 3652 if (n1->Opcode() < n2->Opcode()) return -1; 3653 else if (n1->Opcode() > n2->Opcode()) return 1; 3654 3655 assert(n1->req() == n2->req(), err_msg_res("can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req())); 3656 for (uint i = 1; i < n1->req(); i++) { 3657 if (n1->in(i) < n2->in(i)) return -1; 3658 else if (n1->in(i) > n2->in(i)) return 1; 3659 } 3660 3661 return 0; 3662 } 3663 3664 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) { 3665 Node* n1 = *n1p; 3666 Node* n2 = *n2p; 3667 3668 return cmp_expensive_nodes(n1, n2); 3669 } 3670 3671 void Compile::sort_expensive_nodes() { 3672 if (!expensive_nodes_sorted()) { 3673 _expensive_nodes->sort(cmp_expensive_nodes); 3674 } 3675 } 3676 3677 bool Compile::expensive_nodes_sorted() const { 3678 for (int i = 1; i < _expensive_nodes->length(); i++) { 3679 if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i-1)) < 0) { 3680 return false; 3681 } 3682 } 3683 return true; 3684 } 3685 3686 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) { 3687 if (_expensive_nodes->length() == 0) { 3688 return false; 3689 } 3690 3691 assert(OptimizeExpensiveOps, "optimization off?"); 3692 3693 // Take this opportunity to remove dead nodes from the list 3694 int j = 0; 3695 for (int i = 0; i < _expensive_nodes->length(); i++) { 3696 Node* n = _expensive_nodes->at(i); 3697 if (!n->is_unreachable(igvn)) { 3698 assert(n->is_expensive(), "should be expensive"); 3699 _expensive_nodes->at_put(j, n); 3700 j++; 3701 } 3702 } 3703 _expensive_nodes->trunc_to(j); 3704 3705 // Then sort the list so that similar nodes are next to each other 3706 // and check for at least two nodes of identical kind with same data 3707 // inputs. 3708 sort_expensive_nodes(); 3709 3710 for (int i = 0; i < _expensive_nodes->length()-1; i++) { 3711 if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i+1)) == 0) { 3712 return true; 3713 } 3714 } 3715 3716 return false; 3717 } 3718 3719 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) { 3720 if (_expensive_nodes->length() == 0) { 3721 return; 3722 } 3723 3724 assert(OptimizeExpensiveOps, "optimization off?"); 3725 3726 // Sort to bring similar nodes next to each other and clear the 3727 // control input of nodes for which there's only a single copy. 3728 sort_expensive_nodes(); 3729 3730 int j = 0; 3731 int identical = 0; 3732 int i = 0; 3733 for (; i < _expensive_nodes->length()-1; i++) { 3734 assert(j <= i, "can't write beyond current index"); 3735 if (_expensive_nodes->at(i)->Opcode() == _expensive_nodes->at(i+1)->Opcode()) { 3736 identical++; 3737 _expensive_nodes->at_put(j++, _expensive_nodes->at(i)); 3738 continue; 3739 } 3740 if (identical > 0) { 3741 _expensive_nodes->at_put(j++, _expensive_nodes->at(i)); 3742 identical = 0; 3743 } else { 3744 Node* n = _expensive_nodes->at(i); 3745 igvn.hash_delete(n); 3746 n->set_req(0, NULL); 3747 igvn.hash_insert(n); 3748 } 3749 } 3750 if (identical > 0) { 3751 _expensive_nodes->at_put(j++, _expensive_nodes->at(i)); 3752 } else if (_expensive_nodes->length() >= 1) { 3753 Node* n = _expensive_nodes->at(i); 3754 igvn.hash_delete(n); 3755 n->set_req(0, NULL); 3756 igvn.hash_insert(n); 3757 } 3758 _expensive_nodes->trunc_to(j); 3759 } 3760 3761 void Compile::add_expensive_node(Node * n) { 3762 assert(!_expensive_nodes->contains(n), "duplicate entry in expensive list"); 3763 assert(n->is_expensive(), "expensive nodes with non-null control here only"); 3764 assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here"); 3765 if (OptimizeExpensiveOps) { 3766 _expensive_nodes->append(n); 3767 } else { 3768 // Clear control input and let IGVN optimize expensive nodes if 3769 // OptimizeExpensiveOps is off. 3770 n->set_req(0, NULL); 3771 } 3772 }