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