1 /* 2 * Copyright (c) 1997, 2022, 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/macroAssembler.hpp" 27 #include "asm/macroAssembler.inline.hpp" 28 #include "ci/ciReplay.hpp" 29 #include "classfile/javaClasses.hpp" 30 #include "code/exceptionHandlerTable.hpp" 31 #include "code/nmethod.hpp" 32 #include "compiler/compileBroker.hpp" 33 #include "compiler/compileLog.hpp" 34 #include "compiler/disassembler.hpp" 35 #include "compiler/oopMap.hpp" 36 #include "gc/shared/barrierSet.hpp" 37 #include "gc/shared/c2/barrierSetC2.hpp" 38 #include "jfr/jfrEvents.hpp" 39 #include "jvm_io.h" 40 #include "memory/allocation.hpp" 41 #include "memory/resourceArea.hpp" 42 #include "opto/addnode.hpp" 43 #include "opto/block.hpp" 44 #include "opto/c2compiler.hpp" 45 #include "opto/callGenerator.hpp" 46 #include "opto/callnode.hpp" 47 #include "opto/castnode.hpp" 48 #include "opto/cfgnode.hpp" 49 #include "opto/chaitin.hpp" 50 #include "opto/compile.hpp" 51 #include "opto/connode.hpp" 52 #include "opto/convertnode.hpp" 53 #include "opto/divnode.hpp" 54 #include "opto/escape.hpp" 55 #include "opto/idealGraphPrinter.hpp" 56 #include "opto/loopnode.hpp" 57 #include "opto/machnode.hpp" 58 #include "opto/macro.hpp" 59 #include "opto/matcher.hpp" 60 #include "opto/mathexactnode.hpp" 61 #include "opto/memnode.hpp" 62 #include "opto/mulnode.hpp" 63 #include "opto/narrowptrnode.hpp" 64 #include "opto/node.hpp" 65 #include "opto/opcodes.hpp" 66 #include "opto/output.hpp" 67 #include "opto/parse.hpp" 68 #include "opto/phaseX.hpp" 69 #include "opto/rootnode.hpp" 70 #include "opto/runtime.hpp" 71 #include "opto/stringopts.hpp" 72 #include "opto/type.hpp" 73 #include "opto/vector.hpp" 74 #include "opto/vectornode.hpp" 75 #include "runtime/globals_extension.hpp" 76 #include "runtime/sharedRuntime.hpp" 77 #include "runtime/signature.hpp" 78 #include "runtime/stubRoutines.hpp" 79 #include "runtime/timer.hpp" 80 #include "utilities/align.hpp" 81 #include "utilities/copy.hpp" 82 #include "utilities/macros.hpp" 83 #include "utilities/resourceHash.hpp" 84 85 // -------------------- Compile::mach_constant_base_node ----------------------- 86 // Constant table base node singleton. 87 MachConstantBaseNode* Compile::mach_constant_base_node() { 88 if (_mach_constant_base_node == NULL) { 89 _mach_constant_base_node = new MachConstantBaseNode(); 90 _mach_constant_base_node->add_req(C->root()); 91 } 92 return _mach_constant_base_node; 93 } 94 95 96 /// Support for intrinsics. 97 98 // Return the index at which m must be inserted (or already exists). 99 // The sort order is by the address of the ciMethod, with is_virtual as minor key. 100 class IntrinsicDescPair { 101 private: 102 ciMethod* _m; 103 bool _is_virtual; 104 public: 105 IntrinsicDescPair(ciMethod* m, bool is_virtual) : _m(m), _is_virtual(is_virtual) {} 106 static int compare(IntrinsicDescPair* const& key, CallGenerator* const& elt) { 107 ciMethod* m= elt->method(); 108 ciMethod* key_m = key->_m; 109 if (key_m < m) return -1; 110 else if (key_m > m) return 1; 111 else { 112 bool is_virtual = elt->is_virtual(); 113 bool key_virtual = key->_is_virtual; 114 if (key_virtual < is_virtual) return -1; 115 else if (key_virtual > is_virtual) return 1; 116 else return 0; 117 } 118 } 119 }; 120 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual, bool& found) { 121 #ifdef ASSERT 122 for (int i = 1; i < _intrinsics.length(); i++) { 123 CallGenerator* cg1 = _intrinsics.at(i-1); 124 CallGenerator* cg2 = _intrinsics.at(i); 125 assert(cg1->method() != cg2->method() 126 ? cg1->method() < cg2->method() 127 : cg1->is_virtual() < cg2->is_virtual(), 128 "compiler intrinsics list must stay sorted"); 129 } 130 #endif 131 IntrinsicDescPair pair(m, is_virtual); 132 return _intrinsics.find_sorted<IntrinsicDescPair*, IntrinsicDescPair::compare>(&pair, found); 133 } 134 135 void Compile::register_intrinsic(CallGenerator* cg) { 136 bool found = false; 137 int index = intrinsic_insertion_index(cg->method(), cg->is_virtual(), found); 138 assert(!found, "registering twice"); 139 _intrinsics.insert_before(index, cg); 140 assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked"); 141 } 142 143 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) { 144 assert(m->is_loaded(), "don't try this on unloaded methods"); 145 if (_intrinsics.length() > 0) { 146 bool found = false; 147 int index = intrinsic_insertion_index(m, is_virtual, found); 148 if (found) { 149 return _intrinsics.at(index); 150 } 151 } 152 // Lazily create intrinsics for intrinsic IDs well-known in the runtime. 153 if (m->intrinsic_id() != vmIntrinsics::_none && 154 m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) { 155 CallGenerator* cg = make_vm_intrinsic(m, is_virtual); 156 if (cg != NULL) { 157 // Save it for next time: 158 register_intrinsic(cg); 159 return cg; 160 } else { 161 gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled); 162 } 163 } 164 return NULL; 165 } 166 167 // Compile::make_vm_intrinsic is defined in library_call.cpp. 168 169 #ifndef PRODUCT 170 // statistics gathering... 171 172 juint Compile::_intrinsic_hist_count[vmIntrinsics::number_of_intrinsics()] = {0}; 173 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::number_of_intrinsics()] = {0}; 174 175 inline int as_int(vmIntrinsics::ID id) { 176 return vmIntrinsics::as_int(id); 177 } 178 179 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) { 180 assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob"); 181 int oflags = _intrinsic_hist_flags[as_int(id)]; 182 assert(flags != 0, "what happened?"); 183 if (is_virtual) { 184 flags |= _intrinsic_virtual; 185 } 186 bool changed = (flags != oflags); 187 if ((flags & _intrinsic_worked) != 0) { 188 juint count = (_intrinsic_hist_count[as_int(id)] += 1); 189 if (count == 1) { 190 changed = true; // first time 191 } 192 // increment the overall count also: 193 _intrinsic_hist_count[as_int(vmIntrinsics::_none)] += 1; 194 } 195 if (changed) { 196 if (((oflags ^ flags) & _intrinsic_virtual) != 0) { 197 // Something changed about the intrinsic's virtuality. 198 if ((flags & _intrinsic_virtual) != 0) { 199 // This is the first use of this intrinsic as a virtual call. 200 if (oflags != 0) { 201 // We already saw it as a non-virtual, so note both cases. 202 flags |= _intrinsic_both; 203 } 204 } else if ((oflags & _intrinsic_both) == 0) { 205 // This is the first use of this intrinsic as a non-virtual 206 flags |= _intrinsic_both; 207 } 208 } 209 _intrinsic_hist_flags[as_int(id)] = (jubyte) (oflags | flags); 210 } 211 // update the overall flags also: 212 _intrinsic_hist_flags[as_int(vmIntrinsics::_none)] |= (jubyte) flags; 213 return changed; 214 } 215 216 static char* format_flags(int flags, char* buf) { 217 buf[0] = 0; 218 if ((flags & Compile::_intrinsic_worked) != 0) strcat(buf, ",worked"); 219 if ((flags & Compile::_intrinsic_failed) != 0) strcat(buf, ",failed"); 220 if ((flags & Compile::_intrinsic_disabled) != 0) strcat(buf, ",disabled"); 221 if ((flags & Compile::_intrinsic_virtual) != 0) strcat(buf, ",virtual"); 222 if ((flags & Compile::_intrinsic_both) != 0) strcat(buf, ",nonvirtual"); 223 if (buf[0] == 0) strcat(buf, ","); 224 assert(buf[0] == ',', "must be"); 225 return &buf[1]; 226 } 227 228 void Compile::print_intrinsic_statistics() { 229 char flagsbuf[100]; 230 ttyLocker ttyl; 231 if (xtty != NULL) xtty->head("statistics type='intrinsic'"); 232 tty->print_cr("Compiler intrinsic usage:"); 233 juint total = _intrinsic_hist_count[as_int(vmIntrinsics::_none)]; 234 if (total == 0) total = 1; // avoid div0 in case of no successes 235 #define PRINT_STAT_LINE(name, c, f) \ 236 tty->print_cr(" %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f); 237 for (auto id : EnumRange<vmIntrinsicID>{}) { 238 int flags = _intrinsic_hist_flags[as_int(id)]; 239 juint count = _intrinsic_hist_count[as_int(id)]; 240 if ((flags | count) != 0) { 241 PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf)); 242 } 243 } 244 PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[as_int(vmIntrinsics::_none)], flagsbuf)); 245 if (xtty != NULL) xtty->tail("statistics"); 246 } 247 248 void Compile::print_statistics() { 249 { ttyLocker ttyl; 250 if (xtty != NULL) xtty->head("statistics type='opto'"); 251 Parse::print_statistics(); 252 PhaseStringOpts::print_statistics(); 253 PhaseCCP::print_statistics(); 254 PhaseRegAlloc::print_statistics(); 255 PhaseOutput::print_statistics(); 256 PhasePeephole::print_statistics(); 257 PhaseIdealLoop::print_statistics(); 258 ConnectionGraph::print_statistics(); 259 PhaseMacroExpand::print_statistics(); 260 if (xtty != NULL) xtty->tail("statistics"); 261 } 262 if (_intrinsic_hist_flags[as_int(vmIntrinsics::_none)] != 0) { 263 // put this under its own <statistics> element. 264 print_intrinsic_statistics(); 265 } 266 } 267 #endif //PRODUCT 268 269 void Compile::gvn_replace_by(Node* n, Node* nn) { 270 for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) { 271 Node* use = n->last_out(i); 272 bool is_in_table = initial_gvn()->hash_delete(use); 273 uint uses_found = 0; 274 for (uint j = 0; j < use->len(); j++) { 275 if (use->in(j) == n) { 276 if (j < use->req()) 277 use->set_req(j, nn); 278 else 279 use->set_prec(j, nn); 280 uses_found++; 281 } 282 } 283 if (is_in_table) { 284 // reinsert into table 285 initial_gvn()->hash_find_insert(use); 286 } 287 record_for_igvn(use); 288 i -= uses_found; // we deleted 1 or more copies of this edge 289 } 290 } 291 292 293 // Identify all nodes that are reachable from below, useful. 294 // Use breadth-first pass that records state in a Unique_Node_List, 295 // recursive traversal is slower. 296 void Compile::identify_useful_nodes(Unique_Node_List &useful) { 297 int estimated_worklist_size = live_nodes(); 298 useful.map( estimated_worklist_size, NULL ); // preallocate space 299 300 // Initialize worklist 301 if (root() != NULL) { useful.push(root()); } 302 // If 'top' is cached, declare it useful to preserve cached node 303 if( cached_top_node() ) { useful.push(cached_top_node()); } 304 305 // Push all useful nodes onto the list, breadthfirst 306 for( uint next = 0; next < useful.size(); ++next ) { 307 assert( next < unique(), "Unique useful nodes < total nodes"); 308 Node *n = useful.at(next); 309 uint max = n->len(); 310 for( uint i = 0; i < max; ++i ) { 311 Node *m = n->in(i); 312 if (not_a_node(m)) continue; 313 useful.push(m); 314 } 315 } 316 } 317 318 // Update dead_node_list with any missing dead nodes using useful 319 // list. Consider all non-useful nodes to be useless i.e., dead nodes. 320 void Compile::update_dead_node_list(Unique_Node_List &useful) { 321 uint max_idx = unique(); 322 VectorSet& useful_node_set = useful.member_set(); 323 324 for (uint node_idx = 0; node_idx < max_idx; node_idx++) { 325 // If node with index node_idx is not in useful set, 326 // mark it as dead in dead node list. 327 if (!useful_node_set.test(node_idx)) { 328 record_dead_node(node_idx); 329 } 330 } 331 } 332 333 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) { 334 int shift = 0; 335 for (int i = 0; i < inlines->length(); i++) { 336 CallGenerator* cg = inlines->at(i); 337 if (useful.member(cg->call_node())) { 338 if (shift > 0) { 339 inlines->at_put(i - shift, cg); 340 } 341 } else { 342 shift++; // skip over the dead element 343 } 344 } 345 if (shift > 0) { 346 inlines->trunc_to(inlines->length() - shift); // remove last elements from compacted array 347 } 348 } 349 350 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Node* dead) { 351 assert(dead != NULL && dead->is_Call(), "sanity"); 352 int found = 0; 353 for (int i = 0; i < inlines->length(); i++) { 354 if (inlines->at(i)->call_node() == dead) { 355 inlines->remove_at(i); 356 found++; 357 NOT_DEBUG( break; ) // elements are unique, so exit early 358 } 359 } 360 assert(found <= 1, "not unique"); 361 } 362 363 void Compile::remove_useless_nodes(GrowableArray<Node*>& node_list, Unique_Node_List& useful) { 364 for (int i = node_list.length() - 1; i >= 0; i--) { 365 Node* n = node_list.at(i); 366 if (!useful.member(n)) { 367 node_list.delete_at(i); // replaces i-th with last element which is known to be useful (already processed) 368 } 369 } 370 } 371 372 void Compile::remove_useless_node(Node* dead) { 373 remove_modified_node(dead); 374 375 // Constant node that has no out-edges and has only one in-edge from 376 // root is usually dead. However, sometimes reshaping walk makes 377 // it reachable by adding use edges. So, we will NOT count Con nodes 378 // as dead to be conservative about the dead node count at any 379 // given time. 380 if (!dead->is_Con()) { 381 record_dead_node(dead->_idx); 382 } 383 if (dead->is_macro()) { 384 remove_macro_node(dead); 385 } 386 if (dead->is_expensive()) { 387 remove_expensive_node(dead); 388 } 389 if (dead->Opcode() == Op_Opaque4) { 390 remove_skeleton_predicate_opaq(dead); 391 } 392 if (dead->for_post_loop_opts_igvn()) { 393 remove_from_post_loop_opts_igvn(dead); 394 } 395 if (dead->is_Call()) { 396 remove_useless_late_inlines( &_late_inlines, dead); 397 remove_useless_late_inlines( &_string_late_inlines, dead); 398 remove_useless_late_inlines( &_boxing_late_inlines, dead); 399 remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead); 400 401 if (dead->is_CallStaticJava()) { 402 remove_unstable_if_trap(dead->as_CallStaticJava(), false); 403 } 404 } 405 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 406 bs->unregister_potential_barrier_node(dead); 407 } 408 409 // Disconnect all useless nodes by disconnecting those at the boundary. 410 void Compile::disconnect_useless_nodes(Unique_Node_List &useful, Unique_Node_List* worklist) { 411 uint next = 0; 412 while (next < useful.size()) { 413 Node *n = useful.at(next++); 414 if (n->is_SafePoint()) { 415 // We're done with a parsing phase. Replaced nodes are not valid 416 // beyond that point. 417 n->as_SafePoint()->delete_replaced_nodes(); 418 } 419 // Use raw traversal of out edges since this code removes out edges 420 int max = n->outcnt(); 421 for (int j = 0; j < max; ++j) { 422 Node* child = n->raw_out(j); 423 if (!useful.member(child)) { 424 assert(!child->is_top() || child != top(), 425 "If top is cached in Compile object it is in useful list"); 426 // Only need to remove this out-edge to the useless node 427 n->raw_del_out(j); 428 --j; 429 --max; 430 } 431 } 432 if (n->outcnt() == 1 && n->has_special_unique_user()) { 433 worklist->push(n->unique_out()); 434 } 435 } 436 437 remove_useless_nodes(_macro_nodes, useful); // remove useless macro nodes 438 remove_useless_nodes(_predicate_opaqs, useful); // remove useless predicate opaque nodes 439 remove_useless_nodes(_skeleton_predicate_opaqs, useful); 440 remove_useless_nodes(_expensive_nodes, useful); // remove useless expensive nodes 441 remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass 442 remove_useless_unstable_if_traps(useful); // remove useless unstable_if traps 443 remove_useless_coarsened_locks(useful); // remove useless coarsened locks nodes 444 #ifdef ASSERT 445 if (_modified_nodes != NULL) { 446 _modified_nodes->remove_useless_nodes(useful.member_set()); 447 } 448 #endif 449 450 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 451 bs->eliminate_useless_gc_barriers(useful, this); 452 // clean up the late inline lists 453 remove_useless_late_inlines( &_late_inlines, useful); 454 remove_useless_late_inlines( &_string_late_inlines, useful); 455 remove_useless_late_inlines( &_boxing_late_inlines, useful); 456 remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful); 457 debug_only(verify_graph_edges(true/*check for no_dead_code*/);) 458 } 459 460 // ============================================================================ 461 //------------------------------CompileWrapper--------------------------------- 462 class CompileWrapper : public StackObj { 463 Compile *const _compile; 464 public: 465 CompileWrapper(Compile* compile); 466 467 ~CompileWrapper(); 468 }; 469 470 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) { 471 // the Compile* pointer is stored in the current ciEnv: 472 ciEnv* env = compile->env(); 473 assert(env == ciEnv::current(), "must already be a ciEnv active"); 474 assert(env->compiler_data() == NULL, "compile already active?"); 475 env->set_compiler_data(compile); 476 assert(compile == Compile::current(), "sanity"); 477 478 compile->set_type_dict(NULL); 479 compile->set_clone_map(new Dict(cmpkey, hashkey, _compile->comp_arena())); 480 compile->clone_map().set_clone_idx(0); 481 compile->set_type_last_size(0); 482 compile->set_last_tf(NULL, NULL); 483 compile->set_indexSet_arena(NULL); 484 compile->set_indexSet_free_block_list(NULL); 485 compile->init_type_arena(); 486 Type::Initialize(compile); 487 _compile->begin_method(); 488 _compile->clone_map().set_debug(_compile->has_method() && _compile->directive()->CloneMapDebugOption); 489 } 490 CompileWrapper::~CompileWrapper() { 491 // simulate crash during compilation 492 assert(CICrashAt < 0 || _compile->compile_id() != CICrashAt, "just as planned"); 493 494 _compile->end_method(); 495 _compile->env()->set_compiler_data(NULL); 496 } 497 498 499 //----------------------------print_compile_messages--------------------------- 500 void Compile::print_compile_messages() { 501 #ifndef PRODUCT 502 // Check if recompiling 503 if (!subsume_loads() && PrintOpto) { 504 // Recompiling without allowing machine instructions to subsume loads 505 tty->print_cr("*********************************************************"); 506 tty->print_cr("** Bailout: Recompile without subsuming loads **"); 507 tty->print_cr("*********************************************************"); 508 } 509 if ((do_escape_analysis() != DoEscapeAnalysis) && PrintOpto) { 510 // Recompiling without escape analysis 511 tty->print_cr("*********************************************************"); 512 tty->print_cr("** Bailout: Recompile without escape analysis **"); 513 tty->print_cr("*********************************************************"); 514 } 515 if (do_iterative_escape_analysis() != DoEscapeAnalysis && PrintOpto) { 516 // Recompiling without iterative escape analysis 517 tty->print_cr("*********************************************************"); 518 tty->print_cr("** Bailout: Recompile without iterative escape analysis**"); 519 tty->print_cr("*********************************************************"); 520 } 521 if ((eliminate_boxing() != EliminateAutoBox) && PrintOpto) { 522 // Recompiling without boxing elimination 523 tty->print_cr("*********************************************************"); 524 tty->print_cr("** Bailout: Recompile without boxing elimination **"); 525 tty->print_cr("*********************************************************"); 526 } 527 if ((do_locks_coarsening() != EliminateLocks) && PrintOpto) { 528 // Recompiling without locks coarsening 529 tty->print_cr("*********************************************************"); 530 tty->print_cr("** Bailout: Recompile without locks coarsening **"); 531 tty->print_cr("*********************************************************"); 532 } 533 if (env()->break_at_compile()) { 534 // Open the debugger when compiling this method. 535 tty->print("### Breaking when compiling: "); 536 method()->print_short_name(); 537 tty->cr(); 538 BREAKPOINT; 539 } 540 541 if( PrintOpto ) { 542 if (is_osr_compilation()) { 543 tty->print("[OSR]%3d", _compile_id); 544 } else { 545 tty->print("%3d", _compile_id); 546 } 547 } 548 #endif 549 } 550 551 #ifndef PRODUCT 552 void Compile::print_ideal_ir(const char* phase_name) { 553 ttyLocker ttyl; 554 // keep the following output all in one block 555 // This output goes directly to the tty, not the compiler log. 556 // To enable tools to match it up with the compilation activity, 557 // be sure to tag this tty output with the compile ID. 558 if (xtty != NULL) { 559 xtty->head("ideal compile_id='%d'%s compile_phase='%s'", 560 compile_id(), 561 is_osr_compilation() ? " compile_kind='osr'" : "", 562 phase_name); 563 } 564 if (_output == nullptr) { 565 tty->print_cr("AFTER: %s", phase_name); 566 // Print out all nodes in ascending order of index. 567 root()->dump_bfs(MaxNodeLimit, nullptr, "+S$"); 568 } else { 569 // Dump the node blockwise if we have a scheduling 570 _output->print_scheduling(); 571 } 572 573 if (xtty != NULL) { 574 xtty->tail("ideal"); 575 } 576 } 577 #endif 578 579 // ============================================================================ 580 //------------------------------Compile standard------------------------------- 581 debug_only( int Compile::_debug_idx = 100000; ) 582 583 // Compile a method. entry_bci is -1 for normal compilations and indicates 584 // the continuation bci for on stack replacement. 585 586 587 Compile::Compile( ciEnv* ci_env, ciMethod* target, int osr_bci, 588 Options options, DirectiveSet* directive) 589 : Phase(Compiler), 590 _compile_id(ci_env->compile_id()), 591 _options(options), 592 _method(target), 593 _entry_bci(osr_bci), 594 _ilt(NULL), 595 _stub_function(NULL), 596 _stub_name(NULL), 597 _stub_entry_point(NULL), 598 _max_node_limit(MaxNodeLimit), 599 _post_loop_opts_phase(false), 600 _inlining_progress(false), 601 _inlining_incrementally(false), 602 _do_cleanup(false), 603 _has_reserved_stack_access(target->has_reserved_stack_access()), 604 #ifndef PRODUCT 605 _igv_idx(0), 606 _trace_opto_output(directive->TraceOptoOutputOption), 607 #endif 608 _has_method_handle_invokes(false), 609 _clinit_barrier_on_entry(false), 610 _stress_seed(0), 611 _comp_arena(mtCompiler), 612 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())), 613 _env(ci_env), 614 _directive(directive), 615 _log(ci_env->log()), 616 _failure_reason(NULL), 617 _intrinsics (comp_arena(), 0, 0, NULL), 618 _macro_nodes (comp_arena(), 8, 0, NULL), 619 _predicate_opaqs (comp_arena(), 8, 0, NULL), 620 _skeleton_predicate_opaqs (comp_arena(), 8, 0, NULL), 621 _expensive_nodes (comp_arena(), 8, 0, NULL), 622 _for_post_loop_igvn(comp_arena(), 8, 0, NULL), 623 _unstable_if_traps (comp_arena(), 8, 0, NULL), 624 _coarsened_locks (comp_arena(), 8, 0, NULL), 625 _congraph(NULL), 626 NOT_PRODUCT(_igv_printer(NULL) COMMA) 627 _dead_node_list(comp_arena()), 628 _dead_node_count(0), 629 _node_arena(mtCompiler), 630 _old_arena(mtCompiler), 631 _mach_constant_base_node(NULL), 632 _Compile_types(mtCompiler), 633 _initial_gvn(NULL), 634 _for_igvn(NULL), 635 _late_inlines(comp_arena(), 2, 0, NULL), 636 _string_late_inlines(comp_arena(), 2, 0, NULL), 637 _boxing_late_inlines(comp_arena(), 2, 0, NULL), 638 _vector_reboxing_late_inlines(comp_arena(), 2, 0, NULL), 639 _late_inlines_pos(0), 640 _number_of_mh_late_inlines(0), 641 _print_inlining_stream(new (mtCompiler) stringStream()), 642 _print_inlining_list(NULL), 643 _print_inlining_idx(0), 644 _print_inlining_output(NULL), 645 _replay_inline_data(NULL), 646 _java_calls(0), 647 _inner_loops(0), 648 _interpreter_frame_size(0), 649 _output(NULL) 650 #ifndef PRODUCT 651 , _in_dump_cnt(0) 652 #endif 653 { 654 C = this; 655 CompileWrapper cw(this); 656 657 if (CITimeVerbose) { 658 tty->print(" "); 659 target->holder()->name()->print(); 660 tty->print("."); 661 target->print_short_name(); 662 tty->print(" "); 663 } 664 TraceTime t1("Total compilation time", &_t_totalCompilation, CITime, CITimeVerbose); 665 TraceTime t2(NULL, &_t_methodCompilation, CITime, false); 666 667 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY) 668 bool print_opto_assembly = directive->PrintOptoAssemblyOption; 669 // We can always print a disassembly, either abstract (hex dump) or 670 // with the help of a suitable hsdis library. Thus, we should not 671 // couple print_assembly and print_opto_assembly controls. 672 // But: always print opto and regular assembly on compile command 'print'. 673 bool print_assembly = directive->PrintAssemblyOption; 674 set_print_assembly(print_opto_assembly || print_assembly); 675 #else 676 set_print_assembly(false); // must initialize. 677 #endif 678 679 #ifndef PRODUCT 680 set_parsed_irreducible_loop(false); 681 682 if (directive->ReplayInlineOption) { 683 _replay_inline_data = ciReplay::load_inline_data(method(), entry_bci(), ci_env->comp_level()); 684 } 685 #endif 686 set_print_inlining(directive->PrintInliningOption || PrintOptoInlining); 687 set_print_intrinsics(directive->PrintIntrinsicsOption); 688 set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it 689 690 if (ProfileTraps RTM_OPT_ONLY( || UseRTMLocking )) { 691 // Make sure the method being compiled gets its own MDO, 692 // so we can at least track the decompile_count(). 693 // Need MDO to record RTM code generation state. 694 method()->ensure_method_data(); 695 } 696 697 Init(/*do_aliasing=*/ true); 698 699 print_compile_messages(); 700 701 _ilt = InlineTree::build_inline_tree_root(); 702 703 // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice 704 assert(num_alias_types() >= AliasIdxRaw, ""); 705 706 #define MINIMUM_NODE_HASH 1023 707 // Node list that Iterative GVN will start with 708 Unique_Node_List for_igvn(comp_arena()); 709 set_for_igvn(&for_igvn); 710 711 // GVN that will be run immediately on new nodes 712 uint estimated_size = method()->code_size()*4+64; 713 estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size); 714 PhaseGVN gvn(node_arena(), estimated_size); 715 set_initial_gvn(&gvn); 716 717 print_inlining_init(); 718 { // Scope for timing the parser 719 TracePhase tp("parse", &timers[_t_parser]); 720 721 // Put top into the hash table ASAP. 722 initial_gvn()->transform_no_reclaim(top()); 723 724 // Set up tf(), start(), and find a CallGenerator. 725 CallGenerator* cg = NULL; 726 if (is_osr_compilation()) { 727 const TypeTuple *domain = StartOSRNode::osr_domain(); 728 const TypeTuple *range = TypeTuple::make_range(method()->signature()); 729 init_tf(TypeFunc::make(domain, range)); 730 StartNode* s = new StartOSRNode(root(), domain); 731 initial_gvn()->set_type_bottom(s); 732 init_start(s); 733 cg = CallGenerator::for_osr(method(), entry_bci()); 734 } else { 735 // Normal case. 736 init_tf(TypeFunc::make(method())); 737 StartNode* s = new StartNode(root(), tf()->domain()); 738 initial_gvn()->set_type_bottom(s); 739 init_start(s); 740 if (method()->intrinsic_id() == vmIntrinsics::_Reference_get) { 741 // With java.lang.ref.reference.get() we must go through the 742 // intrinsic - even when get() is the root 743 // method of the compile - so that, if necessary, the value in 744 // the referent field of the reference object gets recorded by 745 // the pre-barrier code. 746 cg = find_intrinsic(method(), false); 747 } 748 if (cg == NULL) { 749 float past_uses = method()->interpreter_invocation_count(); 750 float expected_uses = past_uses; 751 cg = CallGenerator::for_inline(method(), expected_uses); 752 } 753 } 754 if (failing()) return; 755 if (cg == NULL) { 756 record_method_not_compilable("cannot parse method"); 757 return; 758 } 759 JVMState* jvms = build_start_state(start(), tf()); 760 if ((jvms = cg->generate(jvms)) == NULL) { 761 if (!failure_reason_is(C2Compiler::retry_class_loading_during_parsing())) { 762 record_method_not_compilable("method parse failed"); 763 } 764 return; 765 } 766 GraphKit kit(jvms); 767 768 if (!kit.stopped()) { 769 // Accept return values, and transfer control we know not where. 770 // This is done by a special, unique ReturnNode bound to root. 771 return_values(kit.jvms()); 772 } 773 774 if (kit.has_exceptions()) { 775 // Any exceptions that escape from this call must be rethrown 776 // to whatever caller is dynamically above us on the stack. 777 // This is done by a special, unique RethrowNode bound to root. 778 rethrow_exceptions(kit.transfer_exceptions_into_jvms()); 779 } 780 781 assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off"); 782 783 if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) { 784 inline_string_calls(true); 785 } 786 787 if (failing()) return; 788 789 print_method(PHASE_BEFORE_REMOVEUSELESS, 3); 790 791 // Remove clutter produced by parsing. 792 if (!failing()) { 793 ResourceMark rm; 794 PhaseRemoveUseless pru(initial_gvn(), &for_igvn); 795 } 796 } 797 798 // Note: Large methods are capped off in do_one_bytecode(). 799 if (failing()) return; 800 801 // After parsing, node notes are no longer automagic. 802 // They must be propagated by register_new_node_with_optimizer(), 803 // clone(), or the like. 804 set_default_node_notes(NULL); 805 806 #ifndef PRODUCT 807 if (should_print_igv(1)) { 808 _igv_printer->print_inlining(); 809 } 810 #endif 811 812 if (failing()) return; 813 NOT_PRODUCT( verify_graph_edges(); ) 814 815 // If any phase is randomized for stress testing, seed random number 816 // generation and log the seed for repeatability. 817 if (StressLCM || StressGCM || StressIGVN || StressCCP) { 818 if (FLAG_IS_DEFAULT(StressSeed) || (FLAG_IS_ERGO(StressSeed) && RepeatCompilation)) { 819 _stress_seed = static_cast<uint>(Ticks::now().nanoseconds()); 820 FLAG_SET_ERGO(StressSeed, _stress_seed); 821 } else { 822 _stress_seed = StressSeed; 823 } 824 if (_log != NULL) { 825 _log->elem("stress_test seed='%u'", _stress_seed); 826 } 827 } 828 829 // Now optimize 830 Optimize(); 831 if (failing()) return; 832 NOT_PRODUCT( verify_graph_edges(); ) 833 834 #ifndef PRODUCT 835 if (should_print_ideal()) { 836 print_ideal_ir("print_ideal"); 837 } 838 #endif 839 840 #ifdef ASSERT 841 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 842 bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen); 843 #endif 844 845 // Dump compilation data to replay it. 846 if (directive->DumpReplayOption) { 847 env()->dump_replay_data(_compile_id); 848 } 849 if (directive->DumpInlineOption && (ilt() != NULL)) { 850 env()->dump_inline_data(_compile_id); 851 } 852 853 // Now that we know the size of all the monitors we can add a fixed slot 854 // for the original deopt pc. 855 int next_slot = fixed_slots() + (sizeof(address) / VMRegImpl::stack_slot_size); 856 set_fixed_slots(next_slot); 857 858 // Compute when to use implicit null checks. Used by matching trap based 859 // nodes and NullCheck optimization. 860 set_allowed_deopt_reasons(); 861 862 // Now generate code 863 Code_Gen(); 864 } 865 866 //------------------------------Compile---------------------------------------- 867 // Compile a runtime stub 868 Compile::Compile( ciEnv* ci_env, 869 TypeFunc_generator generator, 870 address stub_function, 871 const char *stub_name, 872 int is_fancy_jump, 873 bool pass_tls, 874 bool return_pc, 875 DirectiveSet* directive) 876 : Phase(Compiler), 877 _compile_id(0), 878 _options(Options::for_runtime_stub()), 879 _method(NULL), 880 _entry_bci(InvocationEntryBci), 881 _stub_function(stub_function), 882 _stub_name(stub_name), 883 _stub_entry_point(NULL), 884 _max_node_limit(MaxNodeLimit), 885 _post_loop_opts_phase(false), 886 _inlining_progress(false), 887 _inlining_incrementally(false), 888 _has_reserved_stack_access(false), 889 #ifndef PRODUCT 890 _igv_idx(0), 891 _trace_opto_output(directive->TraceOptoOutputOption), 892 #endif 893 _has_method_handle_invokes(false), 894 _clinit_barrier_on_entry(false), 895 _stress_seed(0), 896 _comp_arena(mtCompiler), 897 _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())), 898 _env(ci_env), 899 _directive(directive), 900 _log(ci_env->log()), 901 _failure_reason(NULL), 902 _congraph(NULL), 903 NOT_PRODUCT(_igv_printer(NULL) COMMA) 904 _dead_node_list(comp_arena()), 905 _dead_node_count(0), 906 _node_arena(mtCompiler), 907 _old_arena(mtCompiler), 908 _mach_constant_base_node(NULL), 909 _Compile_types(mtCompiler), 910 _initial_gvn(NULL), 911 _for_igvn(NULL), 912 _number_of_mh_late_inlines(0), 913 _print_inlining_stream(new (mtCompiler) stringStream()), 914 _print_inlining_list(NULL), 915 _print_inlining_idx(0), 916 _print_inlining_output(NULL), 917 _replay_inline_data(NULL), 918 _java_calls(0), 919 _inner_loops(0), 920 _interpreter_frame_size(0), 921 _output(NULL), 922 #ifndef PRODUCT 923 _in_dump_cnt(0), 924 #endif 925 _allowed_reasons(0) { 926 C = this; 927 928 TraceTime t1(NULL, &_t_totalCompilation, CITime, false); 929 TraceTime t2(NULL, &_t_stubCompilation, CITime, false); 930 931 #ifndef PRODUCT 932 set_print_assembly(PrintFrameConverterAssembly); 933 set_parsed_irreducible_loop(false); 934 #else 935 set_print_assembly(false); // Must initialize. 936 #endif 937 set_has_irreducible_loop(false); // no loops 938 939 CompileWrapper cw(this); 940 Init(/*do_aliasing=*/ false); 941 init_tf((*generator)()); 942 943 { 944 // The following is a dummy for the sake of GraphKit::gen_stub 945 Unique_Node_List for_igvn(comp_arena()); 946 set_for_igvn(&for_igvn); // not used, but some GraphKit guys push on this 947 PhaseGVN gvn(Thread::current()->resource_area(),255); 948 set_initial_gvn(&gvn); // not significant, but GraphKit guys use it pervasively 949 gvn.transform_no_reclaim(top()); 950 951 GraphKit kit; 952 kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc); 953 } 954 955 NOT_PRODUCT( verify_graph_edges(); ) 956 957 Code_Gen(); 958 } 959 960 //------------------------------Init------------------------------------------- 961 // Prepare for a single compilation 962 void Compile::Init(bool aliasing) { 963 _do_aliasing = aliasing; 964 _unique = 0; 965 _regalloc = NULL; 966 967 _tf = NULL; // filled in later 968 _top = NULL; // cached later 969 _matcher = NULL; // filled in later 970 _cfg = NULL; // filled in later 971 972 IA32_ONLY( set_24_bit_selection_and_mode(true, false); ) 973 974 _node_note_array = NULL; 975 _default_node_notes = NULL; 976 DEBUG_ONLY( _modified_nodes = NULL; ) // Used in Optimize() 977 978 _immutable_memory = NULL; // filled in at first inquiry 979 980 // Globally visible Nodes 981 // First set TOP to NULL to give safe behavior during creation of RootNode 982 set_cached_top_node(NULL); 983 set_root(new RootNode()); 984 // Now that you have a Root to point to, create the real TOP 985 set_cached_top_node( new ConNode(Type::TOP) ); 986 set_recent_alloc(NULL, NULL); 987 988 // Create Debug Information Recorder to record scopes, oopmaps, etc. 989 env()->set_oop_recorder(new OopRecorder(env()->arena())); 990 env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder())); 991 env()->set_dependencies(new Dependencies(env())); 992 993 _fixed_slots = 0; 994 set_has_split_ifs(false); 995 set_has_loops(false); // first approximation 996 set_has_stringbuilder(false); 997 set_has_boxed_value(false); 998 _trap_can_recompile = false; // no traps emitted yet 999 _major_progress = true; // start out assuming good things will happen 1000 set_has_unsafe_access(false); 1001 set_max_vector_size(0); 1002 set_clear_upper_avx(false); //false as default for clear upper bits of ymm registers 1003 Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist)); 1004 set_decompile_count(0); 1005 1006 set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption); 1007 _loop_opts_cnt = LoopOptsCount; 1008 set_do_inlining(Inline); 1009 set_max_inline_size(MaxInlineSize); 1010 set_freq_inline_size(FreqInlineSize); 1011 set_do_scheduling(OptoScheduling); 1012 1013 set_do_vector_loop(false); 1014 set_has_monitors(false); 1015 reset_max_monitors(); 1016 1017 if (AllowVectorizeOnDemand) { 1018 if (has_method() && (_directive->VectorizeOption || _directive->VectorizeDebugOption)) { 1019 set_do_vector_loop(true); 1020 NOT_PRODUCT(if (do_vector_loop() && Verbose) {tty->print("Compile::Init: do vectorized loops (SIMD like) for method %s\n", method()->name()->as_quoted_ascii());}) 1021 } else if (has_method() && method()->name() != 0 && 1022 method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) { 1023 set_do_vector_loop(true); 1024 } 1025 } 1026 set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally 1027 NOT_PRODUCT(if (use_cmove() && Verbose && has_method()) {tty->print("Compile::Init: use CMove without profitability tests for method %s\n", method()->name()->as_quoted_ascii());}) 1028 1029 set_rtm_state(NoRTM); // No RTM lock eliding by default 1030 _max_node_limit = _directive->MaxNodeLimitOption; 1031 1032 #if INCLUDE_RTM_OPT 1033 if (UseRTMLocking && has_method() && (method()->method_data_or_null() != NULL)) { 1034 int rtm_state = method()->method_data()->rtm_state(); 1035 if (method_has_option(CompileCommand::NoRTMLockEliding) || ((rtm_state & NoRTM) != 0)) { 1036 // Don't generate RTM lock eliding code. 1037 set_rtm_state(NoRTM); 1038 } else if (method_has_option(CompileCommand::UseRTMLockEliding) || ((rtm_state & UseRTM) != 0) || !UseRTMDeopt) { 1039 // Generate RTM lock eliding code without abort ratio calculation code. 1040 set_rtm_state(UseRTM); 1041 } else if (UseRTMDeopt) { 1042 // Generate RTM lock eliding code and include abort ratio calculation 1043 // code if UseRTMDeopt is on. 1044 set_rtm_state(ProfileRTM); 1045 } 1046 } 1047 #endif 1048 if (VM_Version::supports_fast_class_init_checks() && has_method() && !is_osr_compilation() && method()->needs_clinit_barrier()) { 1049 set_clinit_barrier_on_entry(true); 1050 } 1051 if (debug_info()->recording_non_safepoints()) { 1052 set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*> 1053 (comp_arena(), 8, 0, NULL)); 1054 set_default_node_notes(Node_Notes::make(this)); 1055 } 1056 1057 const int grow_ats = 16; 1058 _max_alias_types = grow_ats; 1059 _alias_types = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats); 1060 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, grow_ats); 1061 Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats); 1062 { 1063 for (int i = 0; i < grow_ats; i++) _alias_types[i] = &ats[i]; 1064 } 1065 // Initialize the first few types. 1066 _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL); 1067 _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM); 1068 _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM); 1069 _num_alias_types = AliasIdxRaw+1; 1070 // Zero out the alias type cache. 1071 Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache)); 1072 // A NULL adr_type hits in the cache right away. Preload the right answer. 1073 probe_alias_cache(NULL)->_index = AliasIdxTop; 1074 1075 #ifdef ASSERT 1076 _type_verify_symmetry = true; 1077 _phase_optimize_finished = false; 1078 _exception_backedge = false; 1079 #endif 1080 } 1081 1082 //---------------------------init_start---------------------------------------- 1083 // Install the StartNode on this compile object. 1084 void Compile::init_start(StartNode* s) { 1085 if (failing()) 1086 return; // already failing 1087 assert(s == start(), ""); 1088 } 1089 1090 /** 1091 * Return the 'StartNode'. We must not have a pending failure, since the ideal graph 1092 * can be in an inconsistent state, i.e., we can get segmentation faults when traversing 1093 * the ideal graph. 1094 */ 1095 StartNode* Compile::start() const { 1096 assert (!failing(), "Must not have pending failure. Reason is: %s", failure_reason()); 1097 for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) { 1098 Node* start = root()->fast_out(i); 1099 if (start->is_Start()) { 1100 return start->as_Start(); 1101 } 1102 } 1103 fatal("Did not find Start node!"); 1104 return NULL; 1105 } 1106 1107 //-------------------------------immutable_memory------------------------------------- 1108 // Access immutable memory 1109 Node* Compile::immutable_memory() { 1110 if (_immutable_memory != NULL) { 1111 return _immutable_memory; 1112 } 1113 StartNode* s = start(); 1114 for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) { 1115 Node *p = s->fast_out(i); 1116 if (p != s && p->as_Proj()->_con == TypeFunc::Memory) { 1117 _immutable_memory = p; 1118 return _immutable_memory; 1119 } 1120 } 1121 ShouldNotReachHere(); 1122 return NULL; 1123 } 1124 1125 //----------------------set_cached_top_node------------------------------------ 1126 // Install the cached top node, and make sure Node::is_top works correctly. 1127 void Compile::set_cached_top_node(Node* tn) { 1128 if (tn != NULL) verify_top(tn); 1129 Node* old_top = _top; 1130 _top = tn; 1131 // Calling Node::setup_is_top allows the nodes the chance to adjust 1132 // their _out arrays. 1133 if (_top != NULL) _top->setup_is_top(); 1134 if (old_top != NULL) old_top->setup_is_top(); 1135 assert(_top == NULL || top()->is_top(), ""); 1136 } 1137 1138 #ifdef ASSERT 1139 uint Compile::count_live_nodes_by_graph_walk() { 1140 Unique_Node_List useful(comp_arena()); 1141 // Get useful node list by walking the graph. 1142 identify_useful_nodes(useful); 1143 return useful.size(); 1144 } 1145 1146 void Compile::print_missing_nodes() { 1147 1148 // Return if CompileLog is NULL and PrintIdealNodeCount is false. 1149 if ((_log == NULL) && (! PrintIdealNodeCount)) { 1150 return; 1151 } 1152 1153 // This is an expensive function. It is executed only when the user 1154 // specifies VerifyIdealNodeCount option or otherwise knows the 1155 // additional work that needs to be done to identify reachable nodes 1156 // by walking the flow graph and find the missing ones using 1157 // _dead_node_list. 1158 1159 Unique_Node_List useful(comp_arena()); 1160 // Get useful node list by walking the graph. 1161 identify_useful_nodes(useful); 1162 1163 uint l_nodes = C->live_nodes(); 1164 uint l_nodes_by_walk = useful.size(); 1165 1166 if (l_nodes != l_nodes_by_walk) { 1167 if (_log != NULL) { 1168 _log->begin_head("mismatched_nodes count='%d'", abs((int) (l_nodes - l_nodes_by_walk))); 1169 _log->stamp(); 1170 _log->end_head(); 1171 } 1172 VectorSet& useful_member_set = useful.member_set(); 1173 int last_idx = l_nodes_by_walk; 1174 for (int i = 0; i < last_idx; i++) { 1175 if (useful_member_set.test(i)) { 1176 if (_dead_node_list.test(i)) { 1177 if (_log != NULL) { 1178 _log->elem("mismatched_node_info node_idx='%d' type='both live and dead'", i); 1179 } 1180 if (PrintIdealNodeCount) { 1181 // Print the log message to tty 1182 tty->print_cr("mismatched_node idx='%d' both live and dead'", i); 1183 useful.at(i)->dump(); 1184 } 1185 } 1186 } 1187 else if (! _dead_node_list.test(i)) { 1188 if (_log != NULL) { 1189 _log->elem("mismatched_node_info node_idx='%d' type='neither live nor dead'", i); 1190 } 1191 if (PrintIdealNodeCount) { 1192 // Print the log message to tty 1193 tty->print_cr("mismatched_node idx='%d' type='neither live nor dead'", i); 1194 } 1195 } 1196 } 1197 if (_log != NULL) { 1198 _log->tail("mismatched_nodes"); 1199 } 1200 } 1201 } 1202 void Compile::record_modified_node(Node* n) { 1203 if (_modified_nodes != NULL && !_inlining_incrementally && !n->is_Con()) { 1204 _modified_nodes->push(n); 1205 } 1206 } 1207 1208 void Compile::remove_modified_node(Node* n) { 1209 if (_modified_nodes != NULL) { 1210 _modified_nodes->remove(n); 1211 } 1212 } 1213 #endif 1214 1215 #ifndef PRODUCT 1216 void Compile::verify_top(Node* tn) const { 1217 if (tn != NULL) { 1218 assert(tn->is_Con(), "top node must be a constant"); 1219 assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type"); 1220 assert(tn->in(0) != NULL, "must have live top node"); 1221 } 1222 } 1223 #endif 1224 1225 1226 ///-------------------Managing Per-Node Debug & Profile Info------------------- 1227 1228 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) { 1229 guarantee(arr != NULL, ""); 1230 int num_blocks = arr->length(); 1231 if (grow_by < num_blocks) grow_by = num_blocks; 1232 int num_notes = grow_by * _node_notes_block_size; 1233 Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes); 1234 Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes)); 1235 while (num_notes > 0) { 1236 arr->append(notes); 1237 notes += _node_notes_block_size; 1238 num_notes -= _node_notes_block_size; 1239 } 1240 assert(num_notes == 0, "exact multiple, please"); 1241 } 1242 1243 bool Compile::copy_node_notes_to(Node* dest, Node* source) { 1244 if (source == NULL || dest == NULL) return false; 1245 1246 if (dest->is_Con()) 1247 return false; // Do not push debug info onto constants. 1248 1249 #ifdef ASSERT 1250 // Leave a bread crumb trail pointing to the original node: 1251 if (dest != NULL && dest != source && dest->debug_orig() == NULL) { 1252 dest->set_debug_orig(source); 1253 } 1254 #endif 1255 1256 if (node_note_array() == NULL) 1257 return false; // Not collecting any notes now. 1258 1259 // This is a copy onto a pre-existing node, which may already have notes. 1260 // If both nodes have notes, do not overwrite any pre-existing notes. 1261 Node_Notes* source_notes = node_notes_at(source->_idx); 1262 if (source_notes == NULL || source_notes->is_clear()) return false; 1263 Node_Notes* dest_notes = node_notes_at(dest->_idx); 1264 if (dest_notes == NULL || dest_notes->is_clear()) { 1265 return set_node_notes_at(dest->_idx, source_notes); 1266 } 1267 1268 Node_Notes merged_notes = (*source_notes); 1269 // The order of operations here ensures that dest notes will win... 1270 merged_notes.update_from(dest_notes); 1271 return set_node_notes_at(dest->_idx, &merged_notes); 1272 } 1273 1274 1275 //--------------------------allow_range_check_smearing------------------------- 1276 // Gating condition for coalescing similar range checks. 1277 // Sometimes we try 'speculatively' replacing a series of a range checks by a 1278 // single covering check that is at least as strong as any of them. 1279 // If the optimization succeeds, the simplified (strengthened) range check 1280 // will always succeed. If it fails, we will deopt, and then give up 1281 // on the optimization. 1282 bool Compile::allow_range_check_smearing() const { 1283 // If this method has already thrown a range-check, 1284 // assume it was because we already tried range smearing 1285 // and it failed. 1286 uint already_trapped = trap_count(Deoptimization::Reason_range_check); 1287 return !already_trapped; 1288 } 1289 1290 1291 //------------------------------flatten_alias_type----------------------------- 1292 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { 1293 assert(do_aliasing(), "Aliasing should be enabled"); 1294 int offset = tj->offset(); 1295 TypePtr::PTR ptr = tj->ptr(); 1296 1297 // Known instance (scalarizable allocation) alias only with itself. 1298 bool is_known_inst = tj->isa_oopptr() != NULL && 1299 tj->is_oopptr()->is_known_instance(); 1300 1301 // Process weird unsafe references. 1302 if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) { 1303 assert(InlineUnsafeOps || StressReflectiveCode, "indeterminate pointers come only from unsafe ops"); 1304 assert(!is_known_inst, "scalarizable allocation should not have unsafe references"); 1305 tj = TypeOopPtr::BOTTOM; 1306 ptr = tj->ptr(); 1307 offset = tj->offset(); 1308 } 1309 1310 // Array pointers need some flattening 1311 const TypeAryPtr* ta = tj->isa_aryptr(); 1312 if (ta && ta->is_stable()) { 1313 // Erase stability property for alias analysis. 1314 tj = ta = ta->cast_to_stable(false); 1315 } 1316 if( ta && is_known_inst ) { 1317 if ( offset != Type::OffsetBot && 1318 offset > arrayOopDesc::length_offset_in_bytes() ) { 1319 offset = Type::OffsetBot; // Flatten constant access into array body only 1320 tj = ta = ta-> 1321 remove_speculative()-> 1322 cast_to_ptr_type(ptr)-> 1323 with_offset(offset); 1324 } 1325 } else if (ta) { 1326 // For arrays indexed by constant indices, we flatten the alias 1327 // space to include all of the array body. Only the header, klass 1328 // and array length can be accessed un-aliased. 1329 if( offset != Type::OffsetBot ) { 1330 if( ta->const_oop() ) { // MethodData* or Method* 1331 offset = Type::OffsetBot; // Flatten constant access into array body 1332 tj = ta = ta-> 1333 remove_speculative()-> 1334 cast_to_ptr_type(ptr)-> 1335 cast_to_exactness(false)-> 1336 with_offset(offset); 1337 } else if( offset == arrayOopDesc::length_offset_in_bytes() ) { 1338 // range is OK as-is. 1339 tj = ta = TypeAryPtr::RANGE; 1340 } else if( offset == oopDesc::klass_offset_in_bytes() ) { 1341 tj = TypeInstPtr::KLASS; // all klass loads look alike 1342 ta = TypeAryPtr::RANGE; // generic ignored junk 1343 ptr = TypePtr::BotPTR; 1344 } else if( offset == oopDesc::mark_offset_in_bytes() ) { 1345 tj = TypeInstPtr::MARK; 1346 ta = TypeAryPtr::RANGE; // generic ignored junk 1347 ptr = TypePtr::BotPTR; 1348 } else { // Random constant offset into array body 1349 offset = Type::OffsetBot; // Flatten constant access into array body 1350 tj = ta = ta-> 1351 remove_speculative()-> 1352 cast_to_ptr_type(ptr)-> 1353 cast_to_exactness(false)-> 1354 with_offset(offset); 1355 } 1356 } 1357 // Arrays of fixed size alias with arrays of unknown size. 1358 if (ta->size() != TypeInt::POS) { 1359 const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS); 1360 tj = ta = ta-> 1361 remove_speculative()-> 1362 cast_to_ptr_type(ptr)-> 1363 with_ary(tary)-> 1364 cast_to_exactness(false); 1365 } 1366 // Arrays of known objects become arrays of unknown objects. 1367 if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) { 1368 const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size()); 1369 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset); 1370 } 1371 if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) { 1372 const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size()); 1373 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset); 1374 } 1375 // Arrays of bytes and of booleans both use 'bastore' and 'baload' so 1376 // cannot be distinguished by bytecode alone. 1377 if (ta->elem() == TypeInt::BOOL) { 1378 const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size()); 1379 ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE); 1380 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset); 1381 } 1382 // During the 2nd round of IterGVN, NotNull castings are removed. 1383 // Make sure the Bottom and NotNull variants alias the same. 1384 // Also, make sure exact and non-exact variants alias the same. 1385 if (ptr == TypePtr::NotNull || ta->klass_is_exact() || ta->speculative() != NULL) { 1386 tj = ta = ta-> 1387 remove_speculative()-> 1388 cast_to_ptr_type(TypePtr::BotPTR)-> 1389 cast_to_exactness(false)-> 1390 with_offset(offset); 1391 } 1392 } 1393 1394 // Oop pointers need some flattening 1395 const TypeInstPtr *to = tj->isa_instptr(); 1396 if (to && to != TypeOopPtr::BOTTOM) { 1397 ciInstanceKlass* ik = to->instance_klass(); 1398 if( ptr == TypePtr::Constant ) { 1399 if (ik != ciEnv::current()->Class_klass() || 1400 offset < ik->layout_helper_size_in_bytes()) { 1401 // No constant oop pointers (such as Strings); they alias with 1402 // unknown strings. 1403 assert(!is_known_inst, "not scalarizable allocation"); 1404 tj = to = to-> 1405 cast_to_instance_id(TypeOopPtr::InstanceBot)-> 1406 remove_speculative()-> 1407 cast_to_ptr_type(TypePtr::BotPTR)-> 1408 cast_to_exactness(false); 1409 } 1410 } else if( is_known_inst ) { 1411 tj = to; // Keep NotNull and klass_is_exact for instance type 1412 } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) { 1413 // During the 2nd round of IterGVN, NotNull castings are removed. 1414 // Make sure the Bottom and NotNull variants alias the same. 1415 // Also, make sure exact and non-exact variants alias the same. 1416 tj = to = to-> 1417 remove_speculative()-> 1418 cast_to_instance_id(TypeOopPtr::InstanceBot)-> 1419 cast_to_ptr_type(TypePtr::BotPTR)-> 1420 cast_to_exactness(false); 1421 } 1422 if (to->speculative() != NULL) { 1423 tj = to = to->remove_speculative(); 1424 } 1425 // Canonicalize the holder of this field 1426 if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) { 1427 // First handle header references such as a LoadKlassNode, even if the 1428 // object's klass is unloaded at compile time (4965979). 1429 if (!is_known_inst) { // Do it only for non-instance types 1430 tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset); 1431 } 1432 } else if (offset < 0 || offset >= ik->layout_helper_size_in_bytes()) { 1433 // Static fields are in the space above the normal instance 1434 // fields in the java.lang.Class instance. 1435 if (ik != ciEnv::current()->Class_klass()) { 1436 to = NULL; 1437 tj = TypeOopPtr::BOTTOM; 1438 offset = tj->offset(); 1439 } 1440 } else { 1441 ciInstanceKlass *canonical_holder = ik->get_canonical_holder(offset); 1442 assert(offset < canonical_holder->layout_helper_size_in_bytes(), ""); 1443 if (!ik->equals(canonical_holder) || tj->offset() != offset) { 1444 if( is_known_inst ) { 1445 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id()); 1446 } else { 1447 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset); 1448 } 1449 } 1450 } 1451 } 1452 1453 // Klass pointers to object array klasses need some flattening 1454 const TypeKlassPtr *tk = tj->isa_klassptr(); 1455 if( tk ) { 1456 // If we are referencing a field within a Klass, we need 1457 // to assume the worst case of an Object. Both exact and 1458 // inexact types must flatten to the same alias class so 1459 // use NotNull as the PTR. 1460 if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) { 1461 tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, 1462 env()->Object_klass(), 1463 offset); 1464 } 1465 1466 if (tk->isa_aryklassptr() && tk->is_aryklassptr()->elem()->isa_klassptr()) { 1467 ciKlass* k = ciObjArrayKlass::make(env()->Object_klass()); 1468 if (!k || !k->is_loaded()) { // Only fails for some -Xcomp runs 1469 tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, env()->Object_klass(), offset); 1470 } else { 1471 tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk->is_aryklassptr()->elem(), k, offset); 1472 } 1473 } 1474 1475 // Check for precise loads from the primary supertype array and force them 1476 // to the supertype cache alias index. Check for generic array loads from 1477 // the primary supertype array and also force them to the supertype cache 1478 // alias index. Since the same load can reach both, we need to merge 1479 // these 2 disparate memories into the same alias class. Since the 1480 // primary supertype array is read-only, there's no chance of confusion 1481 // where we bypass an array load and an array store. 1482 int primary_supers_offset = in_bytes(Klass::primary_supers_offset()); 1483 if (offset == Type::OffsetBot || 1484 (offset >= primary_supers_offset && 1485 offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) || 1486 offset == (int)in_bytes(Klass::secondary_super_cache_offset())) { 1487 offset = in_bytes(Klass::secondary_super_cache_offset()); 1488 tj = tk = tk->with_offset(offset); 1489 } 1490 } 1491 1492 // Flatten all Raw pointers together. 1493 if (tj->base() == Type::RawPtr) 1494 tj = TypeRawPtr::BOTTOM; 1495 1496 if (tj->base() == Type::AnyPtr) 1497 tj = TypePtr::BOTTOM; // An error, which the caller must check for. 1498 1499 offset = tj->offset(); 1500 assert( offset != Type::OffsetTop, "Offset has fallen from constant" ); 1501 1502 assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) || 1503 (offset == Type::OffsetBot && tj->base() == Type::AryPtr) || 1504 (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) || 1505 (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) || 1506 (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) || 1507 (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) || 1508 (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr), 1509 "For oops, klasses, raw offset must be constant; for arrays the offset is never known" ); 1510 assert( tj->ptr() != TypePtr::TopPTR && 1511 tj->ptr() != TypePtr::AnyNull && 1512 tj->ptr() != TypePtr::Null, "No imprecise addresses" ); 1513 // assert( tj->ptr() != TypePtr::Constant || 1514 // tj->base() == Type::RawPtr || 1515 // tj->base() == Type::KlassPtr, "No constant oop addresses" ); 1516 1517 return tj; 1518 } 1519 1520 void Compile::AliasType::Init(int i, const TypePtr* at) { 1521 assert(AliasIdxTop <= i && i < Compile::current()->_max_alias_types, "Invalid alias index"); 1522 _index = i; 1523 _adr_type = at; 1524 _field = NULL; 1525 _element = NULL; 1526 _is_rewritable = true; // default 1527 const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL; 1528 if (atoop != NULL && atoop->is_known_instance()) { 1529 const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot); 1530 _general_index = Compile::current()->get_alias_index(gt); 1531 } else { 1532 _general_index = 0; 1533 } 1534 } 1535 1536 BasicType Compile::AliasType::basic_type() const { 1537 if (element() != NULL) { 1538 const Type* element = adr_type()->is_aryptr()->elem(); 1539 return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type(); 1540 } if (field() != NULL) { 1541 return field()->layout_type(); 1542 } else { 1543 return T_ILLEGAL; // unknown 1544 } 1545 } 1546 1547 //---------------------------------print_on------------------------------------ 1548 #ifndef PRODUCT 1549 void Compile::AliasType::print_on(outputStream* st) { 1550 if (index() < 10) 1551 st->print("@ <%d> ", index()); 1552 else st->print("@ <%d>", index()); 1553 st->print(is_rewritable() ? " " : " RO"); 1554 int offset = adr_type()->offset(); 1555 if (offset == Type::OffsetBot) 1556 st->print(" +any"); 1557 else st->print(" +%-3d", offset); 1558 st->print(" in "); 1559 adr_type()->dump_on(st); 1560 const TypeOopPtr* tjp = adr_type()->isa_oopptr(); 1561 if (field() != NULL && tjp) { 1562 if (tjp->is_instptr()->instance_klass() != field()->holder() || 1563 tjp->offset() != field()->offset_in_bytes()) { 1564 st->print(" != "); 1565 field()->print(); 1566 st->print(" ***"); 1567 } 1568 } 1569 } 1570 1571 void print_alias_types() { 1572 Compile* C = Compile::current(); 1573 tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1); 1574 for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) { 1575 C->alias_type(idx)->print_on(tty); 1576 tty->cr(); 1577 } 1578 } 1579 #endif 1580 1581 1582 //----------------------------probe_alias_cache-------------------------------- 1583 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) { 1584 intptr_t key = (intptr_t) adr_type; 1585 key ^= key >> logAliasCacheSize; 1586 return &_alias_cache[key & right_n_bits(logAliasCacheSize)]; 1587 } 1588 1589 1590 //-----------------------------grow_alias_types-------------------------------- 1591 void Compile::grow_alias_types() { 1592 const int old_ats = _max_alias_types; // how many before? 1593 const int new_ats = old_ats; // how many more? 1594 const int grow_ats = old_ats+new_ats; // how many now? 1595 _max_alias_types = grow_ats; 1596 _alias_types = REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats); 1597 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats); 1598 Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats); 1599 for (int i = 0; i < new_ats; i++) _alias_types[old_ats+i] = &ats[i]; 1600 } 1601 1602 1603 //--------------------------------find_alias_type------------------------------ 1604 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) { 1605 if (!do_aliasing()) { 1606 return alias_type(AliasIdxBot); 1607 } 1608 1609 AliasCacheEntry* ace = probe_alias_cache(adr_type); 1610 if (ace->_adr_type == adr_type) { 1611 return alias_type(ace->_index); 1612 } 1613 1614 // Handle special cases. 1615 if (adr_type == NULL) return alias_type(AliasIdxTop); 1616 if (adr_type == TypePtr::BOTTOM) return alias_type(AliasIdxBot); 1617 1618 // Do it the slow way. 1619 const TypePtr* flat = flatten_alias_type(adr_type); 1620 1621 #ifdef ASSERT 1622 { 1623 ResourceMark rm; 1624 assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s", 1625 Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat))); 1626 assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s", 1627 Type::str(adr_type)); 1628 if (flat->isa_oopptr() && !flat->isa_klassptr()) { 1629 const TypeOopPtr* foop = flat->is_oopptr(); 1630 // Scalarizable allocations have exact klass always. 1631 bool exact = !foop->klass_is_exact() || foop->is_known_instance(); 1632 const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr(); 1633 assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type: foop = %s; xoop = %s", 1634 Type::str(foop), Type::str(xoop)); 1635 } 1636 } 1637 #endif 1638 1639 int idx = AliasIdxTop; 1640 for (int i = 0; i < num_alias_types(); i++) { 1641 if (alias_type(i)->adr_type() == flat) { 1642 idx = i; 1643 break; 1644 } 1645 } 1646 1647 if (idx == AliasIdxTop) { 1648 if (no_create) return NULL; 1649 // Grow the array if necessary. 1650 if (_num_alias_types == _max_alias_types) grow_alias_types(); 1651 // Add a new alias type. 1652 idx = _num_alias_types++; 1653 _alias_types[idx]->Init(idx, flat); 1654 if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false); 1655 if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false); 1656 if (flat->isa_instptr()) { 1657 if (flat->offset() == java_lang_Class::klass_offset() 1658 && flat->is_instptr()->instance_klass() == env()->Class_klass()) 1659 alias_type(idx)->set_rewritable(false); 1660 } 1661 if (flat->isa_aryptr()) { 1662 #ifdef ASSERT 1663 const int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE); 1664 // (T_BYTE has the weakest alignment and size restrictions...) 1665 assert(flat->offset() < header_size_min, "array body reference must be OffsetBot"); 1666 #endif 1667 if (flat->offset() == TypePtr::OffsetBot) { 1668 alias_type(idx)->set_element(flat->is_aryptr()->elem()); 1669 } 1670 } 1671 if (flat->isa_klassptr()) { 1672 if (flat->offset() == in_bytes(Klass::super_check_offset_offset())) 1673 alias_type(idx)->set_rewritable(false); 1674 if (flat->offset() == in_bytes(Klass::modifier_flags_offset())) 1675 alias_type(idx)->set_rewritable(false); 1676 if (flat->offset() == in_bytes(Klass::access_flags_offset())) 1677 alias_type(idx)->set_rewritable(false); 1678 if (flat->offset() == in_bytes(Klass::java_mirror_offset())) 1679 alias_type(idx)->set_rewritable(false); 1680 if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset())) 1681 alias_type(idx)->set_rewritable(false); 1682 } 1683 // %%% (We would like to finalize JavaThread::threadObj_offset(), 1684 // but the base pointer type is not distinctive enough to identify 1685 // references into JavaThread.) 1686 1687 // Check for final fields. 1688 const TypeInstPtr* tinst = flat->isa_instptr(); 1689 if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) { 1690 ciField* field; 1691 if (tinst->const_oop() != NULL && 1692 tinst->instance_klass() == ciEnv::current()->Class_klass() && 1693 tinst->offset() >= (tinst->instance_klass()->layout_helper_size_in_bytes())) { 1694 // static field 1695 ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass(); 1696 field = k->get_field_by_offset(tinst->offset(), true); 1697 } else { 1698 ciInstanceKlass *k = tinst->instance_klass(); 1699 field = k->get_field_by_offset(tinst->offset(), false); 1700 } 1701 assert(field == NULL || 1702 original_field == NULL || 1703 (field->holder() == original_field->holder() && 1704 field->offset() == original_field->offset() && 1705 field->is_static() == original_field->is_static()), "wrong field?"); 1706 // Set field() and is_rewritable() attributes. 1707 if (field != NULL) alias_type(idx)->set_field(field); 1708 } 1709 } 1710 1711 // Fill the cache for next time. 1712 ace->_adr_type = adr_type; 1713 ace->_index = idx; 1714 assert(alias_type(adr_type) == alias_type(idx), "type must be installed"); 1715 1716 // Might as well try to fill the cache for the flattened version, too. 1717 AliasCacheEntry* face = probe_alias_cache(flat); 1718 if (face->_adr_type == NULL) { 1719 face->_adr_type = flat; 1720 face->_index = idx; 1721 assert(alias_type(flat) == alias_type(idx), "flat type must work too"); 1722 } 1723 1724 return alias_type(idx); 1725 } 1726 1727 1728 Compile::AliasType* Compile::alias_type(ciField* field) { 1729 const TypeOopPtr* t; 1730 if (field->is_static()) 1731 t = TypeInstPtr::make(field->holder()->java_mirror()); 1732 else 1733 t = TypeOopPtr::make_from_klass_raw(field->holder()); 1734 AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field); 1735 assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct"); 1736 return atp; 1737 } 1738 1739 1740 //------------------------------have_alias_type-------------------------------- 1741 bool Compile::have_alias_type(const TypePtr* adr_type) { 1742 AliasCacheEntry* ace = probe_alias_cache(adr_type); 1743 if (ace->_adr_type == adr_type) { 1744 return true; 1745 } 1746 1747 // Handle special cases. 1748 if (adr_type == NULL) return true; 1749 if (adr_type == TypePtr::BOTTOM) return true; 1750 1751 return find_alias_type(adr_type, true, NULL) != NULL; 1752 } 1753 1754 //-----------------------------must_alias-------------------------------------- 1755 // True if all values of the given address type are in the given alias category. 1756 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) { 1757 if (alias_idx == AliasIdxBot) return true; // the universal category 1758 if (adr_type == NULL) return true; // NULL serves as TypePtr::TOP 1759 if (alias_idx == AliasIdxTop) return false; // the empty category 1760 if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins 1761 1762 // the only remaining possible overlap is identity 1763 int adr_idx = get_alias_index(adr_type); 1764 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, ""); 1765 assert(adr_idx == alias_idx || 1766 (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM 1767 && adr_type != TypeOopPtr::BOTTOM), 1768 "should not be testing for overlap with an unsafe pointer"); 1769 return adr_idx == alias_idx; 1770 } 1771 1772 //------------------------------can_alias-------------------------------------- 1773 // True if any values of the given address type are in the given alias category. 1774 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) { 1775 if (alias_idx == AliasIdxTop) return false; // the empty category 1776 if (adr_type == NULL) return false; // NULL serves as TypePtr::TOP 1777 // Known instance doesn't alias with bottom memory 1778 if (alias_idx == AliasIdxBot) return !adr_type->is_known_instance(); // the universal category 1779 if (adr_type->base() == Type::AnyPtr) return !C->get_adr_type(alias_idx)->is_known_instance(); // TypePtr::BOTTOM or its twins 1780 1781 // the only remaining possible overlap is identity 1782 int adr_idx = get_alias_index(adr_type); 1783 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, ""); 1784 return adr_idx == alias_idx; 1785 } 1786 1787 //---------------------cleanup_loop_predicates----------------------- 1788 // Remove the opaque nodes that protect the predicates so that all unused 1789 // checks and uncommon_traps will be eliminated from the ideal graph 1790 void Compile::cleanup_loop_predicates(PhaseIterGVN &igvn) { 1791 if (predicate_count()==0) return; 1792 for (int i = predicate_count(); i > 0; i--) { 1793 Node * n = predicate_opaque1_node(i-1); 1794 assert(n->Opcode() == Op_Opaque1, "must be"); 1795 igvn.replace_node(n, n->in(1)); 1796 } 1797 assert(predicate_count()==0, "should be clean!"); 1798 } 1799 1800 void Compile::record_for_post_loop_opts_igvn(Node* n) { 1801 if (!n->for_post_loop_opts_igvn()) { 1802 assert(!_for_post_loop_igvn.contains(n), "duplicate"); 1803 n->add_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn); 1804 _for_post_loop_igvn.append(n); 1805 } 1806 } 1807 1808 void Compile::remove_from_post_loop_opts_igvn(Node* n) { 1809 n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn); 1810 _for_post_loop_igvn.remove(n); 1811 } 1812 1813 void Compile::process_for_post_loop_opts_igvn(PhaseIterGVN& igvn) { 1814 // Verify that all previous optimizations produced a valid graph 1815 // at least to this point, even if no loop optimizations were done. 1816 PhaseIdealLoop::verify(igvn); 1817 1818 C->set_post_loop_opts_phase(); // no more loop opts allowed 1819 1820 assert(!C->major_progress(), "not cleared"); 1821 1822 if (_for_post_loop_igvn.length() > 0) { 1823 while (_for_post_loop_igvn.length() > 0) { 1824 Node* n = _for_post_loop_igvn.pop(); 1825 n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn); 1826 igvn._worklist.push(n); 1827 } 1828 igvn.optimize(); 1829 assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed"); 1830 1831 // Sometimes IGVN sets major progress (e.g., when processing loop nodes). 1832 if (C->major_progress()) { 1833 C->clear_major_progress(); // ensure that major progress is now clear 1834 } 1835 } 1836 } 1837 1838 void Compile::record_unstable_if_trap(UnstableIfTrap* trap) { 1839 if (OptimizeUnstableIf) { 1840 _unstable_if_traps.append(trap); 1841 } 1842 } 1843 1844 void Compile::remove_useless_unstable_if_traps(Unique_Node_List& useful) { 1845 for (int i = _unstable_if_traps.length() - 1; i >= 0; i--) { 1846 UnstableIfTrap* trap = _unstable_if_traps.at(i); 1847 Node* n = trap->uncommon_trap(); 1848 if (!useful.member(n)) { 1849 _unstable_if_traps.delete_at(i); // replaces i-th with last element which is known to be useful (already processed) 1850 } 1851 } 1852 } 1853 1854 // Remove the unstable if trap associated with 'unc' from candidates. It is either dead 1855 // or fold-compares case. Return true if succeed or not found. 1856 // 1857 // In rare cases, the found trap has been processed. It is too late to delete it. Return 1858 // false and ask fold-compares to yield. 1859 // 1860 // 'fold-compares' may use the uncommon_trap of the dominating IfNode to cover the fused 1861 // IfNode. This breaks the unstable_if trap invariant: control takes the unstable path 1862 // when deoptimization does happen. 1863 bool Compile::remove_unstable_if_trap(CallStaticJavaNode* unc, bool yield) { 1864 for (int i = 0; i < _unstable_if_traps.length(); ++i) { 1865 UnstableIfTrap* trap = _unstable_if_traps.at(i); 1866 if (trap->uncommon_trap() == unc) { 1867 if (yield && trap->modified()) { 1868 return false; 1869 } 1870 _unstable_if_traps.delete_at(i); 1871 break; 1872 } 1873 } 1874 return true; 1875 } 1876 1877 // Re-calculate unstable_if traps with the liveness of next_bci, which points to the unlikely path. 1878 // It needs to be done after igvn because fold-compares may fuse uncommon_traps and before renumbering. 1879 void Compile::process_for_unstable_if_traps(PhaseIterGVN& igvn) { 1880 for (int i = _unstable_if_traps.length() - 1; i >= 0; --i) { 1881 UnstableIfTrap* trap = _unstable_if_traps.at(i); 1882 CallStaticJavaNode* unc = trap->uncommon_trap(); 1883 int next_bci = trap->next_bci(); 1884 bool modified = trap->modified(); 1885 1886 if (next_bci != -1 && !modified) { 1887 assert(!_dead_node_list.test(unc->_idx), "changing a dead node!"); 1888 JVMState* jvms = unc->jvms(); 1889 ciMethod* method = jvms->method(); 1890 ciBytecodeStream iter(method); 1891 1892 iter.force_bci(jvms->bci()); 1893 assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if"); 1894 Bytecodes::Code c = iter.cur_bc(); 1895 Node* lhs = nullptr; 1896 Node* rhs = nullptr; 1897 if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) { 1898 lhs = unc->peek_operand(0); 1899 rhs = unc->peek_operand(1); 1900 } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) { 1901 lhs = unc->peek_operand(0); 1902 } 1903 1904 ResourceMark rm; 1905 const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci); 1906 assert(live_locals.is_valid(), "broken liveness info"); 1907 int len = (int)live_locals.size(); 1908 1909 for (int i = 0; i < len; i++) { 1910 Node* local = unc->local(jvms, i); 1911 // kill local using the liveness of next_bci. 1912 // give up when the local looks like an operand to secure reexecution. 1913 if (!live_locals.at(i) && !local->is_top() && local != lhs && local!= rhs) { 1914 uint idx = jvms->locoff() + i; 1915 #ifdef ASSERT 1916 if (Verbose) { 1917 tty->print("[unstable_if] kill local#%d: ", idx); 1918 local->dump(); 1919 tty->cr(); 1920 } 1921 #endif 1922 igvn.replace_input_of(unc, idx, top()); 1923 modified = true; 1924 } 1925 } 1926 } 1927 1928 // keep the mondified trap for late query 1929 if (modified) { 1930 trap->set_modified(); 1931 } else { 1932 _unstable_if_traps.delete_at(i); 1933 } 1934 } 1935 igvn.optimize(); 1936 } 1937 1938 // StringOpts and late inlining of string methods 1939 void Compile::inline_string_calls(bool parse_time) { 1940 { 1941 // remove useless nodes to make the usage analysis simpler 1942 ResourceMark rm; 1943 PhaseRemoveUseless pru(initial_gvn(), for_igvn()); 1944 } 1945 1946 { 1947 ResourceMark rm; 1948 print_method(PHASE_BEFORE_STRINGOPTS, 3); 1949 PhaseStringOpts pso(initial_gvn()); 1950 print_method(PHASE_AFTER_STRINGOPTS, 3); 1951 } 1952 1953 // now inline anything that we skipped the first time around 1954 if (!parse_time) { 1955 _late_inlines_pos = _late_inlines.length(); 1956 } 1957 1958 while (_string_late_inlines.length() > 0) { 1959 CallGenerator* cg = _string_late_inlines.pop(); 1960 cg->do_late_inline(); 1961 if (failing()) return; 1962 } 1963 _string_late_inlines.trunc_to(0); 1964 } 1965 1966 // Late inlining of boxing methods 1967 void Compile::inline_boxing_calls(PhaseIterGVN& igvn) { 1968 if (_boxing_late_inlines.length() > 0) { 1969 assert(has_boxed_value(), "inconsistent"); 1970 1971 PhaseGVN* gvn = initial_gvn(); 1972 set_inlining_incrementally(true); 1973 1974 assert( igvn._worklist.size() == 0, "should be done with igvn" ); 1975 for_igvn()->clear(); 1976 gvn->replace_with(&igvn); 1977 1978 _late_inlines_pos = _late_inlines.length(); 1979 1980 while (_boxing_late_inlines.length() > 0) { 1981 CallGenerator* cg = _boxing_late_inlines.pop(); 1982 cg->do_late_inline(); 1983 if (failing()) return; 1984 } 1985 _boxing_late_inlines.trunc_to(0); 1986 1987 inline_incrementally_cleanup(igvn); 1988 1989 set_inlining_incrementally(false); 1990 } 1991 } 1992 1993 bool Compile::inline_incrementally_one() { 1994 assert(IncrementalInline, "incremental inlining should be on"); 1995 1996 TracePhase tp("incrementalInline_inline", &timers[_t_incrInline_inline]); 1997 1998 set_inlining_progress(false); 1999 set_do_cleanup(false); 2000 2001 for (int i = 0; i < _late_inlines.length(); i++) { 2002 _late_inlines_pos = i+1; 2003 CallGenerator* cg = _late_inlines.at(i); 2004 bool does_dispatch = cg->is_virtual_late_inline() || cg->is_mh_late_inline(); 2005 if (inlining_incrementally() || does_dispatch) { // a call can be either inlined or strength-reduced to a direct call 2006 cg->do_late_inline(); 2007 assert(_late_inlines.at(i) == cg, "no insertions before current position allowed"); 2008 if (failing()) { 2009 return false; 2010 } else if (inlining_progress()) { 2011 _late_inlines_pos = i+1; // restore the position in case new elements were inserted 2012 print_method(PHASE_INCREMENTAL_INLINE_STEP, 3, cg->call_node()); 2013 break; // process one call site at a time 2014 } 2015 } else { 2016 // Ignore late inline direct calls when inlining is not allowed. 2017 // They are left in the late inline list when node budget is exhausted until the list is fully drained. 2018 } 2019 } 2020 // Remove processed elements. 2021 _late_inlines.remove_till(_late_inlines_pos); 2022 _late_inlines_pos = 0; 2023 2024 assert(inlining_progress() || _late_inlines.length() == 0, "no progress"); 2025 2026 bool needs_cleanup = do_cleanup() || over_inlining_cutoff(); 2027 2028 set_inlining_progress(false); 2029 set_do_cleanup(false); 2030 2031 bool force_cleanup = directive()->IncrementalInlineForceCleanupOption; 2032 return (_late_inlines.length() > 0) && !needs_cleanup && !force_cleanup; 2033 } 2034 2035 void Compile::inline_incrementally_cleanup(PhaseIterGVN& igvn) { 2036 { 2037 TracePhase tp("incrementalInline_pru", &timers[_t_incrInline_pru]); 2038 ResourceMark rm; 2039 PhaseRemoveUseless pru(initial_gvn(), for_igvn()); 2040 } 2041 { 2042 TracePhase tp("incrementalInline_igvn", &timers[_t_incrInline_igvn]); 2043 igvn = PhaseIterGVN(initial_gvn()); 2044 igvn.optimize(); 2045 } 2046 print_method(PHASE_INCREMENTAL_INLINE_CLEANUP, 3); 2047 } 2048 2049 // Perform incremental inlining until bound on number of live nodes is reached 2050 void Compile::inline_incrementally(PhaseIterGVN& igvn) { 2051 TracePhase tp("incrementalInline", &timers[_t_incrInline]); 2052 2053 set_inlining_incrementally(true); 2054 uint low_live_nodes = 0; 2055 2056 while (_late_inlines.length() > 0) { 2057 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) { 2058 if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) { 2059 TracePhase tp("incrementalInline_ideal", &timers[_t_incrInline_ideal]); 2060 // PhaseIdealLoop is expensive so we only try it once we are 2061 // out of live nodes and we only try it again if the previous 2062 // helped got the number of nodes down significantly 2063 PhaseIdealLoop::optimize(igvn, LoopOptsNone); 2064 if (failing()) return; 2065 low_live_nodes = live_nodes(); 2066 _major_progress = true; 2067 } 2068 2069 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) { 2070 bool do_print_inlining = print_inlining() || print_intrinsics(); 2071 if (do_print_inlining || log() != NULL) { 2072 // Print inlining message for candidates that we couldn't inline for lack of space. 2073 for (int i = 0; i < _late_inlines.length(); i++) { 2074 CallGenerator* cg = _late_inlines.at(i); 2075 const char* msg = "live nodes > LiveNodeCountInliningCutoff"; 2076 if (do_print_inlining) { 2077 cg->print_inlining_late(msg); 2078 } 2079 log_late_inline_failure(cg, msg); 2080 } 2081 } 2082 break; // finish 2083 } 2084 } 2085 2086 for_igvn()->clear(); 2087 initial_gvn()->replace_with(&igvn); 2088 2089 while (inline_incrementally_one()) { 2090 assert(!failing(), "inconsistent"); 2091 } 2092 if (failing()) return; 2093 2094 inline_incrementally_cleanup(igvn); 2095 2096 print_method(PHASE_INCREMENTAL_INLINE_STEP, 3); 2097 2098 if (failing()) return; 2099 2100 if (_late_inlines.length() == 0) { 2101 break; // no more progress 2102 } 2103 } 2104 assert( igvn._worklist.size() == 0, "should be done with igvn" ); 2105 2106 if (_string_late_inlines.length() > 0) { 2107 assert(has_stringbuilder(), "inconsistent"); 2108 for_igvn()->clear(); 2109 initial_gvn()->replace_with(&igvn); 2110 2111 inline_string_calls(false); 2112 2113 if (failing()) return; 2114 2115 inline_incrementally_cleanup(igvn); 2116 } 2117 2118 set_inlining_incrementally(false); 2119 } 2120 2121 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) { 2122 // "inlining_incrementally() == false" is used to signal that no inlining is allowed 2123 // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details). 2124 // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == NULL" 2125 // as if "inlining_incrementally() == true" were set. 2126 assert(inlining_incrementally() == false, "not allowed"); 2127 assert(_modified_nodes == NULL, "not allowed"); 2128 assert(_late_inlines.length() > 0, "sanity"); 2129 2130 while (_late_inlines.length() > 0) { 2131 for_igvn()->clear(); 2132 initial_gvn()->replace_with(&igvn); 2133 2134 while (inline_incrementally_one()) { 2135 assert(!failing(), "inconsistent"); 2136 } 2137 if (failing()) return; 2138 2139 inline_incrementally_cleanup(igvn); 2140 } 2141 } 2142 2143 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) { 2144 if (_loop_opts_cnt > 0) { 2145 while (major_progress() && (_loop_opts_cnt > 0)) { 2146 TracePhase tp("idealLoop", &timers[_t_idealLoop]); 2147 PhaseIdealLoop::optimize(igvn, mode); 2148 _loop_opts_cnt--; 2149 if (failing()) return false; 2150 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2); 2151 } 2152 } 2153 return true; 2154 } 2155 2156 // Remove edges from "root" to each SafePoint at a backward branch. 2157 // They were inserted during parsing (see add_safepoint()) to make 2158 // infinite loops without calls or exceptions visible to root, i.e., 2159 // useful. 2160 void Compile::remove_root_to_sfpts_edges(PhaseIterGVN& igvn) { 2161 Node *r = root(); 2162 if (r != NULL) { 2163 for (uint i = r->req(); i < r->len(); ++i) { 2164 Node *n = r->in(i); 2165 if (n != NULL && n->is_SafePoint()) { 2166 r->rm_prec(i); 2167 if (n->outcnt() == 0) { 2168 igvn.remove_dead_node(n); 2169 } 2170 --i; 2171 } 2172 } 2173 // Parsing may have added top inputs to the root node (Path 2174 // leading to the Halt node proven dead). Make sure we get a 2175 // chance to clean them up. 2176 igvn._worklist.push(r); 2177 igvn.optimize(); 2178 } 2179 } 2180 2181 //------------------------------Optimize--------------------------------------- 2182 // Given a graph, optimize it. 2183 void Compile::Optimize() { 2184 TracePhase tp("optimizer", &timers[_t_optimizer]); 2185 2186 #ifndef PRODUCT 2187 if (env()->break_at_compile()) { 2188 BREAKPOINT; 2189 } 2190 2191 #endif 2192 2193 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 2194 #ifdef ASSERT 2195 bs->verify_gc_barriers(this, BarrierSetC2::BeforeOptimize); 2196 #endif 2197 2198 ResourceMark rm; 2199 2200 print_inlining_reinit(); 2201 2202 NOT_PRODUCT( verify_graph_edges(); ) 2203 2204 print_method(PHASE_AFTER_PARSING, 1); 2205 2206 { 2207 // Iterative Global Value Numbering, including ideal transforms 2208 // Initialize IterGVN with types and values from parse-time GVN 2209 PhaseIterGVN igvn(initial_gvn()); 2210 #ifdef ASSERT 2211 _modified_nodes = new (comp_arena()) Unique_Node_List(comp_arena()); 2212 #endif 2213 { 2214 TracePhase tp("iterGVN", &timers[_t_iterGVN]); 2215 igvn.optimize(); 2216 } 2217 2218 if (failing()) return; 2219 2220 print_method(PHASE_ITER_GVN1, 2); 2221 2222 process_for_unstable_if_traps(igvn); 2223 2224 inline_incrementally(igvn); 2225 2226 print_method(PHASE_INCREMENTAL_INLINE, 2); 2227 2228 if (failing()) return; 2229 2230 if (eliminate_boxing()) { 2231 // Inline valueOf() methods now. 2232 inline_boxing_calls(igvn); 2233 2234 if (AlwaysIncrementalInline) { 2235 inline_incrementally(igvn); 2236 } 2237 2238 print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2); 2239 2240 if (failing()) return; 2241 } 2242 2243 // Remove the speculative part of types and clean up the graph from 2244 // the extra CastPP nodes whose only purpose is to carry them. Do 2245 // that early so that optimizations are not disrupted by the extra 2246 // CastPP nodes. 2247 remove_speculative_types(igvn); 2248 2249 // No more new expensive nodes will be added to the list from here 2250 // so keep only the actual candidates for optimizations. 2251 cleanup_expensive_nodes(igvn); 2252 2253 assert(EnableVectorSupport || !has_vbox_nodes(), "sanity"); 2254 if (EnableVectorSupport && has_vbox_nodes()) { 2255 TracePhase tp("", &timers[_t_vector]); 2256 PhaseVector pv(igvn); 2257 pv.optimize_vector_boxes(); 2258 2259 print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2); 2260 } 2261 assert(!has_vbox_nodes(), "sanity"); 2262 2263 if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) { 2264 Compile::TracePhase tp("", &timers[_t_renumberLive]); 2265 initial_gvn()->replace_with(&igvn); 2266 Unique_Node_List* old_worklist = for_igvn(); 2267 old_worklist->clear(); 2268 Unique_Node_List new_worklist(C->comp_arena()); 2269 { 2270 ResourceMark rm; 2271 PhaseRenumberLive prl = PhaseRenumberLive(initial_gvn(), for_igvn(), &new_worklist); 2272 } 2273 Unique_Node_List* save_for_igvn = for_igvn(); 2274 set_for_igvn(&new_worklist); 2275 igvn = PhaseIterGVN(initial_gvn()); 2276 igvn.optimize(); 2277 set_for_igvn(old_worklist); // new_worklist is dead beyond this point 2278 } 2279 2280 // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop 2281 // safepoints 2282 remove_root_to_sfpts_edges(igvn); 2283 2284 // Perform escape analysis 2285 if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) { 2286 if (has_loops()) { 2287 // Cleanup graph (remove dead nodes). 2288 TracePhase tp("idealLoop", &timers[_t_idealLoop]); 2289 PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll); 2290 if (major_progress()) print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2); 2291 if (failing()) return; 2292 } 2293 bool progress; 2294 do { 2295 ConnectionGraph::do_analysis(this, &igvn); 2296 2297 if (failing()) return; 2298 2299 int mcount = macro_count(); // Record number of allocations and locks before IGVN 2300 2301 // Optimize out fields loads from scalar replaceable allocations. 2302 igvn.optimize(); 2303 print_method(PHASE_ITER_GVN_AFTER_EA, 2); 2304 2305 if (failing()) return; 2306 2307 if (congraph() != NULL && macro_count() > 0) { 2308 TracePhase tp("macroEliminate", &timers[_t_macroEliminate]); 2309 PhaseMacroExpand mexp(igvn); 2310 mexp.eliminate_macro_nodes(); 2311 igvn.set_delay_transform(false); 2312 2313 igvn.optimize(); 2314 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2); 2315 2316 if (failing()) return; 2317 } 2318 progress = do_iterative_escape_analysis() && 2319 (macro_count() < mcount) && 2320 ConnectionGraph::has_candidates(this); 2321 // Try again if candidates exist and made progress 2322 // by removing some allocations and/or locks. 2323 } while (progress); 2324 } 2325 2326 // Loop transforms on the ideal graph. Range Check Elimination, 2327 // peeling, unrolling, etc. 2328 2329 // Set loop opts counter 2330 if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) { 2331 { 2332 TracePhase tp("idealLoop", &timers[_t_idealLoop]); 2333 PhaseIdealLoop::optimize(igvn, LoopOptsDefault); 2334 _loop_opts_cnt--; 2335 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2); 2336 if (failing()) return; 2337 } 2338 // Loop opts pass if partial peeling occurred in previous pass 2339 if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) { 2340 TracePhase tp("idealLoop", &timers[_t_idealLoop]); 2341 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf); 2342 _loop_opts_cnt--; 2343 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2); 2344 if (failing()) return; 2345 } 2346 // Loop opts pass for loop-unrolling before CCP 2347 if(major_progress() && (_loop_opts_cnt > 0)) { 2348 TracePhase tp("idealLoop", &timers[_t_idealLoop]); 2349 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf); 2350 _loop_opts_cnt--; 2351 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2); 2352 } 2353 if (!failing()) { 2354 // Verify that last round of loop opts produced a valid graph 2355 PhaseIdealLoop::verify(igvn); 2356 } 2357 } 2358 if (failing()) return; 2359 2360 // Conditional Constant Propagation; 2361 PhaseCCP ccp( &igvn ); 2362 assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)"); 2363 { 2364 TracePhase tp("ccp", &timers[_t_ccp]); 2365 ccp.do_transform(); 2366 } 2367 print_method(PHASE_CCP1, 2); 2368 2369 assert( true, "Break here to ccp.dump_old2new_map()"); 2370 2371 // Iterative Global Value Numbering, including ideal transforms 2372 { 2373 TracePhase tp("iterGVN2", &timers[_t_iterGVN2]); 2374 igvn = ccp; 2375 igvn.optimize(); 2376 } 2377 print_method(PHASE_ITER_GVN2, 2); 2378 2379 if (failing()) return; 2380 2381 // Loop transforms on the ideal graph. Range Check Elimination, 2382 // peeling, unrolling, etc. 2383 if (!optimize_loops(igvn, LoopOptsDefault)) { 2384 return; 2385 } 2386 2387 if (failing()) return; 2388 2389 C->clear_major_progress(); // ensure that major progress is now clear 2390 2391 process_for_post_loop_opts_igvn(igvn); 2392 2393 #ifdef ASSERT 2394 bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand); 2395 #endif 2396 2397 { 2398 TracePhase tp("macroExpand", &timers[_t_macroExpand]); 2399 PhaseMacroExpand mex(igvn); 2400 if (mex.expand_macro_nodes()) { 2401 assert(failing(), "must bail out w/ explicit message"); 2402 return; 2403 } 2404 print_method(PHASE_MACRO_EXPANSION, 2); 2405 } 2406 2407 { 2408 TracePhase tp("barrierExpand", &timers[_t_barrierExpand]); 2409 if (bs->expand_barriers(this, igvn)) { 2410 assert(failing(), "must bail out w/ explicit message"); 2411 return; 2412 } 2413 print_method(PHASE_BARRIER_EXPANSION, 2); 2414 } 2415 2416 if (C->max_vector_size() > 0) { 2417 C->optimize_logic_cones(igvn); 2418 igvn.optimize(); 2419 } 2420 2421 DEBUG_ONLY( _modified_nodes = NULL; ) 2422 2423 assert(igvn._worklist.size() == 0, "not empty"); 2424 2425 assert(_late_inlines.length() == 0 || IncrementalInlineMH || IncrementalInlineVirtual, "not empty"); 2426 2427 if (_late_inlines.length() > 0) { 2428 // More opportunities to optimize virtual and MH calls. 2429 // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option. 2430 process_late_inline_calls_no_inline(igvn); 2431 } 2432 } // (End scope of igvn; run destructor if necessary for asserts.) 2433 2434 check_no_dead_use(); 2435 2436 process_print_inlining(); 2437 2438 // A method with only infinite loops has no edges entering loops from root 2439 { 2440 TracePhase tp("graphReshape", &timers[_t_graphReshaping]); 2441 if (final_graph_reshaping()) { 2442 assert(failing(), "must bail out w/ explicit message"); 2443 return; 2444 } 2445 } 2446 2447 print_method(PHASE_OPTIMIZE_FINISHED, 2); 2448 DEBUG_ONLY(set_phase_optimize_finished();) 2449 } 2450 2451 #ifdef ASSERT 2452 void Compile::check_no_dead_use() const { 2453 ResourceMark rm; 2454 Unique_Node_List wq; 2455 wq.push(root()); 2456 for (uint i = 0; i < wq.size(); ++i) { 2457 Node* n = wq.at(i); 2458 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 2459 Node* u = n->fast_out(j); 2460 if (u->outcnt() == 0 && !u->is_Con()) { 2461 u->dump(); 2462 fatal("no reachable node should have no use"); 2463 } 2464 wq.push(u); 2465 } 2466 } 2467 } 2468 #endif 2469 2470 void Compile::inline_vector_reboxing_calls() { 2471 if (C->_vector_reboxing_late_inlines.length() > 0) { 2472 _late_inlines_pos = C->_late_inlines.length(); 2473 while (_vector_reboxing_late_inlines.length() > 0) { 2474 CallGenerator* cg = _vector_reboxing_late_inlines.pop(); 2475 cg->do_late_inline(); 2476 if (failing()) return; 2477 print_method(PHASE_INLINE_VECTOR_REBOX, 3, cg->call_node()); 2478 } 2479 _vector_reboxing_late_inlines.trunc_to(0); 2480 } 2481 } 2482 2483 bool Compile::has_vbox_nodes() { 2484 if (C->_vector_reboxing_late_inlines.length() > 0) { 2485 return true; 2486 } 2487 for (int macro_idx = C->macro_count() - 1; macro_idx >= 0; macro_idx--) { 2488 Node * n = C->macro_node(macro_idx); 2489 assert(n->is_macro(), "only macro nodes expected here"); 2490 if (n->Opcode() == Op_VectorUnbox || n->Opcode() == Op_VectorBox || n->Opcode() == Op_VectorBoxAllocate) { 2491 return true; 2492 } 2493 } 2494 return false; 2495 } 2496 2497 //---------------------------- Bitwise operation packing optimization --------------------------- 2498 2499 static bool is_vector_unary_bitwise_op(Node* n) { 2500 return n->Opcode() == Op_XorV && 2501 VectorNode::is_vector_bitwise_not_pattern(n); 2502 } 2503 2504 static bool is_vector_binary_bitwise_op(Node* n) { 2505 switch (n->Opcode()) { 2506 case Op_AndV: 2507 case Op_OrV: 2508 return true; 2509 2510 case Op_XorV: 2511 return !is_vector_unary_bitwise_op(n); 2512 2513 default: 2514 return false; 2515 } 2516 } 2517 2518 static bool is_vector_ternary_bitwise_op(Node* n) { 2519 return n->Opcode() == Op_MacroLogicV; 2520 } 2521 2522 static bool is_vector_bitwise_op(Node* n) { 2523 return is_vector_unary_bitwise_op(n) || 2524 is_vector_binary_bitwise_op(n) || 2525 is_vector_ternary_bitwise_op(n); 2526 } 2527 2528 static bool is_vector_bitwise_cone_root(Node* n) { 2529 if (n->bottom_type()->isa_vectmask() || !is_vector_bitwise_op(n)) { 2530 return false; 2531 } 2532 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 2533 if (is_vector_bitwise_op(n->fast_out(i))) { 2534 return false; 2535 } 2536 } 2537 return true; 2538 } 2539 2540 static uint collect_unique_inputs(Node* n, Unique_Node_List& inputs) { 2541 uint cnt = 0; 2542 if (is_vector_bitwise_op(n)) { 2543 uint inp_cnt = n->is_predicated_vector() ? n->req()-1 : n->req(); 2544 if (VectorNode::is_vector_bitwise_not_pattern(n)) { 2545 for (uint i = 1; i < inp_cnt; i++) { 2546 Node* in = n->in(i); 2547 bool skip = VectorNode::is_all_ones_vector(in); 2548 if (!skip && !inputs.member(in)) { 2549 inputs.push(in); 2550 cnt++; 2551 } 2552 } 2553 assert(cnt <= 1, "not unary"); 2554 } else { 2555 uint last_req = inp_cnt; 2556 if (is_vector_ternary_bitwise_op(n)) { 2557 last_req = inp_cnt - 1; // skip last input 2558 } 2559 for (uint i = 1; i < last_req; i++) { 2560 Node* def = n->in(i); 2561 if (!inputs.member(def)) { 2562 inputs.push(def); 2563 cnt++; 2564 } 2565 } 2566 } 2567 } else { // not a bitwise operations 2568 if (!inputs.member(n)) { 2569 inputs.push(n); 2570 cnt++; 2571 } 2572 } 2573 return cnt; 2574 } 2575 2576 void Compile::collect_logic_cone_roots(Unique_Node_List& list) { 2577 Unique_Node_List useful_nodes; 2578 C->identify_useful_nodes(useful_nodes); 2579 2580 for (uint i = 0; i < useful_nodes.size(); i++) { 2581 Node* n = useful_nodes.at(i); 2582 if (is_vector_bitwise_cone_root(n)) { 2583 list.push(n); 2584 } 2585 } 2586 } 2587 2588 Node* Compile::xform_to_MacroLogicV(PhaseIterGVN& igvn, 2589 const TypeVect* vt, 2590 Unique_Node_List& partition, 2591 Unique_Node_List& inputs) { 2592 assert(partition.size() == 2 || partition.size() == 3, "not supported"); 2593 assert(inputs.size() == 2 || inputs.size() == 3, "not supported"); 2594 assert(Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()), "not supported"); 2595 2596 Node* in1 = inputs.at(0); 2597 Node* in2 = inputs.at(1); 2598 Node* in3 = (inputs.size() == 3 ? inputs.at(2) : in2); 2599 2600 uint func = compute_truth_table(partition, inputs); 2601 2602 Node* pn = partition.at(partition.size() - 1); 2603 Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : NULL; 2604 return igvn.transform(MacroLogicVNode::make(igvn, in1, in2, in3, mask, func, vt)); 2605 } 2606 2607 static uint extract_bit(uint func, uint pos) { 2608 return (func & (1 << pos)) >> pos; 2609 } 2610 2611 // 2612 // A macro logic node represents a truth table. It has 4 inputs, 2613 // First three inputs corresponds to 3 columns of a truth table 2614 // and fourth input captures the logic function. 2615 // 2616 // eg. fn = (in1 AND in2) OR in3; 2617 // 2618 // MacroNode(in1,in2,in3,fn) 2619 // 2620 // ----------------- 2621 // in1 in2 in3 fn 2622 // ----------------- 2623 // 0 0 0 0 2624 // 0 0 1 1 2625 // 0 1 0 0 2626 // 0 1 1 1 2627 // 1 0 0 0 2628 // 1 0 1 1 2629 // 1 1 0 1 2630 // 1 1 1 1 2631 // 2632 2633 uint Compile::eval_macro_logic_op(uint func, uint in1 , uint in2, uint in3) { 2634 int res = 0; 2635 for (int i = 0; i < 8; i++) { 2636 int bit1 = extract_bit(in1, i); 2637 int bit2 = extract_bit(in2, i); 2638 int bit3 = extract_bit(in3, i); 2639 2640 int func_bit_pos = (bit1 << 2 | bit2 << 1 | bit3); 2641 int func_bit = extract_bit(func, func_bit_pos); 2642 2643 res |= func_bit << i; 2644 } 2645 return res; 2646 } 2647 2648 static uint eval_operand(Node* n, ResourceHashtable<Node*,uint>& eval_map) { 2649 assert(n != NULL, ""); 2650 assert(eval_map.contains(n), "absent"); 2651 return *(eval_map.get(n)); 2652 } 2653 2654 static void eval_operands(Node* n, 2655 uint& func1, uint& func2, uint& func3, 2656 ResourceHashtable<Node*,uint>& eval_map) { 2657 assert(is_vector_bitwise_op(n), ""); 2658 2659 if (is_vector_unary_bitwise_op(n)) { 2660 Node* opnd = n->in(1); 2661 if (VectorNode::is_vector_bitwise_not_pattern(n) && VectorNode::is_all_ones_vector(opnd)) { 2662 opnd = n->in(2); 2663 } 2664 func1 = eval_operand(opnd, eval_map); 2665 } else if (is_vector_binary_bitwise_op(n)) { 2666 func1 = eval_operand(n->in(1), eval_map); 2667 func2 = eval_operand(n->in(2), eval_map); 2668 } else { 2669 assert(is_vector_ternary_bitwise_op(n), "unknown operation"); 2670 func1 = eval_operand(n->in(1), eval_map); 2671 func2 = eval_operand(n->in(2), eval_map); 2672 func3 = eval_operand(n->in(3), eval_map); 2673 } 2674 } 2675 2676 uint Compile::compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs) { 2677 assert(inputs.size() <= 3, "sanity"); 2678 ResourceMark rm; 2679 uint res = 0; 2680 ResourceHashtable<Node*,uint> eval_map; 2681 2682 // Populate precomputed functions for inputs. 2683 // Each input corresponds to one column of 3 input truth-table. 2684 uint input_funcs[] = { 0xAA, // (_, _, c) -> c 2685 0xCC, // (_, b, _) -> b 2686 0xF0 }; // (a, _, _) -> a 2687 for (uint i = 0; i < inputs.size(); i++) { 2688 eval_map.put(inputs.at(i), input_funcs[2-i]); 2689 } 2690 2691 for (uint i = 0; i < partition.size(); i++) { 2692 Node* n = partition.at(i); 2693 2694 uint func1 = 0, func2 = 0, func3 = 0; 2695 eval_operands(n, func1, func2, func3, eval_map); 2696 2697 switch (n->Opcode()) { 2698 case Op_OrV: 2699 assert(func3 == 0, "not binary"); 2700 res = func1 | func2; 2701 break; 2702 case Op_AndV: 2703 assert(func3 == 0, "not binary"); 2704 res = func1 & func2; 2705 break; 2706 case Op_XorV: 2707 if (VectorNode::is_vector_bitwise_not_pattern(n)) { 2708 assert(func2 == 0 && func3 == 0, "not unary"); 2709 res = (~func1) & 0xFF; 2710 } else { 2711 assert(func3 == 0, "not binary"); 2712 res = func1 ^ func2; 2713 } 2714 break; 2715 case Op_MacroLogicV: 2716 // Ordering of inputs may change during evaluation of sub-tree 2717 // containing MacroLogic node as a child node, thus a re-evaluation 2718 // makes sure that function is evaluated in context of current 2719 // inputs. 2720 res = eval_macro_logic_op(n->in(4)->get_int(), func1, func2, func3); 2721 break; 2722 2723 default: assert(false, "not supported: %s", n->Name()); 2724 } 2725 assert(res <= 0xFF, "invalid"); 2726 eval_map.put(n, res); 2727 } 2728 return res; 2729 } 2730 2731 // Criteria under which nodes gets packed into a macro logic node:- 2732 // 1) Parent and both child nodes are all unmasked or masked with 2733 // same predicates. 2734 // 2) Masked parent can be packed with left child if it is predicated 2735 // and both have same predicates. 2736 // 3) Masked parent can be packed with right child if its un-predicated 2737 // or has matching predication condition. 2738 // 4) An unmasked parent can be packed with an unmasked child. 2739 bool Compile::compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) { 2740 assert(partition.size() == 0, "not empty"); 2741 assert(inputs.size() == 0, "not empty"); 2742 if (is_vector_ternary_bitwise_op(n)) { 2743 return false; 2744 } 2745 2746 bool is_unary_op = is_vector_unary_bitwise_op(n); 2747 if (is_unary_op) { 2748 assert(collect_unique_inputs(n, inputs) == 1, "not unary"); 2749 return false; // too few inputs 2750 } 2751 2752 bool pack_left_child = true; 2753 bool pack_right_child = true; 2754 2755 bool left_child_LOP = is_vector_bitwise_op(n->in(1)); 2756 bool right_child_LOP = is_vector_bitwise_op(n->in(2)); 2757 2758 int left_child_input_cnt = 0; 2759 int right_child_input_cnt = 0; 2760 2761 bool parent_is_predicated = n->is_predicated_vector(); 2762 bool left_child_predicated = n->in(1)->is_predicated_vector(); 2763 bool right_child_predicated = n->in(2)->is_predicated_vector(); 2764 2765 Node* parent_pred = parent_is_predicated ? n->in(n->req()-1) : NULL; 2766 Node* left_child_pred = left_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : NULL; 2767 Node* right_child_pred = right_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : NULL; 2768 2769 do { 2770 if (pack_left_child && left_child_LOP && 2771 ((!parent_is_predicated && !left_child_predicated) || 2772 ((parent_is_predicated && left_child_predicated && 2773 parent_pred == left_child_pred)))) { 2774 partition.push(n->in(1)); 2775 left_child_input_cnt = collect_unique_inputs(n->in(1), inputs); 2776 } else { 2777 inputs.push(n->in(1)); 2778 left_child_input_cnt = 1; 2779 } 2780 2781 if (pack_right_child && right_child_LOP && 2782 (!right_child_predicated || 2783 (right_child_predicated && parent_is_predicated && 2784 parent_pred == right_child_pred))) { 2785 partition.push(n->in(2)); 2786 right_child_input_cnt = collect_unique_inputs(n->in(2), inputs); 2787 } else { 2788 inputs.push(n->in(2)); 2789 right_child_input_cnt = 1; 2790 } 2791 2792 if (inputs.size() > 3) { 2793 assert(partition.size() > 0, ""); 2794 inputs.clear(); 2795 partition.clear(); 2796 if (left_child_input_cnt > right_child_input_cnt) { 2797 pack_left_child = false; 2798 } else { 2799 pack_right_child = false; 2800 } 2801 } else { 2802 break; 2803 } 2804 } while(true); 2805 2806 if(partition.size()) { 2807 partition.push(n); 2808 } 2809 2810 return (partition.size() == 2 || partition.size() == 3) && 2811 (inputs.size() == 2 || inputs.size() == 3); 2812 } 2813 2814 void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &visited) { 2815 assert(is_vector_bitwise_op(n), "not a root"); 2816 2817 visited.set(n->_idx); 2818 2819 // 1) Do a DFS walk over the logic cone. 2820 for (uint i = 1; i < n->req(); i++) { 2821 Node* in = n->in(i); 2822 if (!visited.test(in->_idx) && is_vector_bitwise_op(in)) { 2823 process_logic_cone_root(igvn, in, visited); 2824 } 2825 } 2826 2827 // 2) Bottom up traversal: Merge node[s] with 2828 // the parent to form macro logic node. 2829 Unique_Node_List partition; 2830 Unique_Node_List inputs; 2831 if (compute_logic_cone(n, partition, inputs)) { 2832 const TypeVect* vt = n->bottom_type()->is_vect(); 2833 Node* pn = partition.at(partition.size() - 1); 2834 Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : NULL; 2835 if (mask == NULL || 2836 Matcher::match_rule_supported_vector_masked(Op_MacroLogicV, vt->length(), vt->element_basic_type())) { 2837 Node* macro_logic = xform_to_MacroLogicV(igvn, vt, partition, inputs); 2838 #ifdef ASSERT 2839 if (TraceNewVectors) { 2840 tty->print("new Vector node: "); 2841 macro_logic->dump(); 2842 } 2843 #endif 2844 igvn.replace_node(n, macro_logic); 2845 } 2846 } 2847 } 2848 2849 void Compile::optimize_logic_cones(PhaseIterGVN &igvn) { 2850 ResourceMark rm; 2851 if (Matcher::match_rule_supported(Op_MacroLogicV)) { 2852 Unique_Node_List list; 2853 collect_logic_cone_roots(list); 2854 2855 while (list.size() > 0) { 2856 Node* n = list.pop(); 2857 const TypeVect* vt = n->bottom_type()->is_vect(); 2858 bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()); 2859 if (supported) { 2860 VectorSet visited(comp_arena()); 2861 process_logic_cone_root(igvn, n, visited); 2862 } 2863 } 2864 } 2865 } 2866 2867 //------------------------------Code_Gen--------------------------------------- 2868 // Given a graph, generate code for it 2869 void Compile::Code_Gen() { 2870 if (failing()) { 2871 return; 2872 } 2873 2874 // Perform instruction selection. You might think we could reclaim Matcher 2875 // memory PDQ, but actually the Matcher is used in generating spill code. 2876 // Internals of the Matcher (including some VectorSets) must remain live 2877 // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage 2878 // set a bit in reclaimed memory. 2879 2880 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine 2881 // nodes. Mapping is only valid at the root of each matched subtree. 2882 NOT_PRODUCT( verify_graph_edges(); ) 2883 2884 Matcher matcher; 2885 _matcher = &matcher; 2886 { 2887 TracePhase tp("matcher", &timers[_t_matcher]); 2888 matcher.match(); 2889 if (failing()) { 2890 return; 2891 } 2892 } 2893 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine 2894 // nodes. Mapping is only valid at the root of each matched subtree. 2895 NOT_PRODUCT( verify_graph_edges(); ) 2896 2897 // If you have too many nodes, or if matching has failed, bail out 2898 check_node_count(0, "out of nodes matching instructions"); 2899 if (failing()) { 2900 return; 2901 } 2902 2903 print_method(PHASE_MATCHING, 2); 2904 2905 // Build a proper-looking CFG 2906 PhaseCFG cfg(node_arena(), root(), matcher); 2907 _cfg = &cfg; 2908 { 2909 TracePhase tp("scheduler", &timers[_t_scheduler]); 2910 bool success = cfg.do_global_code_motion(); 2911 if (!success) { 2912 return; 2913 } 2914 2915 print_method(PHASE_GLOBAL_CODE_MOTION, 2); 2916 NOT_PRODUCT( verify_graph_edges(); ) 2917 cfg.verify(); 2918 } 2919 2920 PhaseChaitin regalloc(unique(), cfg, matcher, false); 2921 _regalloc = ®alloc; 2922 { 2923 TracePhase tp("regalloc", &timers[_t_registerAllocation]); 2924 // Perform register allocation. After Chaitin, use-def chains are 2925 // no longer accurate (at spill code) and so must be ignored. 2926 // Node->LRG->reg mappings are still accurate. 2927 _regalloc->Register_Allocate(); 2928 2929 // Bail out if the allocator builds too many nodes 2930 if (failing()) { 2931 return; 2932 } 2933 } 2934 2935 // Prior to register allocation we kept empty basic blocks in case the 2936 // the allocator needed a place to spill. After register allocation we 2937 // are not adding any new instructions. If any basic block is empty, we 2938 // can now safely remove it. 2939 { 2940 TracePhase tp("blockOrdering", &timers[_t_blockOrdering]); 2941 cfg.remove_empty_blocks(); 2942 if (do_freq_based_layout()) { 2943 PhaseBlockLayout layout(cfg); 2944 } else { 2945 cfg.set_loop_alignment(); 2946 } 2947 cfg.fixup_flow(); 2948 cfg.remove_unreachable_blocks(); 2949 cfg.verify_dominator_tree(); 2950 } 2951 2952 // Apply peephole optimizations 2953 if( OptoPeephole ) { 2954 TracePhase tp("peephole", &timers[_t_peephole]); 2955 PhasePeephole peep( _regalloc, cfg); 2956 peep.do_transform(); 2957 } 2958 2959 // Do late expand if CPU requires this. 2960 if (Matcher::require_postalloc_expand) { 2961 TracePhase tp("postalloc_expand", &timers[_t_postalloc_expand]); 2962 cfg.postalloc_expand(_regalloc); 2963 } 2964 2965 // Convert Nodes to instruction bits in a buffer 2966 { 2967 TracePhase tp("output", &timers[_t_output]); 2968 PhaseOutput output; 2969 output.Output(); 2970 if (failing()) return; 2971 output.install(); 2972 } 2973 2974 print_method(PHASE_FINAL_CODE, 1); 2975 2976 // He's dead, Jim. 2977 _cfg = (PhaseCFG*)((intptr_t)0xdeadbeef); 2978 _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef); 2979 } 2980 2981 //------------------------------Final_Reshape_Counts--------------------------- 2982 // This class defines counters to help identify when a method 2983 // may/must be executed using hardware with only 24-bit precision. 2984 struct Final_Reshape_Counts : public StackObj { 2985 int _call_count; // count non-inlined 'common' calls 2986 int _float_count; // count float ops requiring 24-bit precision 2987 int _double_count; // count double ops requiring more precision 2988 int _java_call_count; // count non-inlined 'java' calls 2989 int _inner_loop_count; // count loops which need alignment 2990 VectorSet _visited; // Visitation flags 2991 Node_List _tests; // Set of IfNodes & PCTableNodes 2992 2993 Final_Reshape_Counts() : 2994 _call_count(0), _float_count(0), _double_count(0), 2995 _java_call_count(0), _inner_loop_count(0) { } 2996 2997 void inc_call_count () { _call_count ++; } 2998 void inc_float_count () { _float_count ++; } 2999 void inc_double_count() { _double_count++; } 3000 void inc_java_call_count() { _java_call_count++; } 3001 void inc_inner_loop_count() { _inner_loop_count++; } 3002 3003 int get_call_count () const { return _call_count ; } 3004 int get_float_count () const { return _float_count ; } 3005 int get_double_count() const { return _double_count; } 3006 int get_java_call_count() const { return _java_call_count; } 3007 int get_inner_loop_count() const { return _inner_loop_count; } 3008 }; 3009 3010 // Eliminate trivially redundant StoreCMs and accumulate their 3011 // precedence edges. 3012 void Compile::eliminate_redundant_card_marks(Node* n) { 3013 assert(n->Opcode() == Op_StoreCM, "expected StoreCM"); 3014 if (n->in(MemNode::Address)->outcnt() > 1) { 3015 // There are multiple users of the same address so it might be 3016 // possible to eliminate some of the StoreCMs 3017 Node* mem = n->in(MemNode::Memory); 3018 Node* adr = n->in(MemNode::Address); 3019 Node* val = n->in(MemNode::ValueIn); 3020 Node* prev = n; 3021 bool done = false; 3022 // Walk the chain of StoreCMs eliminating ones that match. As 3023 // long as it's a chain of single users then the optimization is 3024 // safe. Eliminating partially redundant StoreCMs would require 3025 // cloning copies down the other paths. 3026 while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) { 3027 if (adr == mem->in(MemNode::Address) && 3028 val == mem->in(MemNode::ValueIn)) { 3029 // redundant StoreCM 3030 if (mem->req() > MemNode::OopStore) { 3031 // Hasn't been processed by this code yet. 3032 n->add_prec(mem->in(MemNode::OopStore)); 3033 } else { 3034 // Already converted to precedence edge 3035 for (uint i = mem->req(); i < mem->len(); i++) { 3036 // Accumulate any precedence edges 3037 if (mem->in(i) != NULL) { 3038 n->add_prec(mem->in(i)); 3039 } 3040 } 3041 // Everything above this point has been processed. 3042 done = true; 3043 } 3044 // Eliminate the previous StoreCM 3045 prev->set_req(MemNode::Memory, mem->in(MemNode::Memory)); 3046 assert(mem->outcnt() == 0, "should be dead"); 3047 mem->disconnect_inputs(this); 3048 } else { 3049 prev = mem; 3050 } 3051 mem = prev->in(MemNode::Memory); 3052 } 3053 } 3054 } 3055 3056 //------------------------------final_graph_reshaping_impl---------------------- 3057 // Implement items 1-5 from final_graph_reshaping below. 3058 void Compile::final_graph_reshaping_impl(Node *n, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) { 3059 3060 if ( n->outcnt() == 0 ) return; // dead node 3061 uint nop = n->Opcode(); 3062 3063 // Check for 2-input instruction with "last use" on right input. 3064 // Swap to left input. Implements item (2). 3065 if( n->req() == 3 && // two-input instruction 3066 n->in(1)->outcnt() > 1 && // left use is NOT a last use 3067 (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop 3068 n->in(2)->outcnt() == 1 &&// right use IS a last use 3069 !n->in(2)->is_Con() ) { // right use is not a constant 3070 // Check for commutative opcode 3071 switch( nop ) { 3072 case Op_AddI: case Op_AddF: case Op_AddD: case Op_AddL: 3073 case Op_MaxI: case Op_MaxL: case Op_MaxF: case Op_MaxD: 3074 case Op_MinI: case Op_MinL: case Op_MinF: case Op_MinD: 3075 case Op_MulI: case Op_MulF: case Op_MulD: case Op_MulL: 3076 case Op_AndL: case Op_XorL: case Op_OrL: 3077 case Op_AndI: case Op_XorI: case Op_OrI: { 3078 // Move "last use" input to left by swapping inputs 3079 n->swap_edges(1, 2); 3080 break; 3081 } 3082 default: 3083 break; 3084 } 3085 } 3086 3087 #ifdef ASSERT 3088 if( n->is_Mem() ) { 3089 int alias_idx = get_alias_index(n->as_Mem()->adr_type()); 3090 assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw || 3091 // oop will be recorded in oop map if load crosses safepoint 3092 n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() || 3093 LoadNode::is_immutable_value(n->in(MemNode::Address))), 3094 "raw memory operations should have control edge"); 3095 } 3096 if (n->is_MemBar()) { 3097 MemBarNode* mb = n->as_MemBar(); 3098 if (mb->trailing_store() || mb->trailing_load_store()) { 3099 assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair"); 3100 Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent)); 3101 assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) || 3102 (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op"); 3103 } else if (mb->leading()) { 3104 assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair"); 3105 } 3106 } 3107 #endif 3108 // Count FPU ops and common calls, implements item (3) 3109 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop, dead_nodes); 3110 if (!gc_handled) { 3111 final_graph_reshaping_main_switch(n, frc, nop, dead_nodes); 3112 } 3113 3114 // Collect CFG split points 3115 if (n->is_MultiBranch() && !n->is_RangeCheck()) { 3116 frc._tests.push(n); 3117 } 3118 } 3119 3120 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) { 3121 switch( nop ) { 3122 // Count all float operations that may use FPU 3123 case Op_AddF: 3124 case Op_SubF: 3125 case Op_MulF: 3126 case Op_DivF: 3127 case Op_NegF: 3128 case Op_ModF: 3129 case Op_ConvI2F: 3130 case Op_ConF: 3131 case Op_CmpF: 3132 case Op_CmpF3: 3133 case Op_StoreF: 3134 case Op_LoadF: 3135 // case Op_ConvL2F: // longs are split into 32-bit halves 3136 frc.inc_float_count(); 3137 break; 3138 3139 case Op_ConvF2D: 3140 case Op_ConvD2F: 3141 frc.inc_float_count(); 3142 frc.inc_double_count(); 3143 break; 3144 3145 // Count all double operations that may use FPU 3146 case Op_AddD: 3147 case Op_SubD: 3148 case Op_MulD: 3149 case Op_DivD: 3150 case Op_NegD: 3151 case Op_ModD: 3152 case Op_ConvI2D: 3153 case Op_ConvD2I: 3154 // case Op_ConvL2D: // handled by leaf call 3155 // case Op_ConvD2L: // handled by leaf call 3156 case Op_ConD: 3157 case Op_CmpD: 3158 case Op_CmpD3: 3159 case Op_StoreD: 3160 case Op_LoadD: 3161 case Op_LoadD_unaligned: 3162 frc.inc_double_count(); 3163 break; 3164 case Op_Opaque1: // Remove Opaque Nodes before matching 3165 case Op_Opaque3: 3166 n->subsume_by(n->in(1), this); 3167 break; 3168 case Op_CallStaticJava: 3169 case Op_CallJava: 3170 case Op_CallDynamicJava: 3171 frc.inc_java_call_count(); // Count java call site; 3172 case Op_CallRuntime: 3173 case Op_CallLeaf: 3174 case Op_CallLeafVector: 3175 case Op_CallLeafNoFP: { 3176 assert (n->is_Call(), ""); 3177 CallNode *call = n->as_Call(); 3178 // Count call sites where the FP mode bit would have to be flipped. 3179 // Do not count uncommon runtime calls: 3180 // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking, 3181 // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ... 3182 if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) { 3183 frc.inc_call_count(); // Count the call site 3184 } else { // See if uncommon argument is shared 3185 Node *n = call->in(TypeFunc::Parms); 3186 int nop = n->Opcode(); 3187 // Clone shared simple arguments to uncommon calls, item (1). 3188 if (n->outcnt() > 1 && 3189 !n->is_Proj() && 3190 nop != Op_CreateEx && 3191 nop != Op_CheckCastPP && 3192 nop != Op_DecodeN && 3193 nop != Op_DecodeNKlass && 3194 !n->is_Mem() && 3195 !n->is_Phi()) { 3196 Node *x = n->clone(); 3197 call->set_req(TypeFunc::Parms, x); 3198 } 3199 } 3200 break; 3201 } 3202 3203 case Op_StoreCM: 3204 { 3205 // Convert OopStore dependence into precedence edge 3206 Node* prec = n->in(MemNode::OopStore); 3207 n->del_req(MemNode::OopStore); 3208 n->add_prec(prec); 3209 eliminate_redundant_card_marks(n); 3210 } 3211 3212 // fall through 3213 3214 case Op_StoreB: 3215 case Op_StoreC: 3216 case Op_StoreI: 3217 case Op_StoreL: 3218 case Op_CompareAndSwapB: 3219 case Op_CompareAndSwapS: 3220 case Op_CompareAndSwapI: 3221 case Op_CompareAndSwapL: 3222 case Op_CompareAndSwapP: 3223 case Op_CompareAndSwapN: 3224 case Op_WeakCompareAndSwapB: 3225 case Op_WeakCompareAndSwapS: 3226 case Op_WeakCompareAndSwapI: 3227 case Op_WeakCompareAndSwapL: 3228 case Op_WeakCompareAndSwapP: 3229 case Op_WeakCompareAndSwapN: 3230 case Op_CompareAndExchangeB: 3231 case Op_CompareAndExchangeS: 3232 case Op_CompareAndExchangeI: 3233 case Op_CompareAndExchangeL: 3234 case Op_CompareAndExchangeP: 3235 case Op_CompareAndExchangeN: 3236 case Op_GetAndAddS: 3237 case Op_GetAndAddB: 3238 case Op_GetAndAddI: 3239 case Op_GetAndAddL: 3240 case Op_GetAndSetS: 3241 case Op_GetAndSetB: 3242 case Op_GetAndSetI: 3243 case Op_GetAndSetL: 3244 case Op_GetAndSetP: 3245 case Op_GetAndSetN: 3246 case Op_StoreP: 3247 case Op_StoreN: 3248 case Op_StoreNKlass: 3249 case Op_LoadB: 3250 case Op_LoadUB: 3251 case Op_LoadUS: 3252 case Op_LoadI: 3253 case Op_LoadKlass: 3254 case Op_LoadNKlass: 3255 case Op_LoadL: 3256 case Op_LoadL_unaligned: 3257 case Op_LoadP: 3258 case Op_LoadN: 3259 case Op_LoadRange: 3260 case Op_LoadS: 3261 break; 3262 3263 case Op_AddP: { // Assert sane base pointers 3264 Node *addp = n->in(AddPNode::Address); 3265 assert( !addp->is_AddP() || 3266 addp->in(AddPNode::Base)->is_top() || // Top OK for allocation 3267 addp->in(AddPNode::Base) == n->in(AddPNode::Base), 3268 "Base pointers must match (addp %u)", addp->_idx ); 3269 #ifdef _LP64 3270 if ((UseCompressedOops || UseCompressedClassPointers) && 3271 addp->Opcode() == Op_ConP && 3272 addp == n->in(AddPNode::Base) && 3273 n->in(AddPNode::Offset)->is_Con()) { 3274 // If the transformation of ConP to ConN+DecodeN is beneficial depends 3275 // on the platform and on the compressed oops mode. 3276 // Use addressing with narrow klass to load with offset on x86. 3277 // Some platforms can use the constant pool to load ConP. 3278 // Do this transformation here since IGVN will convert ConN back to ConP. 3279 const Type* t = addp->bottom_type(); 3280 bool is_oop = t->isa_oopptr() != NULL; 3281 bool is_klass = t->isa_klassptr() != NULL; 3282 3283 if ((is_oop && Matcher::const_oop_prefer_decode() ) || 3284 (is_klass && Matcher::const_klass_prefer_decode())) { 3285 Node* nn = NULL; 3286 3287 int op = is_oop ? Op_ConN : Op_ConNKlass; 3288 3289 // Look for existing ConN node of the same exact type. 3290 Node* r = root(); 3291 uint cnt = r->outcnt(); 3292 for (uint i = 0; i < cnt; i++) { 3293 Node* m = r->raw_out(i); 3294 if (m!= NULL && m->Opcode() == op && 3295 m->bottom_type()->make_ptr() == t) { 3296 nn = m; 3297 break; 3298 } 3299 } 3300 if (nn != NULL) { 3301 // Decode a narrow oop to match address 3302 // [R12 + narrow_oop_reg<<3 + offset] 3303 if (is_oop) { 3304 nn = new DecodeNNode(nn, t); 3305 } else { 3306 nn = new DecodeNKlassNode(nn, t); 3307 } 3308 // Check for succeeding AddP which uses the same Base. 3309 // Otherwise we will run into the assertion above when visiting that guy. 3310 for (uint i = 0; i < n->outcnt(); ++i) { 3311 Node *out_i = n->raw_out(i); 3312 if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) { 3313 out_i->set_req(AddPNode::Base, nn); 3314 #ifdef ASSERT 3315 for (uint j = 0; j < out_i->outcnt(); ++j) { 3316 Node *out_j = out_i->raw_out(j); 3317 assert(out_j == NULL || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp, 3318 "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx); 3319 } 3320 #endif 3321 } 3322 } 3323 n->set_req(AddPNode::Base, nn); 3324 n->set_req(AddPNode::Address, nn); 3325 if (addp->outcnt() == 0) { 3326 addp->disconnect_inputs(this); 3327 } 3328 } 3329 } 3330 } 3331 #endif 3332 break; 3333 } 3334 3335 case Op_CastPP: { 3336 // Remove CastPP nodes to gain more freedom during scheduling but 3337 // keep the dependency they encode as control or precedence edges 3338 // (if control is set already) on memory operations. Some CastPP 3339 // nodes don't have a control (don't carry a dependency): skip 3340 // those. 3341 if (n->in(0) != NULL) { 3342 ResourceMark rm; 3343 Unique_Node_List wq; 3344 wq.push(n); 3345 for (uint next = 0; next < wq.size(); ++next) { 3346 Node *m = wq.at(next); 3347 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) { 3348 Node* use = m->fast_out(i); 3349 if (use->is_Mem() || use->is_EncodeNarrowPtr()) { 3350 use->ensure_control_or_add_prec(n->in(0)); 3351 } else { 3352 switch(use->Opcode()) { 3353 case Op_AddP: 3354 case Op_DecodeN: 3355 case Op_DecodeNKlass: 3356 case Op_CheckCastPP: 3357 case Op_CastPP: 3358 wq.push(use); 3359 break; 3360 } 3361 } 3362 } 3363 } 3364 } 3365 const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false); 3366 if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) { 3367 Node* in1 = n->in(1); 3368 const Type* t = n->bottom_type(); 3369 Node* new_in1 = in1->clone(); 3370 new_in1->as_DecodeN()->set_type(t); 3371 3372 if (!Matcher::narrow_oop_use_complex_address()) { 3373 // 3374 // x86, ARM and friends can handle 2 adds in addressing mode 3375 // and Matcher can fold a DecodeN node into address by using 3376 // a narrow oop directly and do implicit NULL check in address: 3377 // 3378 // [R12 + narrow_oop_reg<<3 + offset] 3379 // NullCheck narrow_oop_reg 3380 // 3381 // On other platforms (Sparc) we have to keep new DecodeN node and 3382 // use it to do implicit NULL check in address: 3383 // 3384 // decode_not_null narrow_oop_reg, base_reg 3385 // [base_reg + offset] 3386 // NullCheck base_reg 3387 // 3388 // Pin the new DecodeN node to non-null path on these platform (Sparc) 3389 // to keep the information to which NULL check the new DecodeN node 3390 // corresponds to use it as value in implicit_null_check(). 3391 // 3392 new_in1->set_req(0, n->in(0)); 3393 } 3394 3395 n->subsume_by(new_in1, this); 3396 if (in1->outcnt() == 0) { 3397 in1->disconnect_inputs(this); 3398 } 3399 } else { 3400 n->subsume_by(n->in(1), this); 3401 if (n->outcnt() == 0) { 3402 n->disconnect_inputs(this); 3403 } 3404 } 3405 break; 3406 } 3407 #ifdef _LP64 3408 case Op_CmpP: 3409 // Do this transformation here to preserve CmpPNode::sub() and 3410 // other TypePtr related Ideal optimizations (for example, ptr nullness). 3411 if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) { 3412 Node* in1 = n->in(1); 3413 Node* in2 = n->in(2); 3414 if (!in1->is_DecodeNarrowPtr()) { 3415 in2 = in1; 3416 in1 = n->in(2); 3417 } 3418 assert(in1->is_DecodeNarrowPtr(), "sanity"); 3419 3420 Node* new_in2 = NULL; 3421 if (in2->is_DecodeNarrowPtr()) { 3422 assert(in2->Opcode() == in1->Opcode(), "must be same node type"); 3423 new_in2 = in2->in(1); 3424 } else if (in2->Opcode() == Op_ConP) { 3425 const Type* t = in2->bottom_type(); 3426 if (t == TypePtr::NULL_PTR) { 3427 assert(in1->is_DecodeN(), "compare klass to null?"); 3428 // Don't convert CmpP null check into CmpN if compressed 3429 // oops implicit null check is not generated. 3430 // This will allow to generate normal oop implicit null check. 3431 if (Matcher::gen_narrow_oop_implicit_null_checks()) 3432 new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR); 3433 // 3434 // This transformation together with CastPP transformation above 3435 // will generated code for implicit NULL checks for compressed oops. 3436 // 3437 // The original code after Optimize() 3438 // 3439 // LoadN memory, narrow_oop_reg 3440 // decode narrow_oop_reg, base_reg 3441 // CmpP base_reg, NULL 3442 // CastPP base_reg // NotNull 3443 // Load [base_reg + offset], val_reg 3444 // 3445 // after these transformations will be 3446 // 3447 // LoadN memory, narrow_oop_reg 3448 // CmpN narrow_oop_reg, NULL 3449 // decode_not_null narrow_oop_reg, base_reg 3450 // Load [base_reg + offset], val_reg 3451 // 3452 // and the uncommon path (== NULL) will use narrow_oop_reg directly 3453 // since narrow oops can be used in debug info now (see the code in 3454 // final_graph_reshaping_walk()). 3455 // 3456 // At the end the code will be matched to 3457 // on x86: 3458 // 3459 // Load_narrow_oop memory, narrow_oop_reg 3460 // Load [R12 + narrow_oop_reg<<3 + offset], val_reg 3461 // NullCheck narrow_oop_reg 3462 // 3463 // and on sparc: 3464 // 3465 // Load_narrow_oop memory, narrow_oop_reg 3466 // decode_not_null narrow_oop_reg, base_reg 3467 // Load [base_reg + offset], val_reg 3468 // NullCheck base_reg 3469 // 3470 } else if (t->isa_oopptr()) { 3471 new_in2 = ConNode::make(t->make_narrowoop()); 3472 } else if (t->isa_klassptr()) { 3473 new_in2 = ConNode::make(t->make_narrowklass()); 3474 } 3475 } 3476 if (new_in2 != NULL) { 3477 Node* cmpN = new CmpNNode(in1->in(1), new_in2); 3478 n->subsume_by(cmpN, this); 3479 if (in1->outcnt() == 0) { 3480 in1->disconnect_inputs(this); 3481 } 3482 if (in2->outcnt() == 0) { 3483 in2->disconnect_inputs(this); 3484 } 3485 } 3486 } 3487 break; 3488 3489 case Op_DecodeN: 3490 case Op_DecodeNKlass: 3491 assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out"); 3492 // DecodeN could be pinned when it can't be fold into 3493 // an address expression, see the code for Op_CastPP above. 3494 assert(n->in(0) == NULL || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control"); 3495 break; 3496 3497 case Op_EncodeP: 3498 case Op_EncodePKlass: { 3499 Node* in1 = n->in(1); 3500 if (in1->is_DecodeNarrowPtr()) { 3501 n->subsume_by(in1->in(1), this); 3502 } else if (in1->Opcode() == Op_ConP) { 3503 const Type* t = in1->bottom_type(); 3504 if (t == TypePtr::NULL_PTR) { 3505 assert(t->isa_oopptr(), "null klass?"); 3506 n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this); 3507 } else if (t->isa_oopptr()) { 3508 n->subsume_by(ConNode::make(t->make_narrowoop()), this); 3509 } else if (t->isa_klassptr()) { 3510 n->subsume_by(ConNode::make(t->make_narrowklass()), this); 3511 } 3512 } 3513 if (in1->outcnt() == 0) { 3514 in1->disconnect_inputs(this); 3515 } 3516 break; 3517 } 3518 3519 case Op_Proj: { 3520 if (OptimizeStringConcat || IncrementalInline) { 3521 ProjNode* proj = n->as_Proj(); 3522 if (proj->_is_io_use) { 3523 assert(proj->_con == TypeFunc::I_O || proj->_con == TypeFunc::Memory, ""); 3524 // Separate projections were used for the exception path which 3525 // are normally removed by a late inline. If it wasn't inlined 3526 // then they will hang around and should just be replaced with 3527 // the original one. Merge them. 3528 Node* non_io_proj = proj->in(0)->as_Multi()->proj_out_or_null(proj->_con, false /*is_io_use*/); 3529 if (non_io_proj != NULL) { 3530 proj->subsume_by(non_io_proj , this); 3531 } 3532 } 3533 } 3534 break; 3535 } 3536 3537 case Op_Phi: 3538 if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) { 3539 // The EncodeP optimization may create Phi with the same edges 3540 // for all paths. It is not handled well by Register Allocator. 3541 Node* unique_in = n->in(1); 3542 assert(unique_in != NULL, ""); 3543 uint cnt = n->req(); 3544 for (uint i = 2; i < cnt; i++) { 3545 Node* m = n->in(i); 3546 assert(m != NULL, ""); 3547 if (unique_in != m) 3548 unique_in = NULL; 3549 } 3550 if (unique_in != NULL) { 3551 n->subsume_by(unique_in, this); 3552 } 3553 } 3554 break; 3555 3556 #endif 3557 3558 #ifdef ASSERT 3559 case Op_CastII: 3560 // Verify that all range check dependent CastII nodes were removed. 3561 if (n->isa_CastII()->has_range_check()) { 3562 n->dump(3); 3563 assert(false, "Range check dependent CastII node was not removed"); 3564 } 3565 break; 3566 #endif 3567 3568 case Op_ModI: 3569 if (UseDivMod) { 3570 // Check if a%b and a/b both exist 3571 Node* d = n->find_similar(Op_DivI); 3572 if (d) { 3573 // Replace them with a fused divmod if supported 3574 if (Matcher::has_match_rule(Op_DivModI)) { 3575 DivModINode* divmod = DivModINode::make(n); 3576 d->subsume_by(divmod->div_proj(), this); 3577 n->subsume_by(divmod->mod_proj(), this); 3578 } else { 3579 // replace a%b with a-((a/b)*b) 3580 Node* mult = new MulINode(d, d->in(2)); 3581 Node* sub = new SubINode(d->in(1), mult); 3582 n->subsume_by(sub, this); 3583 } 3584 } 3585 } 3586 break; 3587 3588 case Op_ModL: 3589 if (UseDivMod) { 3590 // Check if a%b and a/b both exist 3591 Node* d = n->find_similar(Op_DivL); 3592 if (d) { 3593 // Replace them with a fused divmod if supported 3594 if (Matcher::has_match_rule(Op_DivModL)) { 3595 DivModLNode* divmod = DivModLNode::make(n); 3596 d->subsume_by(divmod->div_proj(), this); 3597 n->subsume_by(divmod->mod_proj(), this); 3598 } else { 3599 // replace a%b with a-((a/b)*b) 3600 Node* mult = new MulLNode(d, d->in(2)); 3601 Node* sub = new SubLNode(d->in(1), mult); 3602 n->subsume_by(sub, this); 3603 } 3604 } 3605 } 3606 break; 3607 3608 case Op_UModI: 3609 if (UseDivMod) { 3610 // Check if a%b and a/b both exist 3611 Node* d = n->find_similar(Op_UDivI); 3612 if (d) { 3613 // Replace them with a fused unsigned divmod if supported 3614 if (Matcher::has_match_rule(Op_UDivModI)) { 3615 UDivModINode* divmod = UDivModINode::make(n); 3616 d->subsume_by(divmod->div_proj(), this); 3617 n->subsume_by(divmod->mod_proj(), this); 3618 } else { 3619 // replace a%b with a-((a/b)*b) 3620 Node* mult = new MulINode(d, d->in(2)); 3621 Node* sub = new SubINode(d->in(1), mult); 3622 n->subsume_by(sub, this); 3623 } 3624 } 3625 } 3626 break; 3627 3628 case Op_UModL: 3629 if (UseDivMod) { 3630 // Check if a%b and a/b both exist 3631 Node* d = n->find_similar(Op_UDivL); 3632 if (d) { 3633 // Replace them with a fused unsigned divmod if supported 3634 if (Matcher::has_match_rule(Op_UDivModL)) { 3635 UDivModLNode* divmod = UDivModLNode::make(n); 3636 d->subsume_by(divmod->div_proj(), this); 3637 n->subsume_by(divmod->mod_proj(), this); 3638 } else { 3639 // replace a%b with a-((a/b)*b) 3640 Node* mult = new MulLNode(d, d->in(2)); 3641 Node* sub = new SubLNode(d->in(1), mult); 3642 n->subsume_by(sub, this); 3643 } 3644 } 3645 } 3646 break; 3647 3648 case Op_LoadVector: 3649 case Op_StoreVector: 3650 case Op_LoadVectorGather: 3651 case Op_StoreVectorScatter: 3652 case Op_LoadVectorGatherMasked: 3653 case Op_StoreVectorScatterMasked: 3654 case Op_VectorCmpMasked: 3655 case Op_VectorMaskGen: 3656 case Op_LoadVectorMasked: 3657 case Op_StoreVectorMasked: 3658 break; 3659 3660 case Op_AddReductionVI: 3661 case Op_AddReductionVL: 3662 case Op_AddReductionVF: 3663 case Op_AddReductionVD: 3664 case Op_MulReductionVI: 3665 case Op_MulReductionVL: 3666 case Op_MulReductionVF: 3667 case Op_MulReductionVD: 3668 case Op_MinReductionV: 3669 case Op_MaxReductionV: 3670 case Op_AndReductionV: 3671 case Op_OrReductionV: 3672 case Op_XorReductionV: 3673 break; 3674 3675 case Op_PackB: 3676 case Op_PackS: 3677 case Op_PackI: 3678 case Op_PackF: 3679 case Op_PackL: 3680 case Op_PackD: 3681 if (n->req()-1 > 2) { 3682 // Replace many operand PackNodes with a binary tree for matching 3683 PackNode* p = (PackNode*) n; 3684 Node* btp = p->binary_tree_pack(1, n->req()); 3685 n->subsume_by(btp, this); 3686 } 3687 break; 3688 case Op_Loop: 3689 assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0, "should have been turned into a counted loop"); 3690 case Op_CountedLoop: 3691 case Op_LongCountedLoop: 3692 case Op_OuterStripMinedLoop: 3693 if (n->as_Loop()->is_inner_loop()) { 3694 frc.inc_inner_loop_count(); 3695 } 3696 n->as_Loop()->verify_strip_mined(0); 3697 break; 3698 case Op_LShiftI: 3699 case Op_RShiftI: 3700 case Op_URShiftI: 3701 case Op_LShiftL: 3702 case Op_RShiftL: 3703 case Op_URShiftL: 3704 if (Matcher::need_masked_shift_count) { 3705 // The cpu's shift instructions don't restrict the count to the 3706 // lower 5/6 bits. We need to do the masking ourselves. 3707 Node* in2 = n->in(2); 3708 juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1); 3709 const TypeInt* t = in2->find_int_type(); 3710 if (t != NULL && t->is_con()) { 3711 juint shift = t->get_con(); 3712 if (shift > mask) { // Unsigned cmp 3713 n->set_req(2, ConNode::make(TypeInt::make(shift & mask))); 3714 } 3715 } else { 3716 if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) { 3717 Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask))); 3718 n->set_req(2, shift); 3719 } 3720 } 3721 if (in2->outcnt() == 0) { // Remove dead node 3722 in2->disconnect_inputs(this); 3723 } 3724 } 3725 break; 3726 case Op_MemBarStoreStore: 3727 case Op_MemBarRelease: 3728 // Break the link with AllocateNode: it is no longer useful and 3729 // confuses register allocation. 3730 if (n->req() > MemBarNode::Precedent) { 3731 n->set_req(MemBarNode::Precedent, top()); 3732 } 3733 break; 3734 case Op_MemBarAcquire: { 3735 if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) { 3736 // At parse time, the trailing MemBarAcquire for a volatile load 3737 // is created with an edge to the load. After optimizations, 3738 // that input may be a chain of Phis. If those phis have no 3739 // other use, then the MemBarAcquire keeps them alive and 3740 // register allocation can be confused. 3741 dead_nodes.push(n->in(MemBarNode::Precedent)); 3742 n->set_req(MemBarNode::Precedent, top()); 3743 } 3744 break; 3745 } 3746 case Op_Blackhole: 3747 break; 3748 case Op_RangeCheck: { 3749 RangeCheckNode* rc = n->as_RangeCheck(); 3750 Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt); 3751 n->subsume_by(iff, this); 3752 frc._tests.push(iff); 3753 break; 3754 } 3755 case Op_ConvI2L: { 3756 if (!Matcher::convi2l_type_required) { 3757 // Code generation on some platforms doesn't need accurate 3758 // ConvI2L types. Widening the type can help remove redundant 3759 // address computations. 3760 n->as_Type()->set_type(TypeLong::INT); 3761 ResourceMark rm; 3762 Unique_Node_List wq; 3763 wq.push(n); 3764 for (uint next = 0; next < wq.size(); next++) { 3765 Node *m = wq.at(next); 3766 3767 for(;;) { 3768 // Loop over all nodes with identical inputs edges as m 3769 Node* k = m->find_similar(m->Opcode()); 3770 if (k == NULL) { 3771 break; 3772 } 3773 // Push their uses so we get a chance to remove node made 3774 // redundant 3775 for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) { 3776 Node* u = k->fast_out(i); 3777 if (u->Opcode() == Op_LShiftL || 3778 u->Opcode() == Op_AddL || 3779 u->Opcode() == Op_SubL || 3780 u->Opcode() == Op_AddP) { 3781 wq.push(u); 3782 } 3783 } 3784 // Replace all nodes with identical edges as m with m 3785 k->subsume_by(m, this); 3786 } 3787 } 3788 } 3789 break; 3790 } 3791 case Op_CmpUL: { 3792 if (!Matcher::has_match_rule(Op_CmpUL)) { 3793 // No support for unsigned long comparisons 3794 ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1)); 3795 Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos); 3796 Node* orl = new OrLNode(n->in(1), sign_bit_mask); 3797 ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong)); 3798 Node* andl = new AndLNode(orl, remove_sign_mask); 3799 Node* cmp = new CmpLNode(andl, n->in(2)); 3800 n->subsume_by(cmp, this); 3801 } 3802 break; 3803 } 3804 default: 3805 assert(!n->is_Call(), ""); 3806 assert(!n->is_Mem(), ""); 3807 assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN"); 3808 break; 3809 } 3810 } 3811 3812 //------------------------------final_graph_reshaping_walk--------------------- 3813 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(), 3814 // requires that the walk visits a node's inputs before visiting the node. 3815 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) { 3816 Unique_Node_List sfpt; 3817 3818 frc._visited.set(root->_idx); // first, mark node as visited 3819 uint cnt = root->req(); 3820 Node *n = root; 3821 uint i = 0; 3822 while (true) { 3823 if (i < cnt) { 3824 // Place all non-visited non-null inputs onto stack 3825 Node* m = n->in(i); 3826 ++i; 3827 if (m != NULL && !frc._visited.test_set(m->_idx)) { 3828 if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL) { 3829 // compute worst case interpreter size in case of a deoptimization 3830 update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size()); 3831 3832 sfpt.push(m); 3833 } 3834 cnt = m->req(); 3835 nstack.push(n, i); // put on stack parent and next input's index 3836 n = m; 3837 i = 0; 3838 } 3839 } else { 3840 // Now do post-visit work 3841 final_graph_reshaping_impl(n, frc, dead_nodes); 3842 if (nstack.is_empty()) 3843 break; // finished 3844 n = nstack.node(); // Get node from stack 3845 cnt = n->req(); 3846 i = nstack.index(); 3847 nstack.pop(); // Shift to the next node on stack 3848 } 3849 } 3850 3851 // Skip next transformation if compressed oops are not used. 3852 if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) || 3853 (!UseCompressedOops && !UseCompressedClassPointers)) 3854 return; 3855 3856 // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges. 3857 // It could be done for an uncommon traps or any safepoints/calls 3858 // if the DecodeN/DecodeNKlass node is referenced only in a debug info. 3859 while (sfpt.size() > 0) { 3860 n = sfpt.pop(); 3861 JVMState *jvms = n->as_SafePoint()->jvms(); 3862 assert(jvms != NULL, "sanity"); 3863 int start = jvms->debug_start(); 3864 int end = n->req(); 3865 bool is_uncommon = (n->is_CallStaticJava() && 3866 n->as_CallStaticJava()->uncommon_trap_request() != 0); 3867 for (int j = start; j < end; j++) { 3868 Node* in = n->in(j); 3869 if (in->is_DecodeNarrowPtr()) { 3870 bool safe_to_skip = true; 3871 if (!is_uncommon ) { 3872 // Is it safe to skip? 3873 for (uint i = 0; i < in->outcnt(); i++) { 3874 Node* u = in->raw_out(i); 3875 if (!u->is_SafePoint() || 3876 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) { 3877 safe_to_skip = false; 3878 } 3879 } 3880 } 3881 if (safe_to_skip) { 3882 n->set_req(j, in->in(1)); 3883 } 3884 if (in->outcnt() == 0) { 3885 in->disconnect_inputs(this); 3886 } 3887 } 3888 } 3889 } 3890 } 3891 3892 //------------------------------final_graph_reshaping-------------------------- 3893 // Final Graph Reshaping. 3894 // 3895 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late 3896 // and not commoned up and forced early. Must come after regular 3897 // optimizations to avoid GVN undoing the cloning. Clone constant 3898 // inputs to Loop Phis; these will be split by the allocator anyways. 3899 // Remove Opaque nodes. 3900 // (2) Move last-uses by commutative operations to the left input to encourage 3901 // Intel update-in-place two-address operations and better register usage 3902 // on RISCs. Must come after regular optimizations to avoid GVN Ideal 3903 // calls canonicalizing them back. 3904 // (3) Count the number of double-precision FP ops, single-precision FP ops 3905 // and call sites. On Intel, we can get correct rounding either by 3906 // forcing singles to memory (requires extra stores and loads after each 3907 // FP bytecode) or we can set a rounding mode bit (requires setting and 3908 // clearing the mode bit around call sites). The mode bit is only used 3909 // if the relative frequency of single FP ops to calls is low enough. 3910 // This is a key transform for SPEC mpeg_audio. 3911 // (4) Detect infinite loops; blobs of code reachable from above but not 3912 // below. Several of the Code_Gen algorithms fail on such code shapes, 3913 // so we simply bail out. Happens a lot in ZKM.jar, but also happens 3914 // from time to time in other codes (such as -Xcomp finalizer loops, etc). 3915 // Detection is by looking for IfNodes where only 1 projection is 3916 // reachable from below or CatchNodes missing some targets. 3917 // (5) Assert for insane oop offsets in debug mode. 3918 3919 bool Compile::final_graph_reshaping() { 3920 // an infinite loop may have been eliminated by the optimizer, 3921 // in which case the graph will be empty. 3922 if (root()->req() == 1) { 3923 record_method_not_compilable("trivial infinite loop"); 3924 return true; 3925 } 3926 3927 // Expensive nodes have their control input set to prevent the GVN 3928 // from freely commoning them. There's no GVN beyond this point so 3929 // no need to keep the control input. We want the expensive nodes to 3930 // be freely moved to the least frequent code path by gcm. 3931 assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?"); 3932 for (int i = 0; i < expensive_count(); i++) { 3933 _expensive_nodes.at(i)->set_req(0, NULL); 3934 } 3935 3936 Final_Reshape_Counts frc; 3937 3938 // Visit everybody reachable! 3939 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc 3940 Node_Stack nstack(live_nodes() >> 1); 3941 Unique_Node_List dead_nodes; 3942 final_graph_reshaping_walk(nstack, root(), frc, dead_nodes); 3943 3944 // Check for unreachable (from below) code (i.e., infinite loops). 3945 for( uint i = 0; i < frc._tests.size(); i++ ) { 3946 MultiBranchNode *n = frc._tests[i]->as_MultiBranch(); 3947 // Get number of CFG targets. 3948 // Note that PCTables include exception targets after calls. 3949 uint required_outcnt = n->required_outcnt(); 3950 if (n->outcnt() != required_outcnt) { 3951 // Check for a few special cases. Rethrow Nodes never take the 3952 // 'fall-thru' path, so expected kids is 1 less. 3953 if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) { 3954 if (n->in(0)->in(0)->is_Call()) { 3955 CallNode* call = n->in(0)->in(0)->as_Call(); 3956 if (call->entry_point() == OptoRuntime::rethrow_stub()) { 3957 required_outcnt--; // Rethrow always has 1 less kid 3958 } else if (call->req() > TypeFunc::Parms && 3959 call->is_CallDynamicJava()) { 3960 // Check for null receiver. In such case, the optimizer has 3961 // detected that the virtual call will always result in a null 3962 // pointer exception. The fall-through projection of this CatchNode 3963 // will not be populated. 3964 Node* arg0 = call->in(TypeFunc::Parms); 3965 if (arg0->is_Type() && 3966 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) { 3967 required_outcnt--; 3968 } 3969 } else if (call->entry_point() == OptoRuntime::new_array_Java() || 3970 call->entry_point() == OptoRuntime::new_array_nozero_Java()) { 3971 // Check for illegal array length. In such case, the optimizer has 3972 // detected that the allocation attempt will always result in an 3973 // exception. There is no fall-through projection of this CatchNode . 3974 assert(call->is_CallStaticJava(), "static call expected"); 3975 assert(call->req() == call->jvms()->endoff() + 1, "missing extra input"); 3976 uint valid_length_test_input = call->req() - 1; 3977 Node* valid_length_test = call->in(valid_length_test_input); 3978 call->del_req(valid_length_test_input); 3979 if (valid_length_test->find_int_con(1) == 0) { 3980 required_outcnt--; 3981 } 3982 dead_nodes.push(valid_length_test); 3983 assert(n->outcnt() == required_outcnt, "malformed control flow"); 3984 continue; 3985 } 3986 } 3987 } 3988 // Recheck with a better notion of 'required_outcnt' 3989 if (n->outcnt() != required_outcnt) { 3990 record_method_not_compilable("malformed control flow"); 3991 return true; // Not all targets reachable! 3992 } 3993 } else if (n->is_PCTable() && n->in(0) && n->in(0)->in(0) && n->in(0)->in(0)->is_Call()) { 3994 CallNode* call = n->in(0)->in(0)->as_Call(); 3995 if (call->entry_point() == OptoRuntime::new_array_Java() || 3996 call->entry_point() == OptoRuntime::new_array_nozero_Java()) { 3997 assert(call->is_CallStaticJava(), "static call expected"); 3998 assert(call->req() == call->jvms()->endoff() + 1, "missing extra input"); 3999 uint valid_length_test_input = call->req() - 1; 4000 dead_nodes.push(call->in(valid_length_test_input)); 4001 call->del_req(valid_length_test_input); // valid length test useless now 4002 } 4003 } 4004 // Check that I actually visited all kids. Unreached kids 4005 // must be infinite loops. 4006 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) 4007 if (!frc._visited.test(n->fast_out(j)->_idx)) { 4008 record_method_not_compilable("infinite loop"); 4009 return true; // Found unvisited kid; must be unreach 4010 } 4011 4012 // Here so verification code in final_graph_reshaping_walk() 4013 // always see an OuterStripMinedLoopEnd 4014 if (n->is_OuterStripMinedLoopEnd() || n->is_LongCountedLoopEnd()) { 4015 IfNode* init_iff = n->as_If(); 4016 Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt); 4017 n->subsume_by(iff, this); 4018 } 4019 } 4020 4021 while (dead_nodes.size() > 0) { 4022 Node* m = dead_nodes.pop(); 4023 if (m->outcnt() == 0 && m != top()) { 4024 for (uint j = 0; j < m->req(); j++) { 4025 Node* in = m->in(j); 4026 if (in != NULL) { 4027 dead_nodes.push(in); 4028 } 4029 } 4030 m->disconnect_inputs(this); 4031 } 4032 } 4033 4034 #ifdef IA32 4035 // If original bytecodes contained a mixture of floats and doubles 4036 // check if the optimizer has made it homogeneous, item (3). 4037 if (UseSSE == 0 && 4038 frc.get_float_count() > 32 && 4039 frc.get_double_count() == 0 && 4040 (10 * frc.get_call_count() < frc.get_float_count()) ) { 4041 set_24_bit_selection_and_mode(false, true); 4042 } 4043 #endif // IA32 4044 4045 set_java_calls(frc.get_java_call_count()); 4046 set_inner_loops(frc.get_inner_loop_count()); 4047 4048 // No infinite loops, no reason to bail out. 4049 return false; 4050 } 4051 4052 //-----------------------------too_many_traps---------------------------------- 4053 // Report if there are too many traps at the current method and bci. 4054 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded. 4055 bool Compile::too_many_traps(ciMethod* method, 4056 int bci, 4057 Deoptimization::DeoptReason reason) { 4058 ciMethodData* md = method->method_data(); 4059 if (md->is_empty()) { 4060 // Assume the trap has not occurred, or that it occurred only 4061 // because of a transient condition during start-up in the interpreter. 4062 return false; 4063 } 4064 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL; 4065 if (md->has_trap_at(bci, m, reason) != 0) { 4066 // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic. 4067 // Also, if there are multiple reasons, or if there is no per-BCI record, 4068 // assume the worst. 4069 if (log()) 4070 log()->elem("observe trap='%s' count='%d'", 4071 Deoptimization::trap_reason_name(reason), 4072 md->trap_count(reason)); 4073 return true; 4074 } else { 4075 // Ignore method/bci and see if there have been too many globally. 4076 return too_many_traps(reason, md); 4077 } 4078 } 4079 4080 // Less-accurate variant which does not require a method and bci. 4081 bool Compile::too_many_traps(Deoptimization::DeoptReason reason, 4082 ciMethodData* logmd) { 4083 if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) { 4084 // Too many traps globally. 4085 // Note that we use cumulative trap_count, not just md->trap_count. 4086 if (log()) { 4087 int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason); 4088 log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'", 4089 Deoptimization::trap_reason_name(reason), 4090 mcount, trap_count(reason)); 4091 } 4092 return true; 4093 } else { 4094 // The coast is clear. 4095 return false; 4096 } 4097 } 4098 4099 //--------------------------too_many_recompiles-------------------------------- 4100 // Report if there are too many recompiles at the current method and bci. 4101 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff. 4102 // Is not eager to return true, since this will cause the compiler to use 4103 // Action_none for a trap point, to avoid too many recompilations. 4104 bool Compile::too_many_recompiles(ciMethod* method, 4105 int bci, 4106 Deoptimization::DeoptReason reason) { 4107 ciMethodData* md = method->method_data(); 4108 if (md->is_empty()) { 4109 // Assume the trap has not occurred, or that it occurred only 4110 // because of a transient condition during start-up in the interpreter. 4111 return false; 4112 } 4113 // Pick a cutoff point well within PerBytecodeRecompilationCutoff. 4114 uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8; 4115 uint m_cutoff = (uint) PerMethodRecompilationCutoff / 2 + 1; // not zero 4116 Deoptimization::DeoptReason per_bc_reason 4117 = Deoptimization::reason_recorded_per_bytecode_if_any(reason); 4118 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL; 4119 if ((per_bc_reason == Deoptimization::Reason_none 4120 || md->has_trap_at(bci, m, reason) != 0) 4121 // The trap frequency measure we care about is the recompile count: 4122 && md->trap_recompiled_at(bci, m) 4123 && md->overflow_recompile_count() >= bc_cutoff) { 4124 // Do not emit a trap here if it has already caused recompilations. 4125 // Also, if there are multiple reasons, or if there is no per-BCI record, 4126 // assume the worst. 4127 if (log()) 4128 log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'", 4129 Deoptimization::trap_reason_name(reason), 4130 md->trap_count(reason), 4131 md->overflow_recompile_count()); 4132 return true; 4133 } else if (trap_count(reason) != 0 4134 && decompile_count() >= m_cutoff) { 4135 // Too many recompiles globally, and we have seen this sort of trap. 4136 // Use cumulative decompile_count, not just md->decompile_count. 4137 if (log()) 4138 log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'", 4139 Deoptimization::trap_reason_name(reason), 4140 md->trap_count(reason), trap_count(reason), 4141 md->decompile_count(), decompile_count()); 4142 return true; 4143 } else { 4144 // The coast is clear. 4145 return false; 4146 } 4147 } 4148 4149 // Compute when not to trap. Used by matching trap based nodes and 4150 // NullCheck optimization. 4151 void Compile::set_allowed_deopt_reasons() { 4152 _allowed_reasons = 0; 4153 if (is_method_compilation()) { 4154 for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) { 4155 assert(rs < BitsPerInt, "recode bit map"); 4156 if (!too_many_traps((Deoptimization::DeoptReason) rs)) { 4157 _allowed_reasons |= nth_bit(rs); 4158 } 4159 } 4160 } 4161 } 4162 4163 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) { 4164 return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method); 4165 } 4166 4167 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) { 4168 return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method); 4169 } 4170 4171 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) { 4172 if (holder->is_initialized()) { 4173 return false; 4174 } 4175 if (holder->is_being_initialized()) { 4176 if (accessing_method->holder() == holder) { 4177 // Access inside a class. The barrier can be elided when access happens in <clinit>, 4178 // <init>, or a static method. In all those cases, there was an initialization 4179 // barrier on the holder klass passed. 4180 if (accessing_method->is_static_initializer() || 4181 accessing_method->is_object_initializer() || 4182 accessing_method->is_static()) { 4183 return false; 4184 } 4185 } else if (accessing_method->holder()->is_subclass_of(holder)) { 4186 // Access from a subclass. The barrier can be elided only when access happens in <clinit>. 4187 // In case of <init> or a static method, the barrier is on the subclass is not enough: 4188 // child class can become fully initialized while its parent class is still being initialized. 4189 if (accessing_method->is_static_initializer()) { 4190 return false; 4191 } 4192 } 4193 ciMethod* root = method(); // the root method of compilation 4194 if (root != accessing_method) { 4195 return needs_clinit_barrier(holder, root); // check access in the context of compilation root 4196 } 4197 } 4198 return true; 4199 } 4200 4201 #ifndef PRODUCT 4202 //------------------------------verify_bidirectional_edges--------------------- 4203 // For each input edge to a node (ie - for each Use-Def edge), verify that 4204 // there is a corresponding Def-Use edge. 4205 void Compile::verify_bidirectional_edges(Unique_Node_List &visited) { 4206 // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc 4207 uint stack_size = live_nodes() >> 4; 4208 Node_List nstack(MAX2(stack_size, (uint)OptoNodeListSize)); 4209 nstack.push(_root); 4210 4211 while (nstack.size() > 0) { 4212 Node* n = nstack.pop(); 4213 if (visited.member(n)) { 4214 continue; 4215 } 4216 visited.push(n); 4217 4218 // Walk over all input edges, checking for correspondence 4219 uint length = n->len(); 4220 for (uint i = 0; i < length; i++) { 4221 Node* in = n->in(i); 4222 if (in != NULL && !visited.member(in)) { 4223 nstack.push(in); // Put it on stack 4224 } 4225 if (in != NULL && !in->is_top()) { 4226 // Count instances of `next` 4227 int cnt = 0; 4228 for (uint idx = 0; idx < in->_outcnt; idx++) { 4229 if (in->_out[idx] == n) { 4230 cnt++; 4231 } 4232 } 4233 assert(cnt > 0, "Failed to find Def-Use edge."); 4234 // Check for duplicate edges 4235 // walk the input array downcounting the input edges to n 4236 for (uint j = 0; j < length; j++) { 4237 if (n->in(j) == in) { 4238 cnt--; 4239 } 4240 } 4241 assert(cnt == 0, "Mismatched edge count."); 4242 } else if (in == NULL) { 4243 assert(i == 0 || i >= n->req() || 4244 n->is_Region() || n->is_Phi() || n->is_ArrayCopy() || 4245 (n->is_Unlock() && i == (n->req() - 1)) || 4246 (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion 4247 "only region, phi, arraycopy, unlock or membar nodes have null data edges"); 4248 } else { 4249 assert(in->is_top(), "sanity"); 4250 // Nothing to check. 4251 } 4252 } 4253 } 4254 } 4255 4256 //------------------------------verify_graph_edges--------------------------- 4257 // Walk the Graph and verify that there is a one-to-one correspondence 4258 // between Use-Def edges and Def-Use edges in the graph. 4259 void Compile::verify_graph_edges(bool no_dead_code) { 4260 if (VerifyGraphEdges) { 4261 Unique_Node_List visited; 4262 4263 // Call graph walk to check edges 4264 verify_bidirectional_edges(visited); 4265 if (no_dead_code) { 4266 // Now make sure that no visited node is used by an unvisited node. 4267 bool dead_nodes = false; 4268 Unique_Node_List checked; 4269 while (visited.size() > 0) { 4270 Node* n = visited.pop(); 4271 checked.push(n); 4272 for (uint i = 0; i < n->outcnt(); i++) { 4273 Node* use = n->raw_out(i); 4274 if (checked.member(use)) continue; // already checked 4275 if (visited.member(use)) continue; // already in the graph 4276 if (use->is_Con()) continue; // a dead ConNode is OK 4277 // At this point, we have found a dead node which is DU-reachable. 4278 if (!dead_nodes) { 4279 tty->print_cr("*** Dead nodes reachable via DU edges:"); 4280 dead_nodes = true; 4281 } 4282 use->dump(2); 4283 tty->print_cr("---"); 4284 checked.push(use); // No repeats; pretend it is now checked. 4285 } 4286 } 4287 assert(!dead_nodes, "using nodes must be reachable from root"); 4288 } 4289 } 4290 } 4291 #endif 4292 4293 // The Compile object keeps track of failure reasons separately from the ciEnv. 4294 // This is required because there is not quite a 1-1 relation between the 4295 // ciEnv and its compilation task and the Compile object. Note that one 4296 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides 4297 // to backtrack and retry without subsuming loads. Other than this backtracking 4298 // behavior, the Compile's failure reason is quietly copied up to the ciEnv 4299 // by the logic in C2Compiler. 4300 void Compile::record_failure(const char* reason) { 4301 if (log() != NULL) { 4302 log()->elem("failure reason='%s' phase='compile'", reason); 4303 } 4304 if (_failure_reason == NULL) { 4305 // Record the first failure reason. 4306 _failure_reason = reason; 4307 } 4308 4309 if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) { 4310 C->print_method(PHASE_FAILURE, 1); 4311 } 4312 _root = NULL; // flush the graph, too 4313 } 4314 4315 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator) 4316 : TraceTime(name, accumulator, CITime, CITimeVerbose), 4317 _phase_name(name), _dolog(CITimeVerbose) 4318 { 4319 if (_dolog) { 4320 C = Compile::current(); 4321 _log = C->log(); 4322 } else { 4323 C = NULL; 4324 _log = NULL; 4325 } 4326 if (_log != NULL) { 4327 _log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes()); 4328 _log->stamp(); 4329 _log->end_head(); 4330 } 4331 } 4332 4333 Compile::TracePhase::~TracePhase() { 4334 4335 C = Compile::current(); 4336 if (_dolog) { 4337 _log = C->log(); 4338 } else { 4339 _log = NULL; 4340 } 4341 4342 #ifdef ASSERT 4343 if (PrintIdealNodeCount) { 4344 tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'", 4345 _phase_name, C->unique(), C->live_nodes(), C->count_live_nodes_by_graph_walk()); 4346 } 4347 4348 if (VerifyIdealNodeCount) { 4349 Compile::current()->print_missing_nodes(); 4350 } 4351 #endif 4352 4353 if (_log != NULL) { 4354 _log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes()); 4355 } 4356 } 4357 4358 //----------------------------static_subtype_check----------------------------- 4359 // Shortcut important common cases when superklass is exact: 4360 // (0) superklass is java.lang.Object (can occur in reflective code) 4361 // (1) subklass is already limited to a subtype of superklass => always ok 4362 // (2) subklass does not overlap with superklass => always fail 4363 // (3) superklass has NO subtypes and we can check with a simple compare. 4364 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk) { 4365 if (StressReflectiveCode) { 4366 return SSC_full_test; // Let caller generate the general case. 4367 } 4368 4369 if (subk->is_java_subtype_of(superk)) { 4370 return SSC_always_true; // (0) and (1) this test cannot fail 4371 } 4372 4373 if (!subk->maybe_java_subtype_of(superk)) { 4374 return SSC_always_false; // (2) true path dead; no dynamic test needed 4375 } 4376 4377 const Type* superelem = superk; 4378 if (superk->isa_aryklassptr()) { 4379 int ignored; 4380 superelem = superk->is_aryklassptr()->base_element_type(ignored); 4381 } 4382 4383 if (superelem->isa_instklassptr()) { 4384 ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass(); 4385 if (!ik->has_subklass()) { 4386 if (!ik->is_final()) { 4387 // Add a dependency if there is a chance of a later subclass. 4388 dependencies()->assert_leaf_type(ik); 4389 } 4390 if (!superk->maybe_java_subtype_of(subk)) { 4391 return SSC_always_false; 4392 } 4393 return SSC_easy_test; // (3) caller can do a simple ptr comparison 4394 } 4395 } else { 4396 // A primitive array type has no subtypes. 4397 return SSC_easy_test; // (3) caller can do a simple ptr comparison 4398 } 4399 4400 return SSC_full_test; 4401 } 4402 4403 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) { 4404 #ifdef _LP64 4405 // The scaled index operand to AddP must be a clean 64-bit value. 4406 // Java allows a 32-bit int to be incremented to a negative 4407 // value, which appears in a 64-bit register as a large 4408 // positive number. Using that large positive number as an 4409 // operand in pointer arithmetic has bad consequences. 4410 // On the other hand, 32-bit overflow is rare, and the possibility 4411 // can often be excluded, if we annotate the ConvI2L node with 4412 // a type assertion that its value is known to be a small positive 4413 // number. (The prior range check has ensured this.) 4414 // This assertion is used by ConvI2LNode::Ideal. 4415 int index_max = max_jint - 1; // array size is max_jint, index is one less 4416 if (sizetype != NULL) index_max = sizetype->_hi - 1; 4417 const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax); 4418 idx = constrained_convI2L(phase, idx, iidxtype, ctrl); 4419 #endif 4420 return idx; 4421 } 4422 4423 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check) 4424 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl, bool carry_dependency) { 4425 if (ctrl != NULL) { 4426 // Express control dependency by a CastII node with a narrow type. 4427 value = new CastIINode(value, itype, carry_dependency ? ConstraintCastNode::StrongDependency : ConstraintCastNode::RegularDependency, true /* range check dependency */); 4428 // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L 4429 // node from floating above the range check during loop optimizations. Otherwise, the 4430 // ConvI2L node may be eliminated independently of the range check, causing the data path 4431 // to become TOP while the control path is still there (although it's unreachable). 4432 value->set_req(0, ctrl); 4433 value = phase->transform(value); 4434 } 4435 const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen); 4436 return phase->transform(new ConvI2LNode(value, ltype)); 4437 } 4438 4439 // The message about the current inlining is accumulated in 4440 // _print_inlining_stream and transferred into the _print_inlining_list 4441 // once we know whether inlining succeeds or not. For regular 4442 // inlining, messages are appended to the buffer pointed by 4443 // _print_inlining_idx in the _print_inlining_list. For late inlining, 4444 // a new buffer is added after _print_inlining_idx in the list. This 4445 // way we can update the inlining message for late inlining call site 4446 // when the inlining is attempted again. 4447 void Compile::print_inlining_init() { 4448 if (print_inlining() || print_intrinsics()) { 4449 // print_inlining_init is actually called several times. 4450 print_inlining_reset(); 4451 _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer*>(comp_arena(), 1, 1, new PrintInliningBuffer()); 4452 } 4453 } 4454 4455 void Compile::print_inlining_reinit() { 4456 if (print_inlining() || print_intrinsics()) { 4457 print_inlining_reset(); 4458 } 4459 } 4460 4461 void Compile::print_inlining_reset() { 4462 _print_inlining_stream->reset(); 4463 } 4464 4465 void Compile::print_inlining_commit() { 4466 assert(print_inlining() || print_intrinsics(), "PrintInlining off?"); 4467 // Transfer the message from _print_inlining_stream to the current 4468 // _print_inlining_list buffer and clear _print_inlining_stream. 4469 _print_inlining_list->at(_print_inlining_idx)->ss()->write(_print_inlining_stream->base(), _print_inlining_stream->size()); 4470 print_inlining_reset(); 4471 } 4472 4473 void Compile::print_inlining_push() { 4474 // Add new buffer to the _print_inlining_list at current position 4475 _print_inlining_idx++; 4476 _print_inlining_list->insert_before(_print_inlining_idx, new PrintInliningBuffer()); 4477 } 4478 4479 Compile::PrintInliningBuffer* Compile::print_inlining_current() { 4480 return _print_inlining_list->at(_print_inlining_idx); 4481 } 4482 4483 void Compile::print_inlining_update(CallGenerator* cg) { 4484 if (print_inlining() || print_intrinsics()) { 4485 if (cg->is_late_inline()) { 4486 if (print_inlining_current()->cg() != cg && 4487 (print_inlining_current()->cg() != NULL || 4488 print_inlining_current()->ss()->size() != 0)) { 4489 print_inlining_push(); 4490 } 4491 print_inlining_commit(); 4492 print_inlining_current()->set_cg(cg); 4493 } else { 4494 if (print_inlining_current()->cg() != NULL) { 4495 print_inlining_push(); 4496 } 4497 print_inlining_commit(); 4498 } 4499 } 4500 } 4501 4502 void Compile::print_inlining_move_to(CallGenerator* cg) { 4503 // We resume inlining at a late inlining call site. Locate the 4504 // corresponding inlining buffer so that we can update it. 4505 if (print_inlining() || print_intrinsics()) { 4506 for (int i = 0; i < _print_inlining_list->length(); i++) { 4507 if (_print_inlining_list->at(i)->cg() == cg) { 4508 _print_inlining_idx = i; 4509 return; 4510 } 4511 } 4512 ShouldNotReachHere(); 4513 } 4514 } 4515 4516 void Compile::print_inlining_update_delayed(CallGenerator* cg) { 4517 if (print_inlining() || print_intrinsics()) { 4518 assert(_print_inlining_stream->size() > 0, "missing inlining msg"); 4519 assert(print_inlining_current()->cg() == cg, "wrong entry"); 4520 // replace message with new message 4521 _print_inlining_list->at_put(_print_inlining_idx, new PrintInliningBuffer()); 4522 print_inlining_commit(); 4523 print_inlining_current()->set_cg(cg); 4524 } 4525 } 4526 4527 void Compile::print_inlining_assert_ready() { 4528 assert(!_print_inlining || _print_inlining_stream->size() == 0, "losing data"); 4529 } 4530 4531 void Compile::process_print_inlining() { 4532 assert(_late_inlines.length() == 0, "not drained yet"); 4533 if (print_inlining() || print_intrinsics()) { 4534 ResourceMark rm; 4535 stringStream ss; 4536 assert(_print_inlining_list != NULL, "process_print_inlining should be called only once."); 4537 for (int i = 0; i < _print_inlining_list->length(); i++) { 4538 PrintInliningBuffer* pib = _print_inlining_list->at(i); 4539 ss.print("%s", pib->ss()->freeze()); 4540 delete pib; 4541 DEBUG_ONLY(_print_inlining_list->at_put(i, NULL)); 4542 } 4543 // Reset _print_inlining_list, it only contains destructed objects. 4544 // It is on the arena, so it will be freed when the arena is reset. 4545 _print_inlining_list = NULL; 4546 // _print_inlining_stream won't be used anymore, either. 4547 print_inlining_reset(); 4548 size_t end = ss.size(); 4549 _print_inlining_output = NEW_ARENA_ARRAY(comp_arena(), char, end+1); 4550 strncpy(_print_inlining_output, ss.freeze(), end+1); 4551 _print_inlining_output[end] = 0; 4552 } 4553 } 4554 4555 void Compile::dump_print_inlining() { 4556 if (_print_inlining_output != NULL) { 4557 tty->print_raw(_print_inlining_output); 4558 } 4559 } 4560 4561 void Compile::log_late_inline(CallGenerator* cg) { 4562 if (log() != NULL) { 4563 log()->head("late_inline method='%d' inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()), 4564 cg->unique_id()); 4565 JVMState* p = cg->call_node()->jvms(); 4566 while (p != NULL) { 4567 log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method())); 4568 p = p->caller(); 4569 } 4570 log()->tail("late_inline"); 4571 } 4572 } 4573 4574 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) { 4575 log_late_inline(cg); 4576 if (log() != NULL) { 4577 log()->inline_fail(msg); 4578 } 4579 } 4580 4581 void Compile::log_inline_id(CallGenerator* cg) { 4582 if (log() != NULL) { 4583 // The LogCompilation tool needs a unique way to identify late 4584 // inline call sites. This id must be unique for this call site in 4585 // this compilation. Try to have it unique across compilations as 4586 // well because it can be convenient when grepping through the log 4587 // file. 4588 // Distinguish OSR compilations from others in case CICountOSR is 4589 // on. 4590 jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0); 4591 cg->set_unique_id(id); 4592 log()->elem("inline_id id='" JLONG_FORMAT "'", id); 4593 } 4594 } 4595 4596 void Compile::log_inline_failure(const char* msg) { 4597 if (C->log() != NULL) { 4598 C->log()->inline_fail(msg); 4599 } 4600 } 4601 4602 4603 // Dump inlining replay data to the stream. 4604 // Don't change thread state and acquire any locks. 4605 void Compile::dump_inline_data(outputStream* out) { 4606 InlineTree* inl_tree = ilt(); 4607 if (inl_tree != NULL) { 4608 out->print(" inline %d", inl_tree->count()); 4609 inl_tree->dump_replay_data(out); 4610 } 4611 } 4612 4613 void Compile::dump_inline_data_reduced(outputStream* out) { 4614 assert(ReplayReduce, ""); 4615 4616 InlineTree* inl_tree = ilt(); 4617 if (inl_tree == NULL) { 4618 return; 4619 } 4620 // Enable iterative replay file reduction 4621 // Output "compile" lines for depth 1 subtrees, 4622 // simulating that those trees were compiled 4623 // instead of inlined. 4624 for (int i = 0; i < inl_tree->subtrees().length(); ++i) { 4625 InlineTree* sub = inl_tree->subtrees().at(i); 4626 if (sub->inline_level() != 1) { 4627 continue; 4628 } 4629 4630 ciMethod* method = sub->method(); 4631 int entry_bci = -1; 4632 int comp_level = env()->task()->comp_level(); 4633 out->print("compile "); 4634 method->dump_name_as_ascii(out); 4635 out->print(" %d %d", entry_bci, comp_level); 4636 out->print(" inline %d", sub->count()); 4637 sub->dump_replay_data(out, -1); 4638 out->cr(); 4639 } 4640 } 4641 4642 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) { 4643 if (n1->Opcode() < n2->Opcode()) return -1; 4644 else if (n1->Opcode() > n2->Opcode()) return 1; 4645 4646 assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req()); 4647 for (uint i = 1; i < n1->req(); i++) { 4648 if (n1->in(i) < n2->in(i)) return -1; 4649 else if (n1->in(i) > n2->in(i)) return 1; 4650 } 4651 4652 return 0; 4653 } 4654 4655 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) { 4656 Node* n1 = *n1p; 4657 Node* n2 = *n2p; 4658 4659 return cmp_expensive_nodes(n1, n2); 4660 } 4661 4662 void Compile::sort_expensive_nodes() { 4663 if (!expensive_nodes_sorted()) { 4664 _expensive_nodes.sort(cmp_expensive_nodes); 4665 } 4666 } 4667 4668 bool Compile::expensive_nodes_sorted() const { 4669 for (int i = 1; i < _expensive_nodes.length(); i++) { 4670 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i-1)) < 0) { 4671 return false; 4672 } 4673 } 4674 return true; 4675 } 4676 4677 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) { 4678 if (_expensive_nodes.length() == 0) { 4679 return false; 4680 } 4681 4682 assert(OptimizeExpensiveOps, "optimization off?"); 4683 4684 // Take this opportunity to remove dead nodes from the list 4685 int j = 0; 4686 for (int i = 0; i < _expensive_nodes.length(); i++) { 4687 Node* n = _expensive_nodes.at(i); 4688 if (!n->is_unreachable(igvn)) { 4689 assert(n->is_expensive(), "should be expensive"); 4690 _expensive_nodes.at_put(j, n); 4691 j++; 4692 } 4693 } 4694 _expensive_nodes.trunc_to(j); 4695 4696 // Then sort the list so that similar nodes are next to each other 4697 // and check for at least two nodes of identical kind with same data 4698 // inputs. 4699 sort_expensive_nodes(); 4700 4701 for (int i = 0; i < _expensive_nodes.length()-1; i++) { 4702 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i+1)) == 0) { 4703 return true; 4704 } 4705 } 4706 4707 return false; 4708 } 4709 4710 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) { 4711 if (_expensive_nodes.length() == 0) { 4712 return; 4713 } 4714 4715 assert(OptimizeExpensiveOps, "optimization off?"); 4716 4717 // Sort to bring similar nodes next to each other and clear the 4718 // control input of nodes for which there's only a single copy. 4719 sort_expensive_nodes(); 4720 4721 int j = 0; 4722 int identical = 0; 4723 int i = 0; 4724 bool modified = false; 4725 for (; i < _expensive_nodes.length()-1; i++) { 4726 assert(j <= i, "can't write beyond current index"); 4727 if (_expensive_nodes.at(i)->Opcode() == _expensive_nodes.at(i+1)->Opcode()) { 4728 identical++; 4729 _expensive_nodes.at_put(j++, _expensive_nodes.at(i)); 4730 continue; 4731 } 4732 if (identical > 0) { 4733 _expensive_nodes.at_put(j++, _expensive_nodes.at(i)); 4734 identical = 0; 4735 } else { 4736 Node* n = _expensive_nodes.at(i); 4737 igvn.replace_input_of(n, 0, NULL); 4738 igvn.hash_insert(n); 4739 modified = true; 4740 } 4741 } 4742 if (identical > 0) { 4743 _expensive_nodes.at_put(j++, _expensive_nodes.at(i)); 4744 } else if (_expensive_nodes.length() >= 1) { 4745 Node* n = _expensive_nodes.at(i); 4746 igvn.replace_input_of(n, 0, NULL); 4747 igvn.hash_insert(n); 4748 modified = true; 4749 } 4750 _expensive_nodes.trunc_to(j); 4751 if (modified) { 4752 igvn.optimize(); 4753 } 4754 } 4755 4756 void Compile::add_expensive_node(Node * n) { 4757 assert(!_expensive_nodes.contains(n), "duplicate entry in expensive list"); 4758 assert(n->is_expensive(), "expensive nodes with non-null control here only"); 4759 assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here"); 4760 if (OptimizeExpensiveOps) { 4761 _expensive_nodes.append(n); 4762 } else { 4763 // Clear control input and let IGVN optimize expensive nodes if 4764 // OptimizeExpensiveOps is off. 4765 n->set_req(0, NULL); 4766 } 4767 } 4768 4769 /** 4770 * Track coarsened Lock and Unlock nodes. 4771 */ 4772 4773 class Lock_List : public Node_List { 4774 uint _origin_cnt; 4775 public: 4776 Lock_List(Arena *a, uint cnt) : Node_List(a), _origin_cnt(cnt) {} 4777 uint origin_cnt() const { return _origin_cnt; } 4778 }; 4779 4780 void Compile::add_coarsened_locks(GrowableArray<AbstractLockNode*>& locks) { 4781 int length = locks.length(); 4782 if (length > 0) { 4783 // Have to keep this list until locks elimination during Macro nodes elimination. 4784 Lock_List* locks_list = new (comp_arena()) Lock_List(comp_arena(), length); 4785 for (int i = 0; i < length; i++) { 4786 AbstractLockNode* lock = locks.at(i); 4787 assert(lock->is_coarsened(), "expecting only coarsened AbstractLock nodes, but got '%s'[%d] node", lock->Name(), lock->_idx); 4788 locks_list->push(lock); 4789 } 4790 _coarsened_locks.append(locks_list); 4791 } 4792 } 4793 4794 void Compile::remove_useless_coarsened_locks(Unique_Node_List& useful) { 4795 int count = coarsened_count(); 4796 for (int i = 0; i < count; i++) { 4797 Node_List* locks_list = _coarsened_locks.at(i); 4798 for (uint j = 0; j < locks_list->size(); j++) { 4799 Node* lock = locks_list->at(j); 4800 assert(lock->is_AbstractLock(), "sanity"); 4801 if (!useful.member(lock)) { 4802 locks_list->yank(lock); 4803 } 4804 } 4805 } 4806 } 4807 4808 void Compile::remove_coarsened_lock(Node* n) { 4809 if (n->is_AbstractLock()) { 4810 int count = coarsened_count(); 4811 for (int i = 0; i < count; i++) { 4812 Node_List* locks_list = _coarsened_locks.at(i); 4813 locks_list->yank(n); 4814 } 4815 } 4816 } 4817 4818 bool Compile::coarsened_locks_consistent() { 4819 int count = coarsened_count(); 4820 for (int i = 0; i < count; i++) { 4821 bool unbalanced = false; 4822 bool modified = false; // track locks kind modifications 4823 Lock_List* locks_list = (Lock_List*)_coarsened_locks.at(i); 4824 uint size = locks_list->size(); 4825 if (size == 0) { 4826 unbalanced = false; // All locks were eliminated - good 4827 } else if (size != locks_list->origin_cnt()) { 4828 unbalanced = true; // Some locks were removed from list 4829 } else { 4830 for (uint j = 0; j < size; j++) { 4831 Node* lock = locks_list->at(j); 4832 // All nodes in group should have the same state (modified or not) 4833 if (!lock->as_AbstractLock()->is_coarsened()) { 4834 if (j == 0) { 4835 // first on list was modified, the rest should be too for consistency 4836 modified = true; 4837 } else if (!modified) { 4838 // this lock was modified but previous locks on the list were not 4839 unbalanced = true; 4840 break; 4841 } 4842 } else if (modified) { 4843 // previous locks on list were modified but not this lock 4844 unbalanced = true; 4845 break; 4846 } 4847 } 4848 } 4849 if (unbalanced) { 4850 // unbalanced monitor enter/exit - only some [un]lock nodes were removed or modified 4851 #ifdef ASSERT 4852 if (PrintEliminateLocks) { 4853 tty->print_cr("=== unbalanced coarsened locks ==="); 4854 for (uint l = 0; l < size; l++) { 4855 locks_list->at(l)->dump(); 4856 } 4857 } 4858 #endif 4859 record_failure(C2Compiler::retry_no_locks_coarsening()); 4860 return false; 4861 } 4862 } 4863 return true; 4864 } 4865 4866 /** 4867 * Remove the speculative part of types and clean up the graph 4868 */ 4869 void Compile::remove_speculative_types(PhaseIterGVN &igvn) { 4870 if (UseTypeSpeculation) { 4871 Unique_Node_List worklist; 4872 worklist.push(root()); 4873 int modified = 0; 4874 // Go over all type nodes that carry a speculative type, drop the 4875 // speculative part of the type and enqueue the node for an igvn 4876 // which may optimize it out. 4877 for (uint next = 0; next < worklist.size(); ++next) { 4878 Node *n = worklist.at(next); 4879 if (n->is_Type()) { 4880 TypeNode* tn = n->as_Type(); 4881 const Type* t = tn->type(); 4882 const Type* t_no_spec = t->remove_speculative(); 4883 if (t_no_spec != t) { 4884 bool in_hash = igvn.hash_delete(n); 4885 assert(in_hash, "node should be in igvn hash table"); 4886 tn->set_type(t_no_spec); 4887 igvn.hash_insert(n); 4888 igvn._worklist.push(n); // give it a chance to go away 4889 modified++; 4890 } 4891 } 4892 // Iterate over outs - endless loops is unreachable from below 4893 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 4894 Node *m = n->fast_out(i); 4895 if (not_a_node(m)) { 4896 continue; 4897 } 4898 worklist.push(m); 4899 } 4900 } 4901 // Drop the speculative part of all types in the igvn's type table 4902 igvn.remove_speculative_types(); 4903 if (modified > 0) { 4904 igvn.optimize(); 4905 } 4906 #ifdef ASSERT 4907 // Verify that after the IGVN is over no speculative type has resurfaced 4908 worklist.clear(); 4909 worklist.push(root()); 4910 for (uint next = 0; next < worklist.size(); ++next) { 4911 Node *n = worklist.at(next); 4912 const Type* t = igvn.type_or_null(n); 4913 assert((t == NULL) || (t == t->remove_speculative()), "no more speculative types"); 4914 if (n->is_Type()) { 4915 t = n->as_Type()->type(); 4916 assert(t == t->remove_speculative(), "no more speculative types"); 4917 } 4918 // Iterate over outs - endless loops is unreachable from below 4919 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 4920 Node *m = n->fast_out(i); 4921 if (not_a_node(m)) { 4922 continue; 4923 } 4924 worklist.push(m); 4925 } 4926 } 4927 igvn.check_no_speculative_types(); 4928 #endif 4929 } 4930 } 4931 4932 // Auxiliary methods to support randomized stressing/fuzzing. 4933 4934 int Compile::random() { 4935 _stress_seed = os::next_random(_stress_seed); 4936 return static_cast<int>(_stress_seed); 4937 } 4938 4939 // This method can be called the arbitrary number of times, with current count 4940 // as the argument. The logic allows selecting a single candidate from the 4941 // running list of candidates as follows: 4942 // int count = 0; 4943 // Cand* selected = null; 4944 // while(cand = cand->next()) { 4945 // if (randomized_select(++count)) { 4946 // selected = cand; 4947 // } 4948 // } 4949 // 4950 // Including count equalizes the chances any candidate is "selected". 4951 // This is useful when we don't have the complete list of candidates to choose 4952 // from uniformly. In this case, we need to adjust the randomicity of the 4953 // selection, or else we will end up biasing the selection towards the latter 4954 // candidates. 4955 // 4956 // Quick back-envelope calculation shows that for the list of n candidates 4957 // the equal probability for the candidate to persist as "best" can be 4958 // achieved by replacing it with "next" k-th candidate with the probability 4959 // of 1/k. It can be easily shown that by the end of the run, the 4960 // probability for any candidate is converged to 1/n, thus giving the 4961 // uniform distribution among all the candidates. 4962 // 4963 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large. 4964 #define RANDOMIZED_DOMAIN_POW 29 4965 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW) 4966 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1) 4967 bool Compile::randomized_select(int count) { 4968 assert(count > 0, "only positive"); 4969 return (random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count); 4970 } 4971 4972 CloneMap& Compile::clone_map() { return _clone_map; } 4973 void Compile::set_clone_map(Dict* d) { _clone_map._dict = d; } 4974 4975 void NodeCloneInfo::dump() const { 4976 tty->print(" {%d:%d} ", idx(), gen()); 4977 } 4978 4979 void CloneMap::clone(Node* old, Node* nnn, int gen) { 4980 uint64_t val = value(old->_idx); 4981 NodeCloneInfo cio(val); 4982 assert(val != 0, "old node should be in the map"); 4983 NodeCloneInfo cin(cio.idx(), gen + cio.gen()); 4984 insert(nnn->_idx, cin.get()); 4985 #ifndef PRODUCT 4986 if (is_debug()) { 4987 tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen()); 4988 } 4989 #endif 4990 } 4991 4992 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) { 4993 NodeCloneInfo cio(value(old->_idx)); 4994 if (cio.get() == 0) { 4995 cio.set(old->_idx, 0); 4996 insert(old->_idx, cio.get()); 4997 #ifndef PRODUCT 4998 if (is_debug()) { 4999 tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen()); 5000 } 5001 #endif 5002 } 5003 clone(old, nnn, gen); 5004 } 5005 5006 int CloneMap::max_gen() const { 5007 int g = 0; 5008 DictI di(_dict); 5009 for(; di.test(); ++di) { 5010 int t = gen(di._key); 5011 if (g < t) { 5012 g = t; 5013 #ifndef PRODUCT 5014 if (is_debug()) { 5015 tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key)); 5016 } 5017 #endif 5018 } 5019 } 5020 return g; 5021 } 5022 5023 void CloneMap::dump(node_idx_t key) const { 5024 uint64_t val = value(key); 5025 if (val != 0) { 5026 NodeCloneInfo ni(val); 5027 ni.dump(); 5028 } 5029 } 5030 5031 // Move Allocate nodes to the start of the list 5032 void Compile::sort_macro_nodes() { 5033 int count = macro_count(); 5034 int allocates = 0; 5035 for (int i = 0; i < count; i++) { 5036 Node* n = macro_node(i); 5037 if (n->is_Allocate()) { 5038 if (i != allocates) { 5039 Node* tmp = macro_node(allocates); 5040 _macro_nodes.at_put(allocates, n); 5041 _macro_nodes.at_put(i, tmp); 5042 } 5043 allocates++; 5044 } 5045 } 5046 } 5047 5048 void Compile::print_method(CompilerPhaseType cpt, int level, Node* n) { 5049 EventCompilerPhase event; 5050 if (event.should_commit()) { 5051 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, cpt, C->_compile_id, level); 5052 } 5053 #ifndef PRODUCT 5054 ResourceMark rm; 5055 stringStream ss; 5056 ss.print_raw(CompilerPhaseTypeHelper::to_description(cpt)); 5057 if (n != nullptr) { 5058 ss.print(": %d %s ", n->_idx, NodeClassNames[n->Opcode()]); 5059 } 5060 5061 const char* name = ss.as_string(); 5062 if (should_print_igv(level)) { 5063 _igv_printer->print_method(name, level); 5064 } 5065 if (should_print_phase(cpt)) { 5066 print_ideal_ir(CompilerPhaseTypeHelper::to_name(cpt)); 5067 } 5068 #endif 5069 C->_latest_stage_start_counter.stamp(); 5070 } 5071 5072 // Only used from CompileWrapper 5073 void Compile::begin_method() { 5074 #ifndef PRODUCT 5075 if (_method != NULL && should_print_igv(1)) { 5076 _igv_printer->begin_method(); 5077 } 5078 #endif 5079 C->_latest_stage_start_counter.stamp(); 5080 } 5081 5082 // Only used from CompileWrapper 5083 void Compile::end_method() { 5084 EventCompilerPhase event; 5085 if (event.should_commit()) { 5086 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, 1); 5087 } 5088 5089 #ifndef PRODUCT 5090 if (_method != NULL && should_print_igv(1)) { 5091 _igv_printer->end_method(); 5092 } 5093 #endif 5094 } 5095 5096 bool Compile::should_print_phase(CompilerPhaseType cpt) { 5097 #ifndef PRODUCT 5098 if ((_directive->ideal_phase_mask() & CompilerPhaseTypeHelper::to_bitmask(cpt)) != 0) { 5099 return true; 5100 } 5101 #endif 5102 return false; 5103 } 5104 5105 bool Compile::should_print_igv(int level) { 5106 #ifndef PRODUCT 5107 if (PrintIdealGraphLevel < 0) { // disabled by the user 5108 return false; 5109 } 5110 5111 bool need = directive()->IGVPrintLevelOption >= level; 5112 if (need && !_igv_printer) { 5113 _igv_printer = IdealGraphPrinter::printer(); 5114 _igv_printer->set_compile(this); 5115 } 5116 return need; 5117 #else 5118 return false; 5119 #endif 5120 } 5121 5122 #ifndef PRODUCT 5123 IdealGraphPrinter* Compile::_debug_file_printer = NULL; 5124 IdealGraphPrinter* Compile::_debug_network_printer = NULL; 5125 5126 // Called from debugger. Prints method to the default file with the default phase name. 5127 // This works regardless of any Ideal Graph Visualizer flags set or not. 5128 void igv_print() { 5129 Compile::current()->igv_print_method_to_file(); 5130 } 5131 5132 // Same as igv_print() above but with a specified phase name. 5133 void igv_print(const char* phase_name) { 5134 Compile::current()->igv_print_method_to_file(phase_name); 5135 } 5136 5137 // Called from debugger. Prints method with the default phase name to the default network or the one specified with 5138 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument. 5139 // This works regardless of any Ideal Graph Visualizer flags set or not. 5140 void igv_print(bool network) { 5141 if (network) { 5142 Compile::current()->igv_print_method_to_network(); 5143 } else { 5144 Compile::current()->igv_print_method_to_file(); 5145 } 5146 } 5147 5148 // Same as igv_print(bool network) above but with a specified phase name. 5149 void igv_print(bool network, const char* phase_name) { 5150 if (network) { 5151 Compile::current()->igv_print_method_to_network(phase_name); 5152 } else { 5153 Compile::current()->igv_print_method_to_file(phase_name); 5154 } 5155 } 5156 5157 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set. 5158 void igv_print_default() { 5159 Compile::current()->print_method(PHASE_DEBUG, 0); 5160 } 5161 5162 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay. 5163 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow 5164 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not. 5165 void igv_append() { 5166 Compile::current()->igv_print_method_to_file("Debug", true); 5167 } 5168 5169 // Same as igv_append() above but with a specified phase name. 5170 void igv_append(const char* phase_name) { 5171 Compile::current()->igv_print_method_to_file(phase_name, true); 5172 } 5173 5174 void Compile::igv_print_method_to_file(const char* phase_name, bool append) { 5175 const char* file_name = "custom_debug.xml"; 5176 if (_debug_file_printer == NULL) { 5177 _debug_file_printer = new IdealGraphPrinter(C, file_name, append); 5178 } else { 5179 _debug_file_printer->update_compiled_method(C->method()); 5180 } 5181 tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name); 5182 _debug_file_printer->print(phase_name, (Node*)C->root()); 5183 } 5184 5185 void Compile::igv_print_method_to_network(const char* phase_name) { 5186 if (_debug_network_printer == NULL) { 5187 _debug_network_printer = new IdealGraphPrinter(C); 5188 } else { 5189 _debug_network_printer->update_compiled_method(C->method()); 5190 } 5191 tty->print_cr("Method printed over network stream to IGV"); 5192 _debug_network_printer->print(phase_name, (Node*)C->root()); 5193 } 5194 #endif 5195 5196 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) { 5197 if (type != NULL && phase->type(value)->higher_equal(type)) { 5198 return value; 5199 } 5200 Node* result = NULL; 5201 if (bt == T_BYTE) { 5202 result = phase->transform(new LShiftINode(value, phase->intcon(24))); 5203 result = new RShiftINode(result, phase->intcon(24)); 5204 } else if (bt == T_BOOLEAN) { 5205 result = new AndINode(value, phase->intcon(0xFF)); 5206 } else if (bt == T_CHAR) { 5207 result = new AndINode(value,phase->intcon(0xFFFF)); 5208 } else { 5209 assert(bt == T_SHORT, "unexpected narrow type"); 5210 result = phase->transform(new LShiftINode(value, phase->intcon(16))); 5211 result = new RShiftINode(result, phase->intcon(16)); 5212 } 5213 if (transform_res) { 5214 result = phase->transform(result); 5215 } 5216 return result; 5217 } 5218